text:
/*!
 * FlexCss.OffCanvas
 * Licensed under the MIT License (MIT)
 * Copyright (c) 2015 David Heidrich, BowlingX <me@bowlingx.com>
 */

import Settings from './util/Settings';
import Util from './util/Util';
import Event from './util/Event';
import FixedWindow from './lib/FixedWindow';

/**
 * @type {string}
 */
const ATTR_CLOSE_SIDEBAR = 'data-close-offcanvas';

/**
 * @type {string}
 */
const ATTR_TARGET = 'data-offcanvas';
/**
 * @type {string}
 */
const INIT_CLASS = 'init';
/**
 * @type {string}
 */
const OPEN_CLASS = 'open';
/**
 * @type {number}
 */
const HIDE_FACTOR = 3;

/**
 * @type {string}
 */
export const EVENT_TOGGLE = 'flexcss.offcanvas.toggle';

/**
 * A OffCanvas Implementation
 */
class OffCanvas {

    /**
     * Creates an off-canvas navigation
     * @param {HTMLElement|String} NavigationId
     * @param {HTMLElement|String} Darkener
     * @param {int} factor positive will expect right sidebar, positive left
     * @param {bool} [disableTouch] if true all touch events are disabled
     * @constructor
     */
    constructor(NavigationId, Darkener, factor, disableTouch) {
        const doc = global.document;
        let touchedX = 0;
        const navigationContainer = NavigationId instanceof HTMLElement ?
            NavigationId : doc.getElementById(NavigationId);
        const darkener = Darkener instanceof HTMLElement ? Darkener : doc.getElementById(Darkener);
        const DARKENER_CLASS_TOGGLE = `toggle-${darkener.id}` || 'darkener';
        const DARKENER_CLASS_INSTANT_TOGGLE = `${DARKENER_CLASS_TOGGLE}-open`;

        const shouldNotTouch = () => {
            return window.innerWidth >= Settings.get().touchMoveBreakpointOffCanvas;
        };

        if (!darkener || !navigationContainer) {
            throw new Error('Could not find needed elements (Darkener and/or NavigationId)');
        }

        this.darkener = darkener;
        this.darkenerClassToggle = DARKENER_CLASS_TOGGLE;
        this.darkenerClassToggleInstant = DARKENER_CLASS_INSTANT_TOGGLE;
        this.globalToggleClass = Settings.get().canvasToggledClass;

        this.navigationContainer = navigationContainer;
        this.navigationContainerId = navigationContainer.id;

        // create id if id does not exist
        if (!this.navigationContainerId) {
            this.navigationContainerId = Util.guid();
            navigationContainer.id = this.navigationContainerId;
        }

        if (!disableTouch) {
            navigationContainer.addEventListener('touchstart', (e) => {
                if (shouldNotTouch()) {
                    return;
                }
                touchedX = e.touches[0].clientX;
                navigationContainer.mustHide = false;
            });
            navigationContainer.addEventListener('touchmove', (e) => {
                if (shouldNotTouch()) {
                    return;
                }
                const { clientX } = e.touches[0];
                const target = navigationContainer;
                const style = target.style;
                const calcX = touchedX - clientX;
                const bounds = target.getBoundingClientRect();
                const compare = factor > 0 ? calcX <= 0 : calcX >= 0;
                if (compare) {
                    style.transition = 'transform 0s ease';
                    style.webkitTransition = '-webkit-transform 0s ease';
                    target.mustHide = factor > 0 ? calcX * -1 >
                    bounds.width / HIDE_FACTOR : calcX > bounds.width / HIDE_FACTOR;
                    const transform = `translate3d(${calcX * -1}px,0,0)`;
                    style.transform = transform;
                    style.webkitTransform = transform;
                }
            });
            navigationContainer.addEventListener('touchend', () => {
                if (shouldNotTouch()) {
                    return;
                }
                const target = navigationContainer;
                const style = target.style;
                if (target.mustHide) {
                    const width = target.getBoundingClientRect().width * factor;
                    style.transition = 'transform .2s ease';
                    style.webkitTransition = '-webkit-transform .2s ease';
                    const transform = `translate3d(${width}px,0,0)`;
                    style.transform = transform;
                    style.webkitTransform = transform;
                    this._remove().then(() => {
                        this.resetTransform(style);
                    });
                    this._removeInstant();
                } else {
                    this.resetTransform(style);
                }
            });
        }
    }

    /**
     * @param {Object} s
     */
    resetTransform(s) {
        s.transform = '';
        s.transition = '';
        s.webkitTransform = '';
        s.webkitTransition = '';
    }

    /**
     * @param {Object} [event]
     * @private
     */
    _remove(event) {
        return new Promise((resolve) => {
            Util.addEventOnce(Settings.getTransitionEvent(), this.navigationContainer, function scheduler(e) {
                if (e.target !== this.navigationContainer) {
                    return Util.addEventOnce(Settings.getTransitionEvent(),
                        this.navigationContainer, scheduler.bind(this));
                }
                requestAnimationFrame(() => {
                    OffCanvas.currentOpen = null;
                    const docCls = global.document.documentElement.classList;
                    docCls.remove(this.darkenerClassToggle);
                    docCls.remove(this.globalToggleClass);
                    if (!!event) {
                        Event.dispatchAndFire(this.navigationContainer, EVENT_TOGGLE);
                    }
                    resolve();
                });
            }.bind(this));
        });
    }

    /**
     * @private
     */
    _removeInstant() {
        this.navigationContainer.classList.remove(OPEN_CLASS);
        global.document.documentElement.classList.remove(this.darkenerClassToggleInstant);
        this.darkener.classList.remove(INIT_CLASS);
        FixedWindow.getInstance().close();
    }

    /**
     * Toggles a an off-canvas element
     * @param [e]
     * @private
     */
    toggle(e) {
        if (e) {
            e.preventDefault();
        }
        this.resetTransform(this.navigationContainer.style);
        const darkenerClass = this.darkener.classList;
        const DARKENER_CLASS_TOGGLE = this.darkenerClassToggle;
        const DARKENER_CLASS_INSTANT_TOGGLE = this.darkenerClassToggleInstant;
        const navigationControllerClassList = this.navigationContainer.classList;
        if (!OffCanvas.currentOpen) {
            Util.addEventOnce(Settings.getTransitionEvent(), this.navigationContainer, () => {
                if (!!e) {
                    Event.dispatchAndFire(this.navigationContainer, EVENT_TOGGLE);
                }
            });
            OffCanvas.currentOpen = this;
            FixedWindow.getInstance().open(this, this.navigationContainer);
            const docElementCls = global.document.documentElement.classList;
            docElementCls.add(this.globalToggleClass);
            docElementCls.add(DARKENER_CLASS_INSTANT_TOGGLE);
            docElementCls.add(DARKENER_CLASS_TOGGLE);
            darkenerClass.add(INIT_CLASS);
            navigationControllerClassList.add(OPEN_CLASS);
        } else {
            return this.close(e);
        }
    }

    close(event) {
        if (this.navigationContainer.classList.contains(OPEN_CLASS)) {
            const promise = this._remove(event);
            this._removeInstant();
            return promise;
        }
        return new Promise(r => r());
    }

    /**
     * Register events
     * @param [delegate]
     */
    registerEvents(delegate) {
        const thisDelegate = delegate || global.document;
        FixedWindow.getInstance().addScreenConstraint(OffCanvas, (width) => width < Settings.get().smallBreakpoint);
        thisDelegate.addEventListener(Settings.getTabEvent(), (e) => {
            if (OffCanvas.currentOpen && OffCanvas.currentOpen !== this) {
                return;
            }
            const id = this.navigationContainerId;
            const validTarget = e.target.getAttribute(ATTR_TARGET) === id;
            if (!Util.isPartOfNode(e.target, this.navigationContainer)) {
                if (validTarget || (OffCanvas.currentOpen === this && e.target === this.darkener)) {
                    this.toggle(e);
                }
            } else {
                if (e.target.hasAttribute(ATTR_CLOSE_SIDEBAR)) {
                    this.toggle(e);
                }
            }
        });
    }
}

OffCanvas.currentOpen = null;

export default OffCanvas;


text:
<?php

/**
 * @namespace
 */
namespace Pop\Auth;

/**
 * ACL class
 *
 * @category   Pop
 * @package    Pop_Auth
 * @author     Nick Sagona, III <nick@popphp.org>
 * @copyright  Copyright (c) 2009-2014 Moc 10 Media, LLC. (http://www.moc10media.com)
 * @license    http://www.popphp.org/license     New BSD License
 * @version    1.7.0
 */
class Acl
{

    /**
     * Array of roles
     * @var array
     */
    protected $roles = array();

    /**
     * Array of resources
     * @var array
     */
    protected $resources = array();

    /**
     * Array of allowed roles, resources and permissions
     * @var array
     */
    protected $allowed = array();

    /**
     * Array of denied roles, resources and permissions
     * @var array
     */
    protected $denied = array();

    /**
     * Constructor
     *
     * Instantiate the auth object
     *
     * @param  mixed $roles
     * @param  mixed $resources
     * @return \Pop\Auth\Acl
     */
    public function __construct($roles = null, $resources = null)
    {
        if (null !== $roles) {
            $this->addRoles($roles);
        }

        if (null !== $resources) {
            $this->addResources($resources);
        }
    }

    /**
     * Static method to instantiate the ACL object and return itself
     * to facilitate chaining methods together.
     *
     * @param  mixed $roles
     * @param  mixed $resources
     * @return \Pop\Auth\Acl
     */
    public static function factory($roles = null, $resources = null)
    {
        return new self($roles, $resources);
    }

    /**
     * Method to get a role
     *
     * @param  string $role
     * @return \Pop\Auth\Role
     */
    public function getRole($role)
    {
        return (isset($this->roles[$role])) ? $this->roles[$role] : null;
    }

    /**
     * Method to is if a role has been added
     *
     * @param  string $role
     * @return boolean
     */
    public function hasRole($role)
    {
        return (isset($this->roles[$role]));
    }

    /**
     * Method to add a role
     *
     * @param  mixed $role
     * @return \Pop\Auth\Acl
     */
    public function addRole($role)
    {
        $this->addRoles($role);
        return $this;
    }

    /**
     * Method to add roles
     *
     * @param  mixed $roles
     * @return \Pop\Auth\Acl
     */
    public function addRoles($roles)
    {
        if (is_array($roles)) {
            foreach ($roles as $r) {
                if ($r instanceof Role) {
                    $this->roles[$r->getName()] = $r;
                } else {
                    $this->roles[$r] = Role::factory($r);
                }
            }
        } else if ($roles instanceof Role) {
            $this->roles[$roles->getName()] = $roles;
        } else {
            $this->roles[$roles] = Role::factory($roles);
        }

        return $this;
    }

    /**
     * Method to get a resource
     *
     * @param  string $resource
     * @return \Pop\Auth\Resource
     */
    public function getResource($resource)
    {
        return (isset($this->resources[$resource])) ? $this->resources[$resource] : null;
    }

    /**
     * Method to is if a resource has been added
     *
     * @param  string $resource
     * @return boolean
     */
    public function hasResource($resource)
    {
        return (isset($this->resources[$resource]));
    }

    /**
     * Method to add a resource
     *
     * @param  mixed $resource
     * @return \Pop\Auth\Acl
     */
    public function addResource($resource)
    {
        $this->addResources($resource);
        return $this;
    }

    /**
     * Method to add a resource
     *
     * @param  mixed $resources
     * @return \Pop\Auth\Acl
     */
    public function addResources($resources)
    {
        if (is_array($resources)) {
            foreach ($resources as $r) {
                if ($r instanceof Resource) {
                    $this->resources[$r->getName()] = $r;
                } else {
                    $this->resources[$r] = Resource::factory($r);
                }
            }
        } else if ($resources instanceof Resource) {
            $this->resources[$resources->getName()] = $resources;
        } else {
            $this->resources[$resources] = Resource::factory($resources);
        }

        return $this;
    }

    /**
     * Method to allow a user role permission to a resource or resources
     *
     * @param  mixed  $roles
     * @param  mixed  $resources
     * @param  mixed  $permissions
     * @throws \Pop\Auth\Exception
     * @return \Pop\Auth\Acl
     */
    public function allow($roles, $resources = null, $permissions = null)
    {
        if (!is_array($roles)) {
            $roles = array($roles);
        }

        // Check if the roles has been added
        foreach ($roles as $role) {
            if (!isset($this->roles[$role])) {
                throw new Exception('Error: That role has not been added.');
            }

            if (!isset($this->allowed[$role])) {
                $this->allowed[$role] = array();
            }

            // Check if the resource(s) have been added
            if (null !== $resources) {
                if (!is_array($resources)) {
                    $resources = array($resources);
                }
                foreach ($resources as $resource) {
                    if (!isset($this->resources[$resource])) {
                        $this->addResource($resource);
                    }
                    $this->allowed[$role][$resource] = array();
                    if (null != $permissions) {
                        if (!is_array($permissions)) {
                            $permissions = array($permissions);
                        }
                        foreach ($permissions as $permission) {
                            if (!$this->roles[$role]->hasPermission($permission)) {
                                throw new Exception("Error: That role does not have the permission '" . $permission . "'.");
                            }
                            $this->allowed[$role][$resource][] = $permission;
                        }
                    }
                }
            }
        }

        return $this;
    }

    /**
     * Method to remove an allow rule
     *
     * @param  mixed  $roles
     * @param  mixed  $resources
     * @param  mixed  $permissions
     * @throws \Pop\Auth\Exception
     * @return \Pop\Auth\Acl
     */
    public function removeAllow($roles, $resources = null, $permissions = null)
    {
        if (!is_array($roles)) {
            $roles = array($roles);
        }

        // Check if the roles has been added
        foreach ($roles as $role) {
            if (!isset($this->roles[$role])) {
                throw new Exception('Error: That role has not been added.');
            }

            if (!isset($this->allowed[$role])) {
                throw new Exception('Error: That role has no allow rules associated with it.');
            }

            // Check if the resource(s) have been added
            if (null !== $resources) {
                if (!is_array($resources)) {
                    $resources = array($resources);
                }
                foreach ($resources as $resource) {
                    if (!isset($this->resources[$resource])) {
                        $this->addResource($resource);
                    }
                    if (isset($this->allowed[$role][$resource])) {
                        if (null != $permissions) {
                            if (!is_array($permissions)) {
                                $permissions = array($permissions);
                            }
                            foreach ($permissions as $permission) {
                                if (in_array($permission, $this->allowed[$role][$resource])) {
                                    $key = array_search($permission, $this->allowed[$role][$resource]);
                                    unset($this->allowed[$role][$resource][$key]);
                                }
                            }
                        } else {
                            unset($this->allowed[$role][$resource]);
                        }
                    }
                }
            } else {
                unset($this->allowed[$role]);
            }
        }

        return $this;
    }

    /**
     * Method to deny a user role permission to a resource or resources
     *
     * @param  mixed $roles
     * @param  mixed $resources
     * @param  mixed $permissions
     * @throws \Pop\Auth\Exception
     * @return \Pop\Auth\Acl
     */
    public function deny($roles, $resources = null, $permissions = null)
    {
        if (!is_array($roles)) {
            $roles = array($roles);
        }

        // Check if the roles has been added
        foreach ($roles as $role) {
            if (!isset($this->roles[$role])) {
                throw new Exception('Error: That role has not been added.');
            }

            if (!isset($this->denied[$role])) {
                $this->denied[$role] = array();
            }

            // Check if the resource(s) have been added
            if (null !== $resources) {
                if (!is_array($resources)) {
                    $resources = array($resources);
                }
                foreach ($resources as $resource) {
                    if (!isset($this->resources[$resource])) {
                        $this->addResource($resource);
                    }
                    $this->denied[$role][$resource] = array();
                    if (null != $permissions) {
                        if (!is_array($permissions)) {
                            $permissions = array($permissions);
                        }
                        foreach ($permissions as $permission) {
                            if (!$this->roles[$role]->hasPermission($permission)) {
                                throw new Exception("Error: That role does not have the permission '" . $permission . "'.");
                            }
                            $this->denied[$role][$resource][] = $permission;
                        }
                    }
                }
            }
        }

        return $this;
    }

    /**
     * Method to remove a deny rule
     *
     * @param  mixed $roles
     * @param  mixed $resources
     * @param  mixed $permissions
     * @throws \Pop\Auth\Exception
     * @return \Pop\Auth\Acl
     */
    public function removeDeny($roles, $resources = null, $permissions = null)
    {
        if (!is_array($roles)) {
            $roles = array($roles);
        }

        // Check if the roles has been added
        foreach ($roles as $role) {
            if (!isset($this->roles[$role])) {
                throw new Exception('Error: That role has not been added.');
            }

            if (!isset($this->denied[$role])) {
                throw new Exception('Error: That role has no allow rules associated with it.');
            }

            // Check if the resource(s) have been added
            if (null !== $resources) {
                if (!is_array($resources)) {
                    $resources = array($resources);
                }
                foreach ($resources as $resource) {
                    if (!isset($this->resources[$resource])) {
                        $this->addResource($resource);
                    }
                    if (isset($this->denied[$role][$resource])) {
                        if (null != $permissions) {
                            if (!is_array($permissions)) {
                                $permissions = array($permissions);
                            }
                            foreach ($permissions as $permission) {
                                if (in_array($permission, $this->denied[$role][$resource])) {
                                    $key = array_search($permission, $this->denied[$role][$resource]);
                                    unset($this->denied[$role][$resource][$key]);
                                }
                            }
                        } else {
                            unset($this->denied[$role][$resource]);
                        }
                    }
                }
            } else {
                unset($this->denied[$role]);
            }
        }

        return $this;
    }

    /**
     * Method to determine if the user is allowed
     *
     * @param  \Pop\Auth\Role $user
     * @param  string         $resource
     * @param  string         $permission
     * @throws \Pop\Auth\Exception
     * @return boolean
     */
    public function isAllowed(\Pop\Auth\Role $user, $resource = null, $permission = null)
    {
        $result = false;

        if (!isset($this->roles[$user->getName()])) {
            throw new Exception('Error: That role has not been added.');
        }

        if ((null !== $resource) && !isset($this->resources[$resource])) {
            $this->addResource($resource);
        }

        if (!$this->isDenied($user, $resource, $permission)) {
            if ((null !== $resource) && (null !== $permission)) {
                // Full access, no resource or permission defined OR
                // Full access to the resource if no permission defined OR
                // determine access based on resource and permission passed
                if ((isset($this->allowed[$user->getName()]) && (count($this->allowed[$user->getName()]) == 0)) ||
                    (isset($this->allowed[$user->getName()]) && isset($this->allowed[$user->getName()][$resource]) && (count($this->allowed[$user->getName()][$resource]) == 0)) ||
                    ($user->hasPermission($permission) &&
                     isset($this->allowed[$user->getName()]) &&
                     isset($this->allowed[$user->getName()][$resource]) &&
                     in_array($permission, $this->allowed[$user->getName()][$resource]))) {
                    $result = true;
                }
            } else if (null !== $resource) {
                // Full access, no resource defined OR
                // determine access based on resource passed
                if ((isset($this->allowed[$user->getName()]) && (count($this->allowed[$user->getName()]) == 0)) ||
                    (isset($this->allowed[$user->getName()]) &&
                    isset($this->allowed[$user->getName()][$resource]))) {
                    $result = true;
                }
            } else {
                if (isset($this->allowed[$user->getName()])) {
                    $result = true;
                }
            }
        }

        return $result;
    }

    /**
     * Method to determine if the user is denied
     *
     * @param  \Pop\Auth\Role $user
     * @param  string         $resource
     * @param  string         $permission
     * @throws \Pop\Auth\Exception
     * @return boolean
     */
    public function isDenied(\Pop\Auth\Role $user, $resource = null, $permission = null)
    {
        $result = false;

        if (!isset($this->roles[$user->getName()])) {
            throw new Exception('Error: That role has not been added.');
        }

        if ((null !== $resource) && !isset($this->resources[$resource])) {
            $this->addResource($resource);
        }

        // Check if the user, resource and/or permission is denied
        if (isset($this->denied[$user->getName()])) {
            if (count($this->denied[$user->getName()]) > 0) {
                if ((null !== $resource) && array_key_exists($resource, $this->denied[$user->getName()])) {
                    if (count($this->denied[$user->getName()][$resource]) > 0) {
                        if ((null !== $permission) && in_array($permission, $this->denied[$user->getName()][$resource])) {
                            $result = true;
                        }
                    } else {
                        $result = true;
                    }
                }
            } else {
                $result = true;
            }
        }

        return $result;
    }

}

redpajama_set_name: RedPajamaGithub


text:
class Profile;

namespace autofill {
class AutofillWebDataService;
}

namespace password_manager {
class PasswordStore;
}

namespace syncer {
class DeviceInfoTracker;
class SyncApiComponentFactory;
class SyncService;
}

namespace browser_sync {

class ChromeSyncClient : public syncer::SyncClient {
 public:
  explicit ChromeSyncClient(Profile* profile);
  ~ChromeSyncClient() override;

  // SyncClient implementation.
  void Initialize() override;
  syncer::SyncService* GetSyncService() override;
  PrefService* GetPrefService() override;
  bookmarks::BookmarkModel* GetBookmarkModel() override;
  favicon::FaviconService* GetFaviconService() override;
  history::HistoryService* GetHistoryService() override;
  base::Closure GetPasswordStateChangedCallback() override;
  syncer::SyncApiComponentFactory::RegisterDataTypesMethod
  GetRegisterPlatformTypesCallback() override;
  autofill::PersonalDataManager* GetPersonalDataManager() override;
  invalidation::InvalidationService* GetInvalidationService() override;
  BookmarkUndoService* GetBookmarkUndoServiceIfExists() override;
  scoped_refptr<syncer::ExtensionsActivity> GetExtensionsActivity() override;
  sync_sessions::SyncSessionsClient* GetSyncSessionsClient() override;
  base::WeakPtr<syncer::SyncableService> GetSyncableServiceForType(
      syncer::ModelType type) override;
  base::WeakPtr<syncer::ModelTypeSyncBridge> GetSyncBridgeForModelType(
      syncer::ModelType type) override;
  scoped_refptr<syncer::ModelSafeWorker> CreateModelWorkerForGroup(
      syncer::ModelSafeGroup group) override;
  syncer::SyncApiComponentFactory* GetSyncApiComponentFactory() override;

  // Helpers for overriding getters in tests.
  void SetSyncApiComponentFactoryForTesting(
      std::unique_ptr<syncer::SyncApiComponentFactory> component_factory);

  // Iterates over all of the profiles that have been loaded so far, and
  // extracts their tracker if present. If some profiles don't have trackers, no
  // indication is given in the passed vector.
  static void GetDeviceInfoTrackers(
      std::vector<const syncer::DeviceInfoTracker*>* trackers);

 private:
  // Register data types which are enabled on desktop platforms only.
  // |disabled_types| and |enabled_types| correspond only to those types
  // being explicitly disabled/enabled by the command line.
  void RegisterDesktopDataTypes(syncer::SyncService* sync_service,
                                syncer::ModelTypeSet disabled_types,
                                syncer::ModelTypeSet enabled_types);

  // Register data types which are enabled on Android platforms only.
  // |disabled_types| and |enabled_types| correspond only to those types
  // being explicitly disabled/enabled by the command line.
  void RegisterAndroidDataTypes(syncer::SyncService* sync_service,
                                syncer::ModelTypeSet disabled_types,
                                syncer::ModelTypeSet enabled_types);

  Profile* const profile_;

  // The sync api component factory in use by this client.
  std::unique_ptr<syncer::SyncApiComponentFactory> component_factory_;

  // Members that must be fetched on the UI thread but accessed on their
  // respective backend threads.
  scoped_refptr<autofill::AutofillWebDataService> web_data_service_;
  scoped_refptr<password_manager::PasswordStore> password_store_;

  std::unique_ptr<sync_sessions::SyncSessionsClient> sync_sessions_client_;

  // Generates and monitors the ExtensionsActivity object used by sync.
  ExtensionsActivityMonitor extensions_activity_monitor_;

  base::WeakPtrFactory<ChromeSyncClient> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(ChromeSyncClient);
};

}  // namespace browser_sync

#endif  // CHROME_BROWSER_SYNC_CHROME_SYNC_CLIENT_H__


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>intermol.tests.test_gromacs — InterMol 0.2a1 documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />

    <link rel="top" title="InterMol 0.2a1 documentation" href="../../../index.html"/>
        <link rel="up" title="Module code" href="../../index.html"/>

         InterMol

  <form id ="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Installation

Install with pip (coming soon!)

Install from source

Dependencies

Testing your installation

Contributing

Bug Reports

Code Style

Git Flow

intermol package

Subpackages

Submodules

Module contents

intermol.gromacs package

Submodules

Module contents

intermol.forces package

Submodules

Module contents

        InterMol

Docs »

Module code »

intermol.tests.test_gromacs

Source code for intermol.tests.test_gromacs

from collections import OrderedDict
from copy import copy
from glob import glob
import os
from pkg_resources import resource_filename

import logging
import numpy as np
from six import string_types
import sys

from intermol import convert
from testing_tools import (add_handler, remove_handler, summarize_results,
                           ENGINES)

logger = logging.getLogger('InterMolLog')
testing_logger = logging.getLogger('testing')
if not testing_logger.handlers:
    testing_logger.setLevel(logging.DEBUG)
    h = logging.StreamHandler()
    h.setLevel(logging.INFO)  # ignores DEBUG level for now
    f = logging.Formatter("%(levelname)s %(asctime)s %(message)s", "%Y-%m-%d %H:%M:%S")
    h.setFormatter(f)
    testing_logger.addHandler(h)

[docs]def gromacs(flags, test_type='unit'):
    """

    Args:
        args:
    Returns:

    """
    resource_dir = resource_filename('intermol',
                                     'tests/gromacs/{0}_tests'.format(test_type))

    gro_files = sorted(glob(os.path.join(resource_dir, '*/*.gro')))
    gro_files = [x for x in gro_files if not x.endswith('out.gro')]
    top_files = sorted(glob(os.path.join(resource_dir, '*/*.top')))
    names = [os.path.splitext(os.path.basename(gro))[0] for gro in gro_files]

    # The results of all conversions are stored in nested dictionaries:
    # results = {'gromacs': {'bond1: result, 'bond2: results...},
    #            'lammps': {'bond1: result, 'bond2: results...},
    #            ...}
    per_file_results = OrderedDict((k, None) for k in names)
    results = {engine: copy(per_file_results) for engine in ENGINES}

    unit_test_outputs = '{0}_test_outputs/from_gromacs'.format(test_type)
    basedir = os.path.join(os.path.dirname(__file__), unit_test_outputs)
    if not os.path.isdir(basedir):
        os.mkdir(basedir)

    for gro, top, name in zip(gro_files, top_files, names):
        testing_logger.info('Converting {0}'.format(name))
        odir = '{0}/{1}'.format(basedir, name)
        if not os.path.isdir(odir):
            os.mkdir(odir)
        h1, h2 = add_handler(odir)

        flags['gro_in'] = [gro, top]
        flags['odir'] = odir

        for engine in ENGINES:
            flags[engine] = True

        cmd_line_equivalent = []
        for k, v in flags.iteritems():
            if isinstance(v, list):
                in_files = ' '.join(v)
                arg = '--{0} {1}'.format(k, in_files)
            elif not isinstance(v, string_types):
                arg = '--{0}'.format(k)
            else:
                arg = '--{0} {1}'.format(k, v)
            cmd_line_equivalent.append(arg)

        logger.info('Converting {0}, {1} with command:\n'.format(gro, top))
        logger.info('    python convert.py {0}'.format(' '.join(cmd_line_equivalent)))

        diff = convert.main(flags)
        for engine, result in diff.iteritems():
            results[engine][name] = result
        remove_handler(h1, h2)

    summarize_results('gromacs', results, basedir)
    return results

[docs]def test_gromacs_unit():
    """

    Args:
        gromacs:
    Returns:

    """
    unit_test_tolerance = 1e-4
    flags = {'unit': True,
             'energy': True,
             'gromacs': True}

    testing_logger.info('Running unit tests')

    output_dir = os.path.join(os.path.dirname(__file__), 'unit_test_outputs')
    if not os.path.isdir(output_dir):
        os.mkdir(output_dir)

    results = gromacs(flags, test_type='unit')
    zeros = np.zeros(shape=(len(results['gromacs'])))
    for engine, tests in results.iteritems():
        tests = np.array(tests.values())
        try:
            passed = np.allclose(tests, zeros, atol=unit_test_tolerance)
        except:
            raise ValueError('Found non-numeric result for GROMACS to {0}. This'
                             ' probably means an error occured somewhere in the'
                             ' conversion.'.format(engine.upper()))
        assert passed, 'Unit tests do not match within {0:.1e} kJ/mol.'.format(
                unit_test_tolerance)
        print('All unit tests for GROMACS to {0} match within {1:.1e} kJ/mol.'.format(
                engine.upper(), unit_test_tolerance))

[docs]def test_gromacs_stress():
    """

    Args:
        gromacs:
    Returns:

    """
    stress_test_tolerance = 1e-4
    flags = {'stress': True,
             'energy': True,
             'gromacs': True}

    testing_logger.info('Running stress tests')

    output_dir = os.path.join(os.path.dirname(__file__), 'stress_test_outputs')
    if not os.path.isdir(output_dir):
        os.mkdir(output_dir)

    results = gromacs(flags, test_type='stress')
    zeros = np.zeros(shape=(len(results['gromacs'])))
    for engine, tests in results.iteritems():
        tests = np.array(tests.values())
        try:
            passed = np.allclose(tests, zeros, atol=stress_test_tolerance)
        except:
            raise ValueError('Found non-numeric result. This probably means an'
                             'error occured somewhere in the conversion.')
        assert passed, 'Stress tests do not match within {0:.1e} kJ/mol.'.format(
                stress_test_tolerance)
        print('All unit tests for GROMACS to {1} match within {0:.1e} kJ/mol.'.format(
                stress_test_tolerance, engine.upper()))

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Run the GROMACS tests.')

    type_of_test = parser.add_argument('-t', '--type', metavar='test_type',
            default='unit', help="The type of tests to run: 'unit', 'stress' or 'all'.")

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    # TODO: Rewrite assertions or testing calls so that you can run 'all' but
    #       still have working py.test.
    args = vars(parser.parse_args())
    if args['type'] in ['unit', 'all']:
        test_gromacs_unit()
    if args['type'] in ['stress', 'all']:
        test_gromacs_stress()

        © Copyright 2015, Christoph Klein, Christopher Lee, Ellen Zhong, and Michael Shirts.

  Sphinx theme provided by Read the Docs


text:
package net.codetojoy;

import java.util.Date;
import java.util.concurrent.Future;

public class FooService {
    Future<BarService> barServiceFuture;
    AsyncBarServiceWrapper asyncBarServiceWrapper;

    public void initialize() {
        asyncBarServiceWrapper = new AsyncBarServiceWrapper();
        barServiceFuture = asyncBarServiceWrapper.startHandshake();
        System.out.println("TRACER " + new Date() + " initialize");
    }

    public void invokeBarService() {
        try {
            System.out.println("TRACER " + new Date() + " invoke");
            BarService barService = barServiceFuture.get();
            System.out.println("TRACER " + new Date() + " invoke. id: " + barService.getId());
        } catch (Exception ex) {
            System.err.println("TRACER FooService caught exception. ex: " + ex.getMessage());
        } finally {
            asyncBarServiceWrapper.shutdown();
        }
    }
}


text:
class ChangeContactPreferenceDefaults < ActiveRecord::Migration[5.2]
  def change
    change_column_default :users, :notification_when_innovation_award_open, from: true, to: false
    change_column_default :users, :notification_when_trade_award_open, from: true, to: false
    change_column_default :users, :notification_when_development_award_open, from: true, to: false
    change_column_default :users, :notification_when_mobility_award_open, from: true, to: false
    change_column_default :users, :notification_when_submission_deadline_is_coming, from: true, to: false
    change_column_default :users, :subscribed_to_emails, from: true, to: false
    change_column_default :users, :agree_being_contacted_by_department_of_business, from: true, to: false
  end
end


text:
'use strict';

const express = require('express');
const router = express.Router();

const Hits = require('./modules/hits');
const People = require('./modules/people');
const Activity = require('./modules/activity');

router.get('/', (req, res, next) => {

  require('./utilities/polyfill');

  const db = req.db;

  const message = req.query.message || '';
  console.log('message:', message);
  const hitsInSentance = Hits.getFromSentence(message, db); // Get all the hits from the message!

  const messageWithHits = hitsInSentance.then(hitss => Hits.reconstructSentance(message, hitss)); // Get the sentance with hits to render them
  const matchedPeople = hitsInSentance.then(hitss => People.getMatched(hitss, db));

  const people = matchedPeople.then(peopleData => People.getAllData(peopleData, db));

  const peopleWithActivity = people.then(peopleWithoutAcitivity => Activity.add(peopleWithoutAcitivity, db));

  Promise.all([peopleWithActivity, messageWithHits])
    .then((values) => {
      res.render('index', { people: values[0], message, buzzwords: values[1] });
    });

});
module.exports = router;


text:
#cover-container {
  z-index: -2;
  overflow: hidden;
  background: black;
}
  /* Article cover */
#article-cover {
  width: 100%;
  height: 400px;

  background-repeat: no-repeat !important;
  background-attachment: scroll !important;
  background-position: center center !important;
  -webkit-background-size: cover !important;
  -moz-background-size: cover !important;
  -o-background-size: cover !important;
  background-size: cover !important;
}

  /* instafeed cover */

#instafeed {
  display: none;
  flex-direction: row;
  flex-wrap: wrap;

}
#instafeed div {
  margin: auto;
  width: calc(100% / 10);
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: contain;
  display: none;
}
#instafeed div img {
  margin: auto;
  width: 100%;
  border-radius: 0;
  -webkit-filter: grayscale(100%);
  -moz-filter: grayscale(100%);
  -ms-filter: grayscale(100%);
  filter: blur(2px) grayscale(80%);
  transition: 0.1s ease-in-out;
}
#instafeed div a {
  position: relative;
  overflow: hidden;
}
#instafeed div img:hover {
  margin: auto;
  width: 100%;
  -webkit-filter: blur(40px);
  -moz-filter: blur(40px);
  -ms-filter: blur(40px);
  filter: blur(0px) grayscale(20%);
  cursor: pointer;
}

/* Custom, iPhone Retina */
@media only screen and (min-width : 320px) {
  #instafeed div {
    width: calc(100% / 4);
  }
  #cover-container div:nth-child(-n+8) {
    display: inline-block;
  }
  #article-cover {
  height: 250px;
  }
}
/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px) {
  #instafeed div {
    width: calc(100% / 5);
  }
  #instafeed div:nth-child(-n+10) {
    display: inline-block;
  }
  #article-cover {
  height: 350px;
  }
}
/* Small Devices, Tablets */
@media only screen and (min-width : 768px) {
  #instafeed div {
    width: calc(100% / 6);
  }
  #instafeed div:nth-child(-n+12) {
    display: inline-block;
  }
  #article-cover {
  height: 350px;
  }
}

/* Medium Devices, Desktops */
@media only screen and (min-width : 992px) {
  #instafeed div {
    width: calc(100% / 8);
  }
  #instafeed div:nth-child(-n+16) {
    display: inline-block;
  }
  #article-cover {
  height: 400px;
  }
}

/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px) {
  #instafeed div {
    width: calc(100% / 10);
  }
  #instafeed div:nth-child(-n+20) {
    display: inline-block;
  }
}


text:
package com.haskforce.parsing.srcExtsDatatypes;

/**
 * PatTypeSig l (Pat l) (Type l)
 */
public class PatTypeSig extends PatTopType {
    public SrcInfoSpan srcInfoSpan;
    public PatTopType pat;
    public TypeTopType type;

    @Override
    public String toString() {
        return "PatTypeSig{" +
                "pat=" + pat +
                ", type=" + type +
                '}';
    }
}


text:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using VirtPackageAPI;
using System.Collections;
using System.IO;
using System.Threading;

namespace PackageEditor
{
    class RegistryEditor
    {
        private VirtPackage virtPackage;
        private TreeView fsFolderTree;
        private ListView fsFilesList;
        private Label fsFolderInfoFullName;
        private ComboBox fsFolderInfoIsolationCombo;
        private ToolStripButton regRemoveBtn;
        private ToolStripButton regEditBtn;
        private TreeHelper treeHelper;
        public RegistryKey workKey;
        public bool dirty;
        private string masterkey;
        private ArrayList currentkey;
        private AutoResetEvent regLoadAutoResetEvent;

        public delegate bool DelegateRequireElevation();
        private DelegateRequireElevation requireElevation;

        public delegate bool DelegateAddFileOrFolder(String path);
        public DelegateAddFileOrFolder Del_AddFOrF;

        public string Masterkey
        {
            get { return masterkey; }
            set { masterkey = value; }
        }

        public ArrayList Currentkey
        {
            get { return currentkey; }
            set { currentkey = value; }
        }

        public RegistryEditor(VirtPackage virtPackage, DelegateRequireElevation requireElevation,
            TreeView fsFolderTree, ListView fsFilesList, Label fsFolderInfoFullName,
            ComboBox fsFolderInfoIsolationCombo, ToolStripButton regRemoveBtn, ToolStripButton regEditBtn)
        {
            this.virtPackage = virtPackage;
            this.requireElevation = requireElevation;
            this.fsFolderTree = fsFolderTree;
            this.fsFilesList = fsFilesList;
            this.fsFolderInfoFullName = fsFolderInfoFullName;
            this.fsFolderInfoIsolationCombo = fsFolderInfoIsolationCombo;
            this.regRemoveBtn = regRemoveBtn;
            this.regEditBtn = regEditBtn;

            fsFolderInfoFullName.Text = "";
            fsFolderInfoIsolationCombo.Text = "";
            fsFolderInfoIsolationCombo.Items.Add(PackageEditor.Messages.Messages.fullAccess);
            fsFolderInfoIsolationCombo.Items.Add(PackageEditor.Messages.Messages.isolated);
            fsFolderInfoIsolationCombo.Items.Add(PackageEditor.Messages.Messages.strictlyIsolated);
            fsFolderTree.AfterSelect += OnFolderTreeSelect;
            fsFolderInfoIsolationCombo.SelectionChangeCommitted += OnFolderSandboxChange;
            regRemoveBtn.Click += OnRemoveBtnClick;
            regEditBtn.Click += OnEditClick;
            dirty = false;
            treeHelper = new TreeHelper(virtPackage);

            // delegate for AddFileOrFolder init
            Del_AddFOrF = new DelegateAddFileOrFolder(this.AddFileOrFolder);
        }

        // function to add files and folders recursively
        private bool AddFileOrFolder(String path)
        {
            if (Path.GetExtension(path).Equals(".reg", StringComparison.CurrentCultureIgnoreCase))
            {
                importRegFile(path);
            }
            else
                MessageBox.Show("Only .reg files are supported for imporing into the Registry tab");
            return true;
        }

        public void OnPackageOpenBeforeUI()     // Slow operation, for threading. Must NOT perform any UI.
        {
            try
            {
                regLoadAutoResetEvent = new AutoResetEvent(false);
                workKey = virtPackage.GetRegWorkKeyEx(regLoadAutoResetEvent);
                if (workKey == null)    // No virtual registry?
                    return;
            }
            catch
            {
                // ThreadAbortException
            }
        }

        public void OnPackageOpenUI()
        {
            fsFolderTree.Nodes.Clear();
            TreeNode rootNode = new TreeNode("Registry");
            treeHelper.SetFolderNodeImage(rootNode,
                false, false, virtPackage.GetRegistrySandbox("", false));
            fsFolderTree.Nodes.Add(rootNode);
            if (workKey != null)
                PopulateSubKeys(workKey, "", rootNode);
            fsFolderTree.Nodes[0].Expand();     // Expand the "Registry" node
            fsFolderTree.SelectedNode = fsFolderTree.Nodes[0];
            dirty = false;
        }

        public void OnTabActivate()
        {
            // Force Isolation combo to refresh. This is in case the General Properties'
            // Isolation radio was changed, we need to refresh the Isolation combo here.
            if (fsFolderTree.Nodes.Count > 0)
            {
                fsFolderTree.SelectedNode = null;
                fsFolderTree.SelectedNode = fsFolderTree.Nodes[0];
            }
        }

        public void OnPackageClose()
        {
            fsFolderTree.Nodes.Clear();
            fsFilesList.Items.Clear();
            fsFolderInfoFullName.Text = "";
            fsFolderInfoIsolationCombo.Text = "";
            if (workKey != null)
            {
                /*try
                {
                    MessageBox.Show(workKey.Name);
                    workKey.DeleteSubKeyTree("");
                }
                catch
                {
                }*/
                workKey.Close();
                workKey = null;
            }
        }

        public bool OnPackageSave()
        {
            //return (virtPackage.SaveRegWorkKey());
            return true;
        }

        private void PopulateSubKeys(RegistryKey parentKey, String subKeyName, TreeNode curNode)
        {
            //if (subKeyName == "") return;   // No virtual registry exists (programs with no registry modifications)
            RegistryKey curKey = parentKey.OpenSubKey(subKeyName, false);
            if (curKey == null) return;     // Should never happen

            String[] subKeys = curKey.GetSubKeyNames();
            foreach (String subKey in subKeys)
            {
                TreeNode newNode;
                /*if (curNode == null)    // Very first tree node
                    newNode = fsFolderTree.Nodes.Add(subKey);
                else*/
                newNode = curNode.Nodes.Add(subKey);

                // Update image
                String fullName = treeHelper.GetFullNodeName(newNode);
                UInt32 sandboxFlags = virtPackage.GetRegistrySandbox(fullName, false);
                treeHelper.SetFolderNodeImage(newNode, false, false, sandboxFlags);

                // Recurse
                PopulateSubKeys(curKey, subKey, newNode);
            }

            // Add values
            /*Items := TStringList.Create;
            Reg.GetValueNames(Items);
            For I:=0 To Items.Count-1 Do Begin
            NewNode := TreeView.Items.AddChild(CurNode, Items[I]);
            SetNodeImage(NewNode, IMG_FILE);
            End;*/
            curKey.Close();
        }

        public void OnFolderTreeSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode folderNode = e.Node;
            fsFolderInfoFullName.Text = "";
            fsFolderInfoIsolationCombo.SelectedIndex = -1;
            if (folderNode == null)
                return;
            fsFolderInfoIsolationCombo.Enabled = true; //(folderNode != fsFolderTree.Nodes[0]);

            // Fill info panel
            String fullName = treeHelper.GetFullNodeName(folderNode);
            fsFolderInfoFullName.Text = fullName;
            fsFolderInfoIsolationCombo.SelectedIndex = treeHelper.SandboxFlagsToComboIndex(
                virtPackage.GetRegistrySandbox(fsFolderInfoFullName.Text, false));

            // Fill fsFilesList
            fsFilesList.Items.Clear();
            if (workKey == null)
                return;
            RegistryKey regKey = workKey.OpenSubKey(fullName);
            if (regKey == null)
                return;
            String[] values = regKey.GetValueNames();
            currentkey = new ArrayList();
            masterkey = "";
            currentkey.Clear();
            for (int i = 0; i < values.Length; i++)
            {
                ListViewItem newItem = new ListViewItem();
                newItem.Text = values[i];
                masterkey = regKey.ToString();
                currentkey.Add(newItem.Text);
                newItem.SubItems.Add((string)regKey.GetValue(values[i]).ToString());
                newItem.SubItems.Add((string)regKey.GetValueKind(values[i]).ToString());
                //newItem.SubItems.Add(ToDo: read value);
                fsFilesList.Items.Add(newItem);
            }
        }

        private void OnFolderSandboxChange(object sender, EventArgs e)
        {
            TreeNode node = fsFolderTree.SelectedNode;
            if (node == null)
                return;
            String fullName = treeHelper.GetFullNodeName(node);
            virtPackage.SetRegistrySandbox(
                node != fsFolderTree.Nodes[0] ? fullName : "",   // Root = ""
                treeHelper.ComboIndexToSandboxFlags(fsFolderInfoIsolationCombo.SelectedIndex), false);
            RefreshFolderNodeRecursively(node, 0);
            dirty = true;
        }

        private void OnRemoveBtnClick(object sender, EventArgs e)
        {
            TreeNode node = fsFolderTree.SelectedNode;
            if (node == null || workKey == null)
                return;

            // Require elevation
            if (!requireElevation())
                return;

            // Confirm
            if (MessageBox.Show("Delete key?", "Confirm", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;

            // Delete key
            String fullName = treeHelper.GetFullNodeName(node);
            try
            {
                workKey.DeleteSubKeyTree(fullName);
                node.Remove();
                virtPackage.SaveRegWorkKey();
            }
            catch
            {
            }
            dirty = true;
        }

        private void OnEditClick(object sender, EventArgs e)
        {
            // Valid registry?
            if (workKey == null)
            {
                MessageBox.Show("No registry in this package");
                return;
            }

                // Require elevation
            if (!requireElevation())
                return;

            // Notification window
            PackageBuiltNotify packageBuiltNotify = new PackageBuiltNotify();
            String friendlyKeyName = System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(workKey.Name));
            packageBuiltNotify.Do("Registry editor will now open. Please edit entries under the key '" +
                friendlyKeyName + "'. Once you close the registry editor, your changes will be applied.",
                "", "", "RegeditExplain");

            // Set LastKey to the work key
            RegistryKey regKey;
            try
            {
                regKey = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit");
                regKey.SetValue("LastKey", "Computer\\" + workKey.Name);
                regKey.Close();
            }
            catch
            {
                return;
            }

            // Run RegEdit
            System.Diagnostics.ProcessStartInfo procStartInfo =
                new System.Diagnostics.ProcessStartInfo("Regedit.exe", "-m");
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
            proc.StartInfo = procStartInfo;
            try
            {
                proc.Start();
                proc.WaitForExit();
                OnPackageOpenUI();
                virtPackage.SaveRegWorkKey();
                dirty = true;
            }
            catch
            {
                // Exception will occur if user refuses UAC elevation for example..
            }

        }

        public void RefreshFolderNodeRecursively(TreeNode curNode, int iteration)
        {
            String fullName = treeHelper.GetFullNodeName(curNode);
            UInt32 sandboxFlags = virtPackage.GetRegistrySandbox(fullName, false);
            if (iteration == 0)
            {
                treeHelper.SetFolderNodeImage(curNode, false, false, sandboxFlags);
                if (curNode.Nodes.Count > 0)
                    RefreshFolderNodeRecursively(curNode.Nodes[0], iteration + 1);
            }
            else
            {
                while (curNode != null)
                {
                    treeHelper.SetFolderNodeImage(curNode, false, false, sandboxFlags);
                    if (curNode.Nodes.Count > 0)
                        RefreshFolderNodeRecursively(curNode.Nodes[0], iteration + 1);
                    curNode = curNode.NextNode;
                }
            }
        }

        public void toolStripMenuItemExport_Click(object sender, EventArgs e)
        {
            RegFileExport();
        }

        private void importRegFile(string path)
        {
            String RegFileName = path;
            RegistryKey key = workKey;
            RegistryFunctions registryFunctions = new RegistryFunctions();
            registryFunctions.ImportVirtualRegistryFromFile(RegFileName, key);

            // Refresh the local registry tree
            OnPackageOpenUI();
            dirty = true;
        }

        internal void threadedRegLoadStop()
        {
            if (regLoadAutoResetEvent != null)
                regLoadAutoResetEvent.Set();
        }

        internal void RegFileExport()
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter = "Registry file (*.reg)|*.reg";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                String RegFileName = sfd.FileName;

                // Read Registry Keys in the package
                RegistryKey key = workKey;
                String virtKey = treeHelper.GetFullNodeName(fsFolderTree.SelectedNode);
                RegistryFunctions registryFunctions = new RegistryFunctions();
                registryFunctions.ExportVirtualRegistryToFile(RegFileName, key, virtKey);
            }
        }

        internal void RegFileImport()
        {
            // Require elevation
            if (!requireElevation())
                return;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Registry file (*.reg)|*.reg";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                AddFileOrFolder(ofd.FileName);
                virtPackage.SaveRegWorkKey();
            }
        }
    }
}


text:
require 'spec_helper'
module Alf
  class Database
    describe Connection, "fact!" do

      let(:conn){ sap_conn }

      context 'when more than one tuple' do
        subject{ conn.fact!{ suppliers } }

        it 'raises a FactAssertionError' do
          lambda{
            subject
          }.should raise_error(FactAssertionError)
        end
      end

      context 'when zero tuple' do
        subject{ conn.fact!{ restrict(suppliers, ->{ false }) } }

        it 'raises a FactAssertionError' do
          lambda{
            subject
          }.should raise_error(FactAssertionError)
        end
      end

      context 'when exactly one tuple' do
        subject{ conn.fact!{ restrict(suppliers, ->{ sid == 'S1' }) } }

        it 'returns a Tuple instance' do
          subject.should be_a(Tuple)
        end
      end

      context 'with an error message' do
        subject{ conn.fact!("foo"){ suppliers } }

        it 'raises a FactAssertionError' do
          lambda{
            subject
          }.should raise_error(FactAssertionError, /foo/)
        end
      end

    end
  end
end


text:
class GURL;

namespace content {

class RenderViewHost;

class DevToolsHttpHandlerDelegate {
 public:
  enum TargetType {
    kTargetTypeTab = 0,
    kTargetTypeOther,
  };

  virtual ~DevToolsHttpHandlerDelegate() {}

  // Should return discovery page HTML that should list available tabs
  // and provide attach links.
  virtual std::string GetDiscoveryPageHTML() = 0;

  // Returns true if and only if frontend resources are bundled.
  virtual bool BundlesFrontendResources() = 0;

  // Returns path to the front-end files on the local filesystem for debugging.
  virtual base::FilePath GetDebugFrontendDir() = 0;

  // Get a thumbnail for a given page. Returns non-empty string iff we have the
  // thumbnail.
  virtual std::string GetPageThumbnailData(const GURL& url) = 0;

  // Creates new inspectable target and returns its render view host.
  virtual RenderViewHost* CreateNewTarget() = 0;

  // Returns the type of the target.
  virtual TargetType GetTargetType(RenderViewHost*) = 0;

  // Provides the delegate with an ability to supply a description for views.
  virtual std::string GetViewDescription(content::RenderViewHost*) = 0;

  // Creates named socket for reversed tethering implementation (used with
  // remote debugging, primarily for mobile).
  virtual scoped_refptr<net::StreamListenSocket> CreateSocketForTethering(
      net::StreamListenSocket::Delegate* delegate,
      std::string* name) = 0;
};

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_DEVTOOLS_HTTP_HANDLER_DELEGATE_H_


text:
package org.ovirt.engine.ui.webadmin.section.main.view.tab;

import org.ovirt.engine.core.common.businessentities.DbUser;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.uicommon.model.MainModelProvider;
import org.ovirt.engine.ui.common.widget.table.column.TextColumnWithTooltip;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.models.users.UserListModel;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.MainTabUserPresenter;
import org.ovirt.engine.ui.webadmin.section.main.view.AbstractMainTabWithDetailsTableView;
import org.ovirt.engine.ui.webadmin.widget.action.WebAdminButtonDefinition;
import org.ovirt.engine.ui.webadmin.widget.table.column.UserStatusColumn;

import com.google.gwt.core.client.GWT;
import com.google.inject.Inject;

public class MainTabUserView extends AbstractMainTabWithDetailsTableView<DbUser, UserListModel> implements MainTabUserPresenter.ViewDef {

    interface ViewIdHandler extends ElementIdHandler<MainTabUserView> {
        ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
    }

    @Inject
    public MainTabUserView(MainModelProvider<DbUser, UserListModel> modelProvider) {
        super(modelProvider);
        ViewIdHandler.idHandler.generateAndSetIds(this);
        initTable();
        initWidget(getTable());
    }

    void initTable() {
        getTable().addColumn(new UserStatusColumn(), "", "30px");

        getTable().addColumn(new TextColumnWithTooltip<DbUser>() {
            @Override
            public String getValue(DbUser object) {
                return object.getname();
            }
        }, "First Name");

        getTable().addColumn(new TextColumnWithTooltip<DbUser>() {
            @Override
            public String getValue(DbUser object) {
                return object.getsurname();
            }
        }, "Last Name");

        getTable().addColumn(new TextColumnWithTooltip<DbUser>(40) {
            @Override
            public String getValue(DbUser object) {
                return object.getusername();
            }
        }, "User Name");

        getTable().addColumn(new TextColumnWithTooltip<DbUser>(40) {
            @Override
            public String getValue(DbUser object) {
                return object.getgroups();
            }
        }, "Group");

        getTable().addColumn(new TextColumnWithTooltip<DbUser>() {
            @Override
            public String getValue(DbUser object) {
                return object.getemail();
            }
        }, "e-mail");

        getTable().addActionButton(new WebAdminButtonDefinition<DbUser>("Add") {
            @Override
            protected UICommand resolveCommand() {
                return getMainModel().getAddCommand();
            }
        });
        getTable().addActionButton(new WebAdminButtonDefinition<DbUser>("Remove") {
            @Override
            protected UICommand resolveCommand() {
                return getMainModel().getRemoveCommand();
            }
        });
        getTable().addActionButton(new WebAdminButtonDefinition<DbUser>("Assign Tags") {
            @Override
            protected UICommand resolveCommand() {
                return getMainModel().getAssignTagsCommand();
            }
        });
    }

}


text:
namespace ash {

class NetworkPortalNotificationControllerTest;
class NetworkPortalSigninController;

// Shows a message center notification when the networking stack detects a
// captive portal.
class NetworkPortalNotificationController
    : public NetworkStateHandlerObserver,
      public session_manager::SessionManagerObserver {
 public:
  // The values of these metrics are being used for UMA gathering, so it is
  // important that they don't change between releases.
  enum UserActionMetric {
    USER_ACTION_METRIC_CLICKED,
    USER_ACTION_METRIC_CLOSED,
    USER_ACTION_METRIC_IGNORED,
    USER_ACTION_METRIC_COUNT
  };

  static const char kNotificationId[];

  NetworkPortalNotificationController();

  NetworkPortalNotificationController(
      const NetworkPortalNotificationController&) = delete;
  NetworkPortalNotificationController& operator=(
      const NetworkPortalNotificationController&) = delete;

  ~NetworkPortalNotificationController() override;

  // Ignores "No network" errors in browser tests.
  void SetIgnoreNoNetworkForTesting();

  bool IsDialogShownForTesting() const;

 private:
  friend NetworkPortalNotificationControllerTest;

  // Creates the default notification informing the user that a captive portal
  // has been detected. On click the captive portal login page is opened in the
  // browser.
  std::unique_ptr<message_center::Notification>
  CreateDefaultCaptivePortalNotification(
      const NetworkState* network,
      NetworkState::PortalState portal_state);

  // NetworkStateHandlerObserver:
  void PortalStateChanged(const NetworkState* network,
                          NetworkState::PortalState portal_state) override;
  void OnShuttingDown() override;

  // session_manager::SessionManagerObserver:
  void OnSessionStateChanged() override;

  // Last network guid for which notification was displayed.
  std::string last_network_guid_;

  // The signin controller is responsible for displaying the captive portal
  // signin UI.
  std::unique_ptr<NetworkPortalSigninController> signin_controller_;

  // Last portal state for which notification was displayed.
  NetworkState::PortalState last_portal_state_ =
      NetworkState::PortalState::kUnknown;

  // Do not close Portal Login dialog on "No network" error in browser tests.
  bool ignore_no_network_for_testing_ = false;
};

}  // namespace ash

#endif  // CHROME_BROWSER_UI_ASH_NETWORK_NETWORK_PORTAL_NOTIFICATION_CONTROLLER_H_


text:
package org.kie.workbench.common.dmn.client.session;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvas;
import org.kie.workbench.common.stunner.core.client.shape.Shape;
import org.kie.workbench.common.stunner.core.diagram.GraphsProvider;
import org.kie.workbench.common.stunner.core.graph.Element;
import org.kie.workbench.common.stunner.core.graph.content.HasContentDefinitionId;
import org.kie.workbench.common.stunner.core.graph.content.definition.Definition;
import org.mockito.Mock;
import org.mockito.Mockito;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(GwtMockitoTestRunner.class)
public class DMNCanvasHandlerTest {

    @Mock
    private DMNCanvasHandler canvasHandler;

    @Mock
    private Element parent;

    @Mock
    private Element child;

    @Mock
    private AbstractCanvas canvas;

    @Mock
    private Shape shape;

    private final String parentUuid = "parent uuid";

    @Before
    public void setup() {
        when(parent.getUUID()).thenReturn(parentUuid);
        doCallRealMethod().when(canvasHandler).addChild(parent, child);
        doCallRealMethod().when(canvasHandler).updateDiagramId(any());
    }

    @Test
    public void testAddChildWhenItIsElementFromThisCanvas() {

        doReturn(false).when(canvasHandler).isCanvasRoot(parent);
        doReturn(canvas).when(canvasHandler).getCanvas();
        when(canvas.getShape(parentUuid)).thenReturn(shape);

        canvasHandler.addChild(parent, child);

        verify(canvasHandler).superAddChild(parent, child);
    }

    @Test
    public void testAddChildWhenItIsNotElementFromThisCanvas() {

        doReturn(false).when(canvasHandler).isCanvasRoot(parent);
        doReturn(canvas).when(canvasHandler).getCanvas();
        when(canvas.getShape(parentUuid)).thenReturn(null);

        canvasHandler.addChild(parent, child);

        verify(canvasHandler, never()).superAddChild(parent, child);
    }

    @Test
    public void testAddChildWhenItIsCanvasRoot() {

        doReturn(true).when(canvasHandler).isCanvasRoot(parent);
        doReturn(canvas).when(canvasHandler).getCanvas();
        when(canvas.getShape(parentUuid)).thenReturn(null);

        canvasHandler.addChild(parent, child);

        verify(canvasHandler).superAddChild(parent, child);
    }

    @Test
    public void testUpdateDiagramIdWhenDiagramIdIsNull() {

        final String diagramId = "diagram id";
        final HasContentDefinitionId hasContentDefinitionId = mock(HasContentDefinitionId.class);
        final Element element = getElementForTestUpdateDiagramId(diagramId,
                                                                 null,
                                                                 hasContentDefinitionId);

        canvasHandler.updateDiagramId(element);

        verify(hasContentDefinitionId).setDiagramId(diagramId);
    }

    @Test
    public void testUpdateDiagramIdWhenDiagramIdIsSet() {

        final String diagramId = "diagram id";
        final String currentDiagramId = "some set diagram";
        final HasContentDefinitionId hasContentDefinitionId = mock(HasContentDefinitionId.class);
        final Element element = getElementForTestUpdateDiagramId(diagramId,
                                                                 currentDiagramId,
                                                                 hasContentDefinitionId);

        canvasHandler.updateDiagramId(element);

        verify(hasContentDefinitionId, never()).setDiagramId(Mockito.<String>any());
    }

    @Test
    public void testUpdateDiagramIdWhenDiagramIdIsEmpty() {

        final String diagramId = "diagram id";
        final String currentDiagramId = "";
        final HasContentDefinitionId hasContentDefinitionId = mock(HasContentDefinitionId.class);
        final Element element = getElementForTestUpdateDiagramId(diagramId,
                                                                 currentDiagramId,
                                                                 hasContentDefinitionId);

        canvasHandler.updateDiagramId(element);

        verify(hasContentDefinitionId).setDiagramId(diagramId);
    }

    private Element getElementForTestUpdateDiagramId(final String diagramId,
                                                     final String currentDiagramId,
                                                     final HasContentDefinitionId hasContentDefinitionId) {
        final Element element = mock(Element.class);
        final Definition definition = mock(Definition.class);
        final GraphsProvider graphsProvider = mock(GraphsProvider.class);

        when(graphsProvider.getCurrentDiagramId()).thenReturn(diagramId);
        when(definition.getDefinition()).thenReturn(hasContentDefinitionId);
        when(element.getContent()).thenReturn(definition);
        when(hasContentDefinitionId.getDiagramId()).thenReturn(currentDiagramId);
        when(canvasHandler.getGraphsProvider()).thenReturn(graphsProvider);

        return element;
    }
}


text:
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
/// <reference path="../core/Logger.ts"/>
/// <reference path="../core/MainContext.ts"/>
/// <reference path="../core/Ticker.ts"/>
/// <reference path="../texture/Texture.ts"/>
var egret;
(function (egret) {
    var DEBUG = (function () {
        function DEBUG() {
        }

        /**
        * 跟踪渲染主循环过程
        * @param command 0,停止主循环; 1,执行一次主循环 2,正常循环渲染
        * @constructor
        */
        DEBUG.TRACE_RENDER_LOOP = function (command) {
            if (typeof command === "undefined") { command = 0; }
            var ticker = egret.Ticker.getInstance();
            var context = egret.MainContext.instance;
            switch (command) {
                case 0:
                    ticker.unregister(context["renderLoop"], context);
                    break;
                case 1:
                    context["renderLoop"]();
                    break;
                case 2:
                    ticker.register(context["renderLoop"], context);
                    break;
            }
        };
        DEBUG.DRAW_IMAGE = true;

        DEBUG.ADD_EVENT_LISTENER = true;

        DEBUG.SCALE_BITMAP_SET_SCALE_GRID = true;
        return DEBUG;
    })();
    egret.DEBUG = DEBUG;
})(egret || (egret = {}));


text:
<html>
    <head>
        <title>ClickFriend</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    </head>
    <style>
		body{
			margin: 0;
			padding: 0;
		}

		.clickfriend-container{
			position: absolute;
			width: 130px;
			height: 100px;

			-webkit-user-select: none;  /* Chrome all / Safari all */
			-moz-user-select: none;     /* Firefox all */
			-ms-user-select: none;      /* IE 10+ */

			/* No support for these yet, use at own risk */
			-o-user-select: none;
			user-select: none;

			border: none;

			pointer-events: none;
		}

    </style>
    <body>

		Click!

		<script>
			$('body').on('click', function(e){
				var offset = $(this).offset();
				onClick(e.clientX - offset.left, e.clientY - offset.top);
			});

			function onClick(x, y){

				var diameter = 100;

				var dx, dy;
				dx = x - (diameter / 2);
				dy = y - (diameter / 2);
				var containerId = "" + dx + "-" + dy;

				var containerElement = $('<iframe>').attr({'id': containerId, class: 'clickfriend-container'});
				containerElement.css({left: dx, top: dy});
				containerElement.attr({src: 'arc.svg'});
				$('body').append(containerElement);
			}
		</script>
    </body>
</html>


text:
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/fs-test-util.js"></script>
</head>
<body>
<script src="script-tests/read-directory.js"></script>
</body>
</html>


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
// tslint:disable-next-line:quotemark
var core_1 = require("@angular/core");
// tslint:disable-next-line:quotemark
var Ng2OwlCarouselItem = (function () {
    function Ng2OwlCarouselItem() {
    }
    Ng2OwlCarouselItem.prototype.ngOnInit = function () {
        this.onItemSelect = new core_1.EventEmitter();
    };
    Ng2OwlCarouselItem.prototype.onSelect = function () {
        this.onItemSelect.emit(this.item);
    };
    __decorate([
        core_1.Input()
    ], Ng2OwlCarouselItem.prototype, "item", void 0);
    __decorate([
        core_1.Output()
    ], Ng2OwlCarouselItem.prototype, "onItemSelect", void 0);
    Ng2OwlCarouselItem = __decorate([
        core_1.Component({
            // tslint:disable-next-line:quotemark
            selector: 'carousel-item',
            template: "\n  <div>\n    <ng-content> </ng-content>\n  </div>"
        })
    ], Ng2OwlCarouselItem);
    return Ng2OwlCarouselItem;
}());
exports.Ng2OwlCarouselItem = Ng2OwlCarouselItem;


text:
package cn.halo9pan.blog.hello.core;

import java.util.Date;

import cn.halo9pan.blog.hello.core.feature.Browser;

/**
 * @author panhao
 *
 */
public class Access {

	private long id;

	private Guest guest;
	private Browser browser;
	private String remote;
	private Date time;

	public long getId() {
		return id;
	}

    public Guest getGuest(){
		return guest;
	}

	public Browser getBrowser() {
		return browser;
	}

	public String getRemote() {
		return remote;
	}

	public Date getTime() {
		return time;
	}

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

	public void setGuest(Guest guest) {
		this.guest = guest;
	}

	public void setBrowser(Browser browser) {
		this.browser = browser;
	}

	public void setRemote(String remote) {
		this.remote = remote;
	}

	public void setTime(Date time) {
		this.time = time;
	}
}


text:
/******************************************************************************
 *
 *
 * @file mailbox_io.h
 *
 * Header file for mailbox IO for PYNQ Microblaze.
 *
 *
 * <pre>
 * MODIFICATION HISTORY:
 *
 * Ver   Who  Date     Changes
 * ----- --- ------- -----------------------------------------------
 * 1.00  po  02/08/18 release
 *
 * </pre>
 *
 *****************************************************************************/
#ifndef MAILBOX_IO_H_
#define MAILBOX_IO_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <unistd.h>
#include <stdint.h>

char mailbox_inbyte(intptr_t device);
void mailbox_outbyte(intptr_t device, char c);
int mailbox_close(int fd);
int mailbox_open(const char* pathname, int flags, ...);
ssize_t mailbox_read(int file, void* ptr, size_t len);
ssize_t mailbox_write(int file, const void* ptr, size_t len);
long mailbox_lseek(int fd, long offset, int whence);
int mailbox_available(int fd);

#ifdef __cplusplus
}
#endif
#endif


text:
using System;

namespace GitVersion
{
    public interface ITag : IEquatable<ITag>, IComparable<ITag>, INamedReference
    {
        string TargetSha { get; }
        ICommit PeeledTargetCommit();
    }
}


text:
class HelpdeskMailer < ActionMailer::Base
  helper :application

  include Redmine::I18n
  include MacroExpander

  # set the hostname for url_for helper
  def self.default_url_options
    { :host => Setting.host_name, :protocol => Setting.protocol }
  end

  # Sending email notifications to the supportclient
  def email_to_supportclient(issue, recipient, journal=nil, text='')
    redmine_headers 'Project' => issue.project.identifier,
                    'Issue-Id' => issue.id,
                    'Issue-Author' => issue.author.login
    redmine_headers 'Issue-Assignee' => issue.assigned_to.login if issue.assigned_to
    message_id issue
    references issue
    subject = "[#{issue.project.name} - ##{issue.id}] #{issue.subject}"
    # Set 'from' email-address to 'helpdesk-sender-email' if available.
    # Falls back to regular redmine behaviour if 'sender' is empty.
    p = issue.project
    s = CustomField.find_by_name('helpdesk-sender-email')
    sender = p.custom_value_for(s).try(:value) if p.present? && s.present?
    # If a custom field with text for the first reply is
    # available then use this one instead of the regular
    r = CustomField.find_by_name('helpdesk-first-reply')
    f = CustomField.find_by_name('helpdesk-email-footer')
    h = CustomField.find_by_name('helpdesk-send-html-emails')
    reply  = p.nil? || r.nil? ? '' : p.custom_value_for(r).try(:value)
    footer = p.nil? || f.nil? ? '' : p.custom_value_for(f).try(:value)
    send_html_emails = p.nil? || h.nil? || p.custom_value_for(h).nil? ? false : p.custom_value_for(h).true?
    # add any attachements
    if journal.present? && text.present?
      journal.details.each do |d|
        if d.property == 'attachment'
          a = Attachment.find(d.prop_key)
          begin
            attachments[a.filename] = File.read(a.diskfile)
          rescue
            # ignore rescue
          end
        end
      end
    end
    if @message_id_object
      headers[:message_id] = "<#{self.class.message_id_for(@message_id_object)}>"
    end
    if @references_objects
      headers[:references] = @references_objects.collect {|o| "<#{self.class.references_for(o)}>"}.join(' ')
    end
    # create mail object to deliver
    mail = if text.present? || reply.present?
      # sending out the journal note to the support client
      # or the first reply message
      t = text.present? ? "#{text}\n\n#{footer}" : reply
      @body = expand_macros(t, issue, journal)
      f = CustomField.find_by_name('helpdesk-reply-separator')
      @reply_separator = issue.project.custom_value_for(f).try(:value)
      if !@reply_separator.blank?
        plaintext_body = @reply_separator + "\n\n" + @body
      end
      mail(
        :from     => sender.present? && sender || Setting.mail_from,
        :reply_to => sender.present? && sender || Setting.mail_from,
        :to       => recipient,
        :subject  => subject,
        :body     => send_html_emails ? nil : plaintext_body,
        :date     => Time.zone.now
      )
    else
      # fallback to a regular notifications email with redmine view
      @issue = issue
      @journal = journal
      @issue_url = url_for(:controller => 'issues', :action => 'show', :id => issue)
      mail(
        :from     => sender.present? && sender || Setting.mail_from,
        :reply_to => sender.present? && sender || Setting.mail_from,
        :to       => recipient,
        :subject  => subject,
        :date     => Time.zone.now,
        :template_path => 'mailer',
        :template_name => 'issue_edit'
      )
    end
    # return mail object to deliver it
    return mail
  end

  private

  # Returns a Message-Id for the given object
  def self.message_id_for(object)
    Mailer.class_eval do
      token_for(object, true)
    end
  end

  # Returns a uniq token for a given object referenced by all notifications
  # related to this object
  def self.references_for(object)
    Mailer.class_eval do
      token_for(object, false)
    end
  end

  # Appends a Redmine header field (name is prepended with 'X-Redmine-')
  def redmine_headers(h)
    h.each { |k,v| headers["X-Redmine-#{k}"] = v.to_s }
  end

  def message_id(object)
    @message_id_object = object
  end

  def references(object)
    @references_objects ||= []
    @references_objects << object
  end
end


text:
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Field, Div, Row
from crispy_forms_materialize.layout import FileField
from django import forms

from lapses.models import AutoLapseConfiguration

class LapseCreateForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(LapseCreateForm, self).__init__(*args, **kwargs)
        self.fields['max_output_size'].label = False
        self.helper = FormHelper()
        self.helper.layout = Layout(
            'create_new_every',
            'image_count',
            'frames_per_second',
            Row(
                Field('enabled', label=None),
                Field('max_output_size', label=None),
            )
        )
        self.helper.add_input(Submit('submit', 'Submit'))

    class Meta:
        model = AutoLapseConfiguration
        fields = ('create_new_every', 'image_count', 'frames_per_second', 'enabled', 'max_output_size')


text:
package jsinterop.generator.visitor;

import jsinterop.generator.model.AbstractRewriter;
import jsinterop.generator.model.ModelVisitor;
import jsinterop.generator.model.Program;
import jsinterop.generator.model.Type;

/**
 * Deletes Java class from our model that have been generated from a namespace that don't contain
 * any functions nor variables.
 */
public class EmptyNamespaceFilter implements ModelVisitor {
  @Override
  public void applyTo(Program program) {
    program.accept(
        new AbstractRewriter() {
          @Override
          public Type rewriteType(Type node) {
            return isEmptyNamespace(node) ? null : node;
          }
        });
  }

  private static boolean isEmptyNamespace(Type type) {
    return type.isNamespace()
        && type.getFields().isEmpty()
        && type.getMethods().isEmpty()
        && type.getInnerTypes().isEmpty();
  }
}


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using HelperSharp;

namespace JobSharp
{
    /// <summary>
    /// The central point to registers logs.
    /// </summary>
    public static class LogService
    {
        #region Fields
        private static Stopwatch s_stopWatch = new Stopwatch();
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the count of errors already registered.
        /// </summary>
        /// <remarks>
        /// Used for functional tests purposes.
        /// </remarks>
        public static long ErrorsCount { get; set; }
        #endregion

        #region Methods
        /// <summary>
        /// Writes the generic log.
        /// </summary>
        /// <param name="message">The message to be written.</param>
        /// <param name="isError">True is the message is about an error.</param>
        public static void Write(string message, bool isError = false)
        {
            if (isError)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine(message);
                Skahal.Infrastructure.Framework.Logging.LogService.Error(message);
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine(message);
                Skahal.Infrastructure.Framework.Logging.LogService.Debug(message);
            }

        }

        /// <summary>
        /// Writes a start log.
        /// </summary>
        /// <param name="message">The message to be written.</param>
        public static void WriteStart(string message)
        {
            var msg = "[STARTED] {0}".With(message);
            Write(msg);
            s_stopWatch.Restart();
        }

        /// <summary>
        /// Write a end log.
        /// </summary>
        /// <param name="message">The message to be written.</param>
        public static void WriteEnd(string message)
        {
            s_stopWatch.Stop();

            Write("[ENDED]");
            Write("\tElapsed time: {0} seconds".With(s_stopWatch.Elapsed.TotalSeconds));
            Write("\t{0}{1}".With(message, Environment.NewLine));
        }

        /// <summary>
        /// Writes a error log.
        /// </summary>
        /// <param name="exception">The exception to be writen.</param>
        public static void WriteError(Exception exception)
        {
            ErrorsCount++;
            var message = "[JOB ERROR] {0}\n{1}".With(exception.Message, exception.StackTrace);
            var typeLoadException = exception as ReflectionTypeLoadException;

            if (typeLoadException != null)
            {
                message += string.Join("\n", typeLoadException.LoaderExceptions.Select(m => m.Message));
            }

            Write(message, true);

            WriteInnerExceptions(exception.InnerException);

            Write(message, true);
        }

        /// <summary>
        /// Initializes with the specified log strategy.
        /// </summary>
        /// <param name="logStrategy">The log strategy.</param>
        internal static void Initialize(Skahal.Infrastructure.Framework.Logging.ILogStrategy logStrategy)
        {
            Skahal.Infrastructure.Framework.Logging.LogService.Initialize(logStrategy);
        }
        #endregion

        #region Helpers
        /// <summary>
        /// Writes the inner exceptions.
        /// </summary>
        /// <param name="exception">The exception.</param>
        private static void WriteInnerExceptions(Exception exception)
        {
            if (exception != null)
            {
                Write("\n\n{0}\n{1}".With(exception.Message, exception.StackTrace), true);
                WriteInnerExceptions(exception.InnerException);
            }
        }
        #endregion
    }
}


text:
require 'bundler/setup'
require 'html/pipeline'
require 'minitest/autorun'
require 'minitest/pride'
require 'minitest/focus'

require 'active_support/core_ext/string'

module TestHelpers
  # Asserts that two html fragments are equivalent. Attribute order
  # will be ignored.
  def assert_equal_html(expected, actual)
    assert_equal Nokogiri::HTML::DocumentFragment.parse(expected).to_hash,
                 Nokogiri::HTML::DocumentFragment.parse(actual).to_hash
  end
end

Minitest::Test.send(:include, TestHelpers)


text:
import { useStaticQuery, graphql } from 'gatsby'

const useBuildTime = () => {
  const time = useStaticQuery(graphql`
    query {
      site {
        buildTime(formatString: "YYYY-MM-DD")
      }
    }
  `)

  return time.site.buildTime
}

export default useBuildTime


text:
package com.echo5bravo.govre.BLL;

import android.content.Context;
import com.echo5bravo.govre.DAL.BusinessBaseAlert;
import com.echo5bravo.govre.INFO.Alert;
import com.echo5bravo.govre.UTILS.ProxyNetworkAlerts;
import java.util.ArrayList;

public class BusinessAlert extends BusinessBaseAlert {

	//CONSTRUCTORS
	public BusinessAlert(Context context) {
		super(context);
	}

	//METHODS
	/**
	* Return all VRE Alerts, Always check for NULL allAlerts because
	* this data is being queried from SQLite.
	*/
	public static ArrayList<Alert> getAllAlerts(Context context)
	{
		try{
			@SuppressWarnings("unused")
			ArrayList<Alert> allAlerts;
			return allAlerts = BusinessBaseAlert.getAllAlerts(context);
		}
		catch (Exception e)
		{
			e.toString();
		}
		return null;
	}

	/* Method calls ProxyNetworkAlerts to attempt to VRE website
	 * and pagescrape alerts.  ArrayList of alerts are returned
	 * and refreshed in the database on each call.
	 */
	public static void LoadAlertsFromWeb(Context context){

		ArrayList<Alert> myAlerts = ProxyNetworkAlerts.fetchAlerts(context);
		if (myAlerts != null)
		{
			/*Delete all Alerts and refresh with new */
			DeleteAll(context);

			/*Insert new alerts */
			Insert(context, myAlerts);
		}
	}
}


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.anttribe.vigor.vigor-infra</groupId>
		<artifactId>vigor-infra</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>vigor-infra-persist</artifactId>
	<name>vigor-infra-persist</name>
	<packaging>jar</packaging>

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

	<dependencies>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
		</dependency>

		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
		</dependency>
	</dependencies>
</project>