text:
using System;
using System.Collections.Generic;
using Gibraltar.Monitor.Serialization;
using Loupe.Extensibility.Data;

namespace Gibraltar.Monitor
{
    ///
    /// A collection of metric definitions, keyed by their unique ID and name
    ///
    /// <remarks>
    /// <para>A metric definition has a unique ID to identify a particular instance of the definition(associated with one session)
    /// and a name that is unique within a session but is designed for comparison of the same definition between sessions.</para>
    /// <para>This class is sealed because it is owned by either the single static active Log class (for metric collection in the current process)
    /// or during replay is automatically created as part of base objects and there is no way to inject an alternative implementation.</para>
    /// </remarks>
    public sealed class MetricDefinitionCollection : IMetricDefinitionCollection
    {
        private readonly Dictionary<Guid, IMetric> m_MetricById = new Dictionary<Guid, IMetric>();
        private readonly Dictionary<string, IMetricDefinition> m_DictionaryByName = new Dictionary<string, IMetricDefinition>(StringComparer.OrdinalIgnoreCase);
        private readonly Dictionary<Guid, IMetricDefinition> m_Dictionary = new Dictionary<Guid, IMetricDefinition>();
        private readonly List<IMetricDefinition> m_List = new List<IMetricDefinition>();
        private readonly object m_Lock = new object();

        ///
        /// Raised every time the collection's contents are changed to allow subscribers to automatically track changes.
        ///
        public event EventHandler<CollectionChangedEventArgs<IMetricDefinitionCollection, IMetricDefinition>> CollectionChanged;

        #region Private Properties and Methods

        ///
        /// This method is called every time a collection change event occurs to allow inheritors to override the change event.
        ///
        /// <remarks>If overridden, it is important to call this base implementation to actually fire the event.</remarks>
        /// <param name="e"></param>
        private void OnCollectionChanged(CollectionChangedEventArgs<IMetricDefinitionCollection, IMetricDefinition> e)
        {
            //save the delegate field in a temporary field for thread safety
            EventHandler<CollectionChangedEventArgs<IMetricDefinitionCollection, IMetricDefinition>> tempEvent = CollectionChanged;

            if (tempEvent != null)
            {
                tempEvent(this, e);
            }
        }

        #endregion

        #region Internal Properties and Methods

        ///
        /// Add a metric to the definition metric cache.  Used by the MetricCollection base class to flatten the hierarchy.
        ///
        /// <param name="newMetric">The metric object to add to the cache.</param>
        internal void AddMetric(IMetric newMetric)
        {
            lock (m_Lock)
            {
                m_MetricById.Add(newMetric.Id, newMetric);
            }
        }

        ///
        /// Remove a metric to the definition metric cache.  Used by the MetricCollection base class to flatten the hierarchy.
        ///
        /// <param name="victimMetric">The metric object to remove from the cache.</param>
        internal void RemoveMetric(IMetric victimMetric)
        {
            lock (m_Lock)
            {
                m_MetricById.Remove(victimMetric.Id);
            }
        }

        #endregion

        #region Public Properties and Methods

        ///
        /// Object Change Locking object.
        ///
        public object Lock { get { return m_Lock; } }

        ///
        /// Add an existing metric packet object to our collection for the supplied packet.
        ///
        /// <param name="newDefinitionPacket">The new metric packet object to add.</param>
        internal MetricDefinition Add(MetricDefinitionPacket newDefinitionPacket)
        {
            //just do the null check - the rest of the checks (like dupe checks) are done in the normal add routine
            if (newDefinitionPacket == null)
            {
                throw new ArgumentNullException(nameof(newDefinitionPacket), "A metric packet object must be provided to add it to the collection.");
            }

            //create a new metric object to wrap the supplied metric packet
            MetricDefinition newDefinition = new MetricDefinition(this, newDefinitionPacket);

            //and call our mainstream add method which does the rest of our checks.
            Add(newDefinition);

            //return the newly added object so our caller doesn't have to go digging for it
            return newDefinition;
        }

        ///
        /// Retrieve a metric given its unique Id.
        ///
        /// <param name="metricId">The unique Id of the metric to retrieve</param>
        /// <returns></returns>
        public IMetric Metric(Guid metricId)
        {
            lock (m_Lock)
            {
                return m_MetricById[metricId];
            }
        }

        ///
        /// Determines whether the collection contains an element with the specified key.
        ///
        /// <param name="key">The key to locate in the collection</param>
        /// <returns>true if the collection contains an element with the key; otherwise, false.</returns>
        public bool ContainsKey(Guid key)
        {
            lock (m_Lock)
            {
                //gateway to our inner dictionary
                return m_Dictionary.ContainsKey(key);
            }
        }

        ///
        /// Determines whether the collection contains an element with the specified key.
        ///
        /// <param name="name">The metric name to locate in the collection</param>
        /// <returns>true if the collection contains an element with the key; otherwise, false.</returns>
        public bool ContainsKey(string name)
        {
            //protect ourself from a null before we do the trim (or we'll get an odd user the error won't understand)
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            lock (m_Lock)
            {
                //gateway to our alternate inner dictionary
                return m_DictionaryByName.ContainsKey(name.Trim());
            }
        }

        ///
        /// Determines whether the collection contains an element with the specified key.
        ///
        /// <param name="metricTypeName">The unique metric type</param>
        /// <param name="categoryName">The name of the category with which this definition is associated.</param>
        /// <param name="counterName">The name of the definition within the category.</param>
        /// <returns>true if the collection contains an element with the key; otherwise, false.</returns>
        public bool ContainsKey(string metricTypeName, string categoryName, string counterName)
        {
            //get the key for the provided values
            string key = MetricDefinition.GetKey(metricTypeName, categoryName, counterName);

            lock (m_Lock)
            {
                //gateway to our alternate inner dictionary
                return m_DictionaryByName.ContainsKey(key);
            }
        }

        ///
        /// Determines whether the collection contains an element with the specified key.
        ///
        /// <param name="key">The metric name to locate in the collection</param>
        /// <returns>true if the collection contains an element with the key; otherwise, false.</returns>
        public bool ContainsMetricKey(Guid key)
        {
            lock (m_Lock)
            {
                //gateway to our alternate inner dictionary
                return m_MetricById.ContainsKey(key);
            }
        }

        ///
        /// Retrieve an item from the collection by its key if present.  If not present, the default value of the object is returned.
        ///
        /// <param name="key">The key of the value to get.</param>
        /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param>
        /// <returns>true if the collection contains an element with the specified key; otherwise false.</returns>
        public bool TryGetValue(Guid key, out IMetricDefinition value)
        {
            lock (m_Lock)
            {
                //gateway to our inner dictionary try get value
                return m_Dictionary.TryGetValue(key, out value);
            }
        }

        ///
        /// Retrieve an item from the collection by its key if present.  If not present, the default value of the object is returned.
        ///
        /// <param name="name">The metric name to locate in the collection</param>
        /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param>
        /// <returns>true if the collection contains an element with the specified key; otherwise false.</returns>
        public bool TryGetValue(string name, out IMetricDefinition value)
        {
            //protect ourself from a null before we do the trim (or we'll get an odd user the error won't understand)
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            lock (m_Lock)
            {
                //gateway to our inner dictionary try get value
                return m_DictionaryByName.TryGetValue(name.Trim(), out value);
            }
        }

        ///
        /// Retrieve an item from the collection by its key if present.  If not present, the default value of the object is returned.
        ///
        /// <param name="metricTypeName">The unique metric type</param>
        /// <param name="categoryName">The name of the category with which this definition is associated.</param>
        /// <param name="counterName">The name of the definition within the category.</param>
        /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param>
        /// <returns>true if the collection contains an element with the specified key; otherwise false.</returns>
        /// <exception cref="ArgumentNullException">The provided metricsSystem, categoryName, or counterName was null.</exception>
        public bool TryGetValue(string metricTypeName, string categoryName, string counterName, out IMetricDefinition value)
        {
            //get the key for the provided values
            string key = MetricDefinition.GetKey( metricTypeName, categoryName, counterName );

            lock (m_Lock)
            {
                //gateway to our inner dictionary try get value
                return m_DictionaryByName.TryGetValue(key, out value);
            }
        }

        ///
        /// Retrieve an item from the collection by its key if present.  If not present, the default value of the object is returned.
        ///
        /// <param name="key">The key of the value to get.</param>
        /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param>
        /// <returns>true if the collection contains an element with the specified key; otherwise false.</returns>
        public bool TryGetMetricValue(Guid key, out IMetric value)
        {
            lock (m_Lock)
            {
                //gateway to our inner dictionary try get value
                return m_MetricById.TryGetValue(key, out value);
            }
        }

        #endregion

        #region IEnumerable<IMetricDefinition> Members

        IEnumerator<IMetricDefinition> IEnumerable<IMetricDefinition>.GetEnumerator()
        {
            //we use the list for enumeration
            return m_List.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            //we use the list for enumeration
            return m_List.GetEnumerator();
        }

        #endregion

        #region IList<IMetricDefinition> Members

        ///
        /// Searches for the specified value and returns the zero-based index of the first occurrence
        ///
        /// <param name="item"></param>
        /// <returns></returns>
        public int IndexOf(IMetricDefinition item)
        {
            lock (m_Lock)
            {
                return m_List.IndexOf(item);
            }
        }

        ///Inserting objects by index is not supported because the collection is sorted.
        ///<remarks>This method is implemented only for IList interface support and will throw an exception if called.</remarks>
        public void Insert(int index, IMetricDefinition item)
        {
            //we don't support setting an object by index; we are sorted.
            throw new NotSupportedException();
        }

        ///Removing objects by index is not supported because the collection is always read only.
        ///<remarks>This method is implemented only for IList interface support and will throw an exception if called.</remarks>
        public void RemoveAt(int index)
        {
            throw new NotSupportedException();
        }

        ///
        /// Retrieve metric packet by numeric index in collection.
        ///
        /// <param name="index"></param>
        /// <returns></returns>
        public IMetricDefinition this[int index]
        {
            get
            {
                lock (m_Lock)
                {
                    return m_List[index];
                }
            }
            set
            {
                //we don't want to support setting an object by index, we are sorted.
                throw new NotSupportedException();
            }
        }

        ///
        /// Retrieve metric object by its Id
        ///
        /// <param name="ID"></param>
        /// <returns></returns>
        public IMetricDefinition this[Guid ID]
        {
            get
            {
                lock (m_Lock)
                {
                    return m_Dictionary[ID];
                }
            }
        }

        ///
        /// Retrieve metric object by its name
        ///
        /// <param name="name"></param>
        /// <returns></returns>
        public IMetricDefinition this[string name]
        {
            get
            {
                //protect ourself from a null before we do the trim (or we'll get an odd user the error won't understand)
                if (string.IsNullOrEmpty(name))
                {
                    throw new ArgumentNullException(nameof(name));
                }

                lock (m_Lock)
                {
                    return m_DictionaryByName[name.Trim()];
                }
            }
        }

        ///
        /// Retrieve metric object by its type, category, and counter names.
        ///
        /// <param name="metricTypeName">The unique metric type</param>
        /// <param name="categoryName">The name of the category with which this definition is associated.</param>
        /// <param name="counterName">The name of the definition within the category.</param>
        /// <returns></returns>
        public IMetricDefinition this[string metricTypeName, string categoryName, string counterName]
        {
            get
            {
                //create the key from the parts we got
                string key = MetricDefinition.GetKey( metricTypeName, categoryName, counterName );
                lock (m_Lock)
                {
                    return m_DictionaryByName[key];
                }
            }
        }

        #endregion

        #region ICollection<IMetricDefinition> Members

        ///
        /// Add an existing MetricDefinition item to this collection.
        ///
        /// <remarks>If the supplied MetricDefinitin item is already in the collection, an exception will be thrown.</remarks>
        /// <param name="item">The new MetricDefinition item to add.</param>
        public void Add(IMetricDefinition item)
        {
            //we really don't want to support this method, but we have to for ICollection<T> compatibility.  So we're going to ruthlessly
            //verify that the metric object was created correctly.

            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            //we're about to modify the collection, get a lock.  We don't want the lock to cover the changed event since
            //we really don't know how long that will take, and it could be deadlock prone.
            lock (m_Lock)
            {
                //make sure we don't already have it
                if (m_Dictionary.ContainsKey(item.Id))
                {
                    throw new ArgumentException("The specified metric definition item is already in the collection.", nameof(item));
                }

                if (m_DictionaryByName.ContainsKey(item.Name))
                {
                    throw new ArgumentException("A metric definition item for the same metric is already in the collection.", nameof(item));
                }

                //add it to both lookup collections
                m_Dictionary.Add(item.Id, item);
                m_DictionaryByName.Add(item.Name, item);
                m_List.Add(item);
            }

            //and fire our event
            OnCollectionChanged(new CollectionChangedEventArgs<IMetricDefinitionCollection, IMetricDefinition>(this, item, CollectionAction.Added));
        }

        ///
        /// Clearing objects is not supported.
        ///
        /// <remarks>This method is implemented only for ICollection interface support and will throw an exception if called.</remarks>
        public void Clear()
        {
            throw new NotSupportedException();
        }

        ///
        /// Determines whether an element is in the collection.
        ///
        /// <remarks>This method determines equality using the default equality comparer for the type of values in the list.  It performs
        /// a linear search and therefore is an O(n) operation.</remarks>
        /// <param name="item">The object to locate in the collection.</param>
        /// <returns>true if the item is found in the collection; otherwise false.</returns>
        public bool Contains(IMetricDefinition item)
        {
            lock (m_Lock)
            {
                //here we are relying on the fact that the comment object implements IComparable sufficiently to guarantee uniqueness
                return m_List.Contains(item);
            }
        }

        ///
        /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array.
        ///
        /// <remarks>Elements are copied to the array in the same order in which the enumerator iterates them from the collection.  The provided array
        /// must be large enough to contain the entire contents of this collection starting at the specified index.  This method is an O(n) operation.</remarks>
        /// <param name="array">The one-dimensional array that is the destination of the elements copied from the collection.  The Array must have zero-based indexing.</param>
        /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
        public void CopyTo(IMetricDefinition[] array, int arrayIndex)
        {
            lock (m_Lock)
            {
                m_List.CopyTo(array, arrayIndex);
            }
        }

        ///
        /// Copy the entire collection of metric definitions into a new array.
        ///
        /// <returns>A new array containing all of the metric definitions in this collection.</returns>
        public IMetricDefinition[] ToArray()
        {
            lock (m_Lock)
            {
                return m_List.ToArray();
            }
        }

        ///
        /// The number of items currently in the collection
        ///
        public int Count
        {
            get
            {
                lock (m_Lock)
                {
                    return m_List.Count;
                }
            }
        }

        ///
        /// Indicates if the collection is read only and therefore can't have items added or removed.
        ///
        /// <remarks>This collection is never read-only, however removing items is not supported.
        /// This property is required for ICollection compatibility</remarks>
        public bool IsReadOnly
        {
            get { return false; }
        }

        ///
        /// Removing objects is not supported.
        ///
        /// <remarks>This method is implemented only for ICollection interface support and will throw an exception if called.</remarks>
        /// <param name="item">The MetricDefinition item to remove.</param>
        public bool Remove(IMetricDefinition item)
        {
            throw new NotSupportedException();
        }

        #endregion
    }
}


text:
"""Logic to handle uprevving packages."""

from __future__ import print_function

import collections
import enum
import filecmp
import functools
import os
import re
import sys
from typing import List, Optional, Tuple

from chromite.cbuildbot import manifest_version
from chromite.lib import constants
from chromite.lib import cros_build_lib
from chromite.lib import cros_logging as logging
from chromite.lib import osutils
from chromite.lib import parallel
from chromite.lib import portage_util
from chromite.lib.chroot_lib import Chroot

assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'

CHROME_VERSION_REGEX = r'\d+\.\d+\.\d+\.\d+'

# The directory relative to the source root housing the chrome packages.
_CHROME_OVERLAY_DIR = 'src/third_party/chromiumos-overlay'
_CHROME_OVERLAY_PATH = os.path.join(constants.SOURCE_ROOT, _CHROME_OVERLAY_DIR)

GitRef = collections.namedtuple('GitRef', ['path', 'ref', 'revision'])

class Error(Exception):
  """Base error class for the module."""

class NoUnstableEbuildError(Error):
  """When no unstable ebuild can be found."""

class ChromeEBuild(portage_util.EBuild):
  """Thin sub-class of EBuild that adds a few small helpers."""
  chrome_version_re = re.compile(r'.*-(%s|9999).*' % CHROME_VERSION_REGEX)
  chrome_version = ''

  def __init__(self, path):
    portage_util.EBuild.__init__(self, path)
    re_match = self.chrome_version_re.match(self.ebuild_path_no_revision)
    if re_match:
      self.chrome_version = re_match.group(1)

  def __str__(self):
    return self.ebuild_path

  @property
  def is_unstable(self):
    return not self.is_stable

  @property
  def atom(self):
    return '%s-%s' % (self.package, self.version)

def get_chrome_version_from_refs(refs):
  """Get the chrome version to use from the list of provided tags.

  Args:
    refs (list[GitRef]): The tags to parse for the best chrome version.

  Returns:
    str: The chrome version to use.
  """
  assert refs

  # Each tag is a chrome version string, e.g. "78.0.3876.1", so extract the
  # tag name from the ref, e.g. "refs/tags/78.0.3876.1".
  versions = [ref.ref.split('/')[-1] for ref in refs]
  return best_chrome_version(versions)

def best_chrome_version(versions):
  # Convert each version from a string like "78.0.3876.1" to a list of ints
  # to compare them, find the most recent (max), and then reconstruct the
  # version string.
  assert versions

  version = max([int(part) for part in v.split('.')] for v in versions)
  return '.'.join(str(part) for part in version)

def best_chrome_ebuild(ebuilds):
  """Determine the best/newest chrome ebuild from a list of ebuilds."""
  assert ebuilds

  version = best_chrome_version(ebuild.chrome_version for ebuild in ebuilds)
  candidates = [
      ebuild for ebuild in ebuilds if ebuild.chrome_version == version
  ]

  if len(candidates) == 1:
    # Only one, return it.
    return candidates[0]

  # Compare revisions to break a tie.
  best = candidates[0]
  for candidate in candidates[1:]:
    if best.current_revision < candidate.current_revision:
      best = candidate

  return best

def find_chrome_ebuilds(package_dir):
  """Return a tuple of chrome's unstable ebuild and stable ebuilds.

  Args:
    package_dir: The path to where the package ebuild is stored.

  Returns:
    Tuple [unstable_ebuild, stable_ebuilds].

  Raises:
    Exception: if no unstable ebuild exists for Chrome.
  """
  stable_ebuilds = []
  unstable_ebuilds = []

  for ebuild_path in portage_util.EBuild.List(package_dir):
    ebuild = ChromeEBuild(ebuild_path)
    if not ebuild.chrome_version:
      logging.warning('Poorly formatted ebuild found at %s', ebuild_path)
      continue

    if ebuild.is_unstable:
      unstable_ebuilds.append(ebuild)
    else:
      stable_ebuilds.append(ebuild)

  # Apply some sanity checks.
  if not unstable_ebuilds:
    raise NoUnstableEbuildError('Missing 9999 ebuild for %s' % package_dir)
  if not stable_ebuilds:
    logging.warning('Missing stable ebuild for %s', package_dir)

  return best_chrome_ebuild(unstable_ebuilds), stable_ebuilds

@enum.unique
class Outcome(enum.Enum):
  """An enum representing the possible outcomes of a package uprev attempt.

  Variants:
    NEWER_VERSION_EXISTS: An ebuild with a higher version than the requested
        version already exists, so no change occurred.
    SAME_VERSION_EXISTS: An ebuild with the same version as the requested
        version already exists and the stable & unstable ebuilds are identical,
        so no change occurred.
    REVISION_BUMP: An ebuild with the same version as the requested version
        already exists but the contents of the stable & unstable ebuilds differ,
        so the stable ebuild was updated and the revision number was increased.
    VERSION_BUMP: The requested uprev version was greater than that of any
        stable ebuild that exists, so a new stable ebuild was created at the
        requested version.
    NEW_EBUILD_CREATED: No stable ebuild for this package existed yet, so a new
        stable ebuild was created at the requested version.
  """
  NEWER_VERSION_EXISTS = enum.auto()
  SAME_VERSION_EXISTS = enum.auto()
  REVISION_BUMP = enum.auto()
  VERSION_BUMP = enum.auto()
  NEW_EBUILD_CREATED = enum.auto()

class UprevResult(object):
  """The result of a package uprev attempt.

  This object is truthy if files were altered by the uprev and falsey if no
  files were changed.

  Attributes:
    outcome: An instance of Outcome documenting what change took place.
    best_ebuild: An Ebuild object representing the highest available version of
        the package after the uprev. May differ from the requested version in
        some cases.
  """

  def __init__(self, outcome: Outcome, best_ebuild: portage_util.EBuild):
    self.outcome = outcome
    self.best_ebuild = best_ebuild

  def __bool__(self):
    """Returns True only if this Result indicates that a file was modified."""
    return self.outcome in (
        Outcome.REVISION_BUMP,
        Outcome.VERSION_BUMP,
        Outcome.NEW_EBUILD_CREATED,
    )

class UprevChromeManager(object):
  """Class to handle uprevving chrome and its related packages."""

  def __init__(self, version, build_targets=None, overlay_dir=None,
               chroot=None):
    self._version = version
    self._build_targets = build_targets or []
    self._new_ebuild_files = []
    self._removed_ebuild_files = []
    self._overlay_dir = str(overlay_dir or _CHROME_OVERLAY_PATH)
    self._chroot = chroot

  @property
  def modified_ebuilds(self):
    return self._new_ebuild_files + self._removed_ebuild_files

  def uprev(self, package: str) -> UprevResult:
    """Uprev a chrome package."""
    package_dir = os.path.join(self._overlay_dir, package)
    package_name = os.path.basename(package)

    # Find the unstable (9999) ebuild and any existing stable ebuilds.
    unstable_ebuild, stable_ebuilds = find_chrome_ebuilds(package_dir)
    # Find the best stable candidate to uprev -- the one that will be replaced.
    should_uprev, candidate = self._find_chrome_uprev_candidate(stable_ebuilds)

    if not should_uprev and candidate:
      return UprevResult(Outcome.NEWER_VERSION_EXISTS, candidate)

    result = self._mark_as_stable(candidate, unstable_ebuild, package_name,
                                  package_dir)

    # If result is falsey then no files changed, and we don't need to do any
    # clean-up.
    if not result:
      return result

    self._new_ebuild_files.append(result.best_ebuild.ebuild_path)
    if candidate and not candidate.IsSticky():
      osutils.SafeUnlink(candidate.ebuild_path)
      self._removed_ebuild_files.append(candidate.ebuild_path)

    if self._build_targets:
      self._clean_stale_package(result.best_ebuild.atom)

    return result

  def _find_chrome_uprev_candidate(
      self, stable_ebuilds: List[ChromeEBuild]
  ) -> Tuple[bool, Optional[ChromeEBuild]]:
    """Find the ebuild to replace.

    Args:
      stable_ebuilds: All stable ebuilds that were found.

    Returns:
      A (okay_to_uprev, best_stable_candidate) tuple.
      okay_to_uprev: A bool indicating that an uprev should proceed. False if
          a newer stable ebuild than the requested version exists.
      best_stable_candidate: The highest version stable ebuild that exists, or
          None if no stable ebuilds exist.
    """
    candidates = []
    # This is an artifact from the old process.
    chrome_branch_re = re.compile(r'%s.*_rc.*' % CHROME_VERSION_REGEX)
    for ebuild in stable_ebuilds:
      if chrome_branch_re.search(ebuild.version):
        candidates.append(ebuild)

    if not candidates:
      return (True, None)

    candidate = best_chrome_ebuild(candidates)

    # A candidate is only a valid uprev candidate if its chrome version
    # is no better than the target version. We can uprev equal versions
    # (i.e. a revision bump), but not older. E.g.:
    # Case 1 - Uprev: self._version = 78.0.0.0, Candidate = 77.0.0.0
    # Case 2 - Uprev: self._version = 78.0.0.0, Candidate = 78.0.0.0
    # Case 3 - Skip:  self._version = 78.0.0.0, Candidate = 79.0.0.0
    best_version = best_chrome_version(
        [self._version, candidate.chrome_version])
    if self._version == best_version:
      # Cases 1 and 2.
      return (True, candidate)

    logging.warning('A chrome ebuild candidate with a higher version than the '
                    'requested uprev version was found.')
    logging.debug('Requested uprev version: %s', self._version)
    logging.debug('Candidate version found: %s', candidate.chrome_version)
    return (False, candidate)

  def _mark_as_stable(self, stable_candidate, unstable_ebuild, package_name,
                      package_dir) -> UprevResult:
    """Uprevs the chrome ebuild specified by chrome_rev.

    This is the main function that uprevs the chrome_rev from a stable candidate
    to its new version.

    Args:
      stable_candidate: ebuild that corresponds to the stable ebuild we are
        revving from.  If None, builds the a new ebuild given the version
        and logic for chrome_rev type with revision set to 1.
      unstable_ebuild: ebuild corresponding to the unstable ebuild for chrome.
      package_name: package name.
      package_dir: Path to the chromeos-chrome package dir.

    Returns:
      Full portage version atom (including rc's, etc) that was revved.
    """

    def _is_new_ebuild_redundant(uprevved_ebuild, stable_ebuild) -> bool:
      """Returns True if the new ebuild is redundant.

      This is True if there if the current stable ebuild is the exact same copy
      of the new one.
      """
      if (stable_ebuild and
          stable_candidate.chrome_version == uprevved_ebuild.chrome_version):
        return filecmp.cmp(
            uprevved_ebuild.ebuild_path,
            stable_ebuild.ebuild_path,
            shallow=False)
      else:
        return False

    # Case where we have the last stable candidate with same version just rev.
    if stable_candidate and stable_candidate.chrome_version == self._version:
      new_ebuild_path = '%s-r%d.ebuild' % (
          stable_candidate.ebuild_path_no_revision,
          stable_candidate.current_revision + 1)
      rev_bump = True
    else:
      pf = '%s-%s_rc-r1' % (package_name, self._version)
      new_ebuild_path = os.path.join(package_dir, '%s.ebuild' % pf)
      rev_bump = False

    portage_util.EBuild.MarkAsStable(unstable_ebuild.ebuild_path,
                                     new_ebuild_path, {})
    new_ebuild = ChromeEBuild(new_ebuild_path)

    # Determine whether this is ebuild is redundant.
    if _is_new_ebuild_redundant(new_ebuild, stable_candidate):
      msg = 'Previous ebuild with same version found and ebuild is redundant.'
      logging.info(msg)
      os.unlink(new_ebuild_path)
      return UprevResult(Outcome.SAME_VERSION_EXISTS, stable_candidate)

    if rev_bump:
      return UprevResult(Outcome.REVISION_BUMP, new_ebuild)
    elif stable_candidate:
      # If a stable ebuild already existed and rev_bump is False, then a stable
      # ebuild with a new major version has been generated.
      return UprevResult(Outcome.VERSION_BUMP, new_ebuild)
    else:
      # If no stable ebuild existed, then we've created the first stable ebuild
      # for this package.
      return UprevResult(Outcome.NEW_EBUILD_CREATED, new_ebuild)

  def _clean_stale_package(self, package):
    clean_stale_packages([package], self._build_targets, chroot=self._chroot)

class UprevOverlayManager(object):
  """Class to handle the uprev process for a set of overlays.

  This handles the standard uprev process that covers most packages. There are
  also specialized uprev processes for a few specific packages not handled by
  this class, e.g. chrome and android.

  TODO (saklein): The manifest object for this class is used deep in the
    portage_util uprev process. Look into whether it's possible to redo it so
    the manifest isn't required.
  """

  def __init__(self, overlays, manifest, build_targets=None, chroot=None,
               output_dir=None):
    """Init function.

    Args:
      overlays (list[str]): The overlays to search for ebuilds.
      manifest (git.ManifestCheckout): The manifest object.
      build_targets (list[build_target_lib.BuildTarget]|None): The build
        targets to clean in |chroot|, if desired. No effect unless |chroot| is
        provided.
      chroot (chroot_lib.Chroot|None): The chroot to clean, if desired.
      output_dir (str|None): The path to optionally dump result files.
    """
    self.overlays = overlays
    self.manifest = manifest
    self.build_targets = build_targets or []
    self.chroot = chroot
    self.output_dir = output_dir

    self._revved_packages = None
    self._new_package_atoms = None
    self._new_ebuild_files = None
    self._removed_ebuild_files = None
    self._overlay_ebuilds = None

  @property
  def modified_ebuilds(self):
    if self._new_ebuild_files is not None:
      return self._new_ebuild_files + self._removed_ebuild_files
    else:
      return []

  def uprev(self):
    self._populate_overlay_ebuilds()

    with parallel.Manager() as manager:
      # Contains the list of packages we actually revved.
      self._revved_packages = manager.list()
      # The new package atoms for cleanup.
      self._new_package_atoms = manager.list()
      # The list of added ebuild files.
      self._new_ebuild_files = manager.list()
      # The list of removed ebuild files.
      self._removed_ebuild_files = manager.list()

      inputs = [[overlay] for overlay in self.overlays]
      parallel.RunTasksInProcessPool(self._uprev_overlay, inputs)

      self._revved_packages = list(self._revved_packages)
      self._new_package_atoms = list(self._new_package_atoms)
      self._new_ebuild_files = list(self._new_ebuild_files)
      self._removed_ebuild_files = list(self._removed_ebuild_files)

    self._clean_stale_packages()

    if self.output_dir and os.path.exists(self.output_dir):
      # Write out dumps of the results. This is largely meant for sanity
      # checking results.
      osutils.WriteFile(os.path.join(self.output_dir, 'revved_packages'),
                        '\n'.join(self._revved_packages))
      osutils.WriteFile(os.path.join(self.output_dir, 'new_package_atoms'),
                        '\n'.join(self._new_package_atoms))
      osutils.WriteFile(os.path.join(self.output_dir, 'new_ebuild_files'),
                        '\n'.join(self._new_ebuild_files))
      osutils.WriteFile(os.path.join(self.output_dir, 'removed_ebuild_files'),
                        '\n'.join(self._removed_ebuild_files))

  def _uprev_overlay(self, overlay):
    """Execute uprevs for an overlay.

    Args:
      overlay: The overlay to uprev.
    """
    if not os.path.isdir(overlay):
      logging.warning('Skipping %s, which is not a directory.', overlay)
      return

    ebuilds = self._overlay_ebuilds.get(overlay, [])
    if not ebuilds:
      return

    inputs = [[overlay, ebuild] for ebuild in ebuilds]
    parallel.RunTasksInProcessPool(self._uprev_ebuild, inputs)

  def _uprev_ebuild(self, overlay, ebuild):
    """Work on a single ebuild.

    Args:
      overlay: The overlay the ebuild belongs to.
      ebuild: The ebuild to work on.
    """
    logging.debug('Working on %s, info %s', ebuild.package,
                  ebuild.cros_workon_vars)
    try:
      result = ebuild.RevWorkOnEBuild(
          os.path.join(constants.SOURCE_ROOT, 'src'), self.manifest)
    except portage_util.InvalidUprevSourceError as e:
      logging.error('An error occurred while uprevving %s: %s',
                    ebuild.package, e)
      raise
    except portage_util.EbuildVersionError as e:
      logging.warning('An error occurred while uprevving %s, skipping: %s',
                      ebuild.package, e)
      return
    except (OSError, IOError):
      logging.warning(
          'Cannot rev %s\n'
          'Note you will have to go into %s '
          'and reset the git repo yourself.', ebuild.package, overlay)
      raise

    if result:
      new_package, ebuild_path_to_add, ebuild_path_to_remove = result

      if ebuild_path_to_add:
        self._new_ebuild_files.append(ebuild_path_to_add)
      if ebuild_path_to_remove:
        osutils.SafeUnlink(ebuild_path_to_remove)
        self._removed_ebuild_files.append(ebuild_path_to_remove)

      self._revved_packages.append(ebuild.package)
      self._new_package_atoms.append('=%s' % new_package)

  def _populate_overlay_ebuilds(self):
    """Populates the overlay to ebuilds mapping."""
    # See crrev.com/c/1257944 for origins of this.
    root_version = manifest_version.VersionInfo.from_repo(constants.SOURCE_ROOT)
    subdir_removal = manifest_version.VersionInfo('10363.0.0')
    require_subdir_support = root_version < subdir_removal

    # Parameters lost to the current narrow implementation.
    use_all = True
    package_list = []
    force = False

    overlay_ebuilds = {}
    inputs = [[overlay, use_all, package_list, force, require_subdir_support]
              for overlay in self.overlays]
    result = parallel.RunTasksInProcessPool(portage_util.GetOverlayEBuilds,
                                            inputs)
    for idx, ebuilds in enumerate(result):
      overlay_ebuilds[self.overlays[idx]] = ebuilds

    self._overlay_ebuilds = overlay_ebuilds

  def _clean_stale_packages(self):
    """Cleans up stale package info from a previous build."""
    clean_stale_packages(self._new_package_atoms, self.build_targets,
                         chroot=self.chroot)

def clean_stale_packages(new_package_atoms, build_targets, chroot=None):
  """Cleans up stale package info from a previous build."""
  if new_package_atoms:
    logging.info('Cleaning up stale packages %s.', new_package_atoms)

  chroot = chroot or Chroot()

  if cros_build_lib.IsOutsideChroot() and not chroot.exists():
    logging.warning('Unable to clean packages. No chroot to enter.')
    return

  # First unmerge all the packages for a board, then eclean it.
  # We need these two steps to run in order (unmerge/eclean),
  # but we can let all the boards run in parallel.
  def _do_clean_stale_packages(board):
    if board:
      suffix = '-' + board
      runcmd = cros_build_lib.run
    else:
      suffix = ''
      runcmd = cros_build_lib.sudo_run

    if cros_build_lib.IsOutsideChroot():
      # Setup runcmd with the chroot arguments once.
      runcmd = functools.partial(
          runcmd, enter_chroot=True, chroot_args=chroot.get_enter_args())

    emerge, eclean = 'emerge' + suffix, 'eclean' + suffix
    if not osutils.FindMissingBinaries([emerge, eclean]):
      if new_package_atoms:
        # If nothing was found to be unmerged, emerge will exit(1).
        result = runcmd(
            [emerge, '-q', '--unmerge'] + new_package_atoms,
            extra_env={'CLEAN_DELAY': '0'},
            check=False,
            cwd=constants.SOURCE_ROOT)
        if result.returncode not in (0, 1):
          raise cros_build_lib.RunCommandError('unexpected error', result)

      runcmd([eclean, '-d', 'packages'],
             cwd=constants.SOURCE_ROOT,
             capture_output=True)

  tasks = []
  for build_target in build_targets:
    tasks.append([build_target.name])
  tasks.append([None])

  parallel.RunTasksInProcessPool(_do_clean_stale_packages, tasks)

redpajama_set_name: RedPajamaGithub


text:
<?php

defined('JPATH_PLATFORM') or die;

JFormHelper::loadFieldClass('list');

/**
 * Form Field class for the Joomla Platform.
 * Provides a select list of session handler options.
 *
 * @package     Joomla.Platform
 * @subpackage  Form
 * @since       11.1
 */
class JFormFieldSessionHandler extends JFormFieldList
{

	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  11.1
	 */
	protected $type = 'SessionHandler';

	/**
	 * Method to get the session handler field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   11.1
	 */
	protected function getOptions()
	{
		// Initialize variables.
		$options = array();

		// Get the options from JSession.
		foreach (JSession::getStores() as $store)
		{
			$options[] = JHtml::_('select.option', $store, JText::_('JLIB_FORM_VALUE_SESSION_' . $store), 'value', 'text');
		}

		// Merge any additional options in the XML definition.
		$options = array_merge(parent::getOptions(), $options);

		return $options;
	}
}


text:
module Azure::ApiManagement::Mgmt::V2017_03_01
  module Models
    #
    # Parameters supplied to the Deploy Configuration operation.
    #
    class DeployConfigurationParameters

      include MsRestAzure

      # @return [String] The name of the Git branch from which the
      # configuration is to be deployed to the configuration database.
      attr_accessor :branch

      # @return [Boolean] The value enforcing deleting subscriptions to
      # products that are deleted in this update.
      attr_accessor :force

      #
      # Mapper for DeployConfigurationParameters class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'DeployConfigurationParameters',
          type: {
            name: 'Composite',
            class_name: 'DeployConfigurationParameters',
            model_properties: {
              branch: {
                client_side_validation: true,
                required: true,
                serialized_name: 'branch',
                type: {
                  name: 'String'
                }
              },
              force: {
                client_side_validation: true,
                required: false,
                serialized_name: 'force',
                type: {
                  name: 'Boolean'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
jQuery(document).ready( function ( $ ) {
    var li_subscribe_flag = $.cookie('li_subscribe');

    if ( !leadin_subscribe_check_mobile($) )
    {
        if ( !li_subscribe_flag )
        {
            leadin_check_visitor_status($.cookie("li_hash"), function ( data ) {
                if ( data != 'subscribe' )
                {
                    $.cookie("li_subscribe", 'show', {path: "/", domain: ""});
                    bind_leadin_subscribe_widget();
                }
                else
                {
                    $.cookie("li_subscribe", 'ignore', {path: "/", domain: ""});
                }
            });
        }
        else
        {
            if ( li_subscribe_flag == 'show' )
                bind_leadin_subscribe_widget();
        }
    }
});

function bind_leadin_subscribe_widget ()
{
    (function(){
        var $ = jQuery;
        var subscribe = {};

        subscribe.vex = undefined;

        subscribe.init = function() {
            $(window).scroll(function() {
                if ($(window).scrollTop() + $(window).height() > $(document).height() / 2) {
                    subscribe.open();
                } else {
                    //subscribe.close();
                }
            });
        };

        subscribe.open = function() {
            if (subscribe.vex) {
                return subscribe._open();
            }

            subscribe.vex = vex.dialog.open({
                showCloseButton: true,
                className: 'leadin-subscribe ' + $('#leadin-subscribe-vex-class').val(),
                message: $('#leadin-subscribe-heading').val(),
                input: '<input id="leadin-subscribe-email" name="email" type="email" placeholder="Email address" required />' +
                    (($('#leadin-subscribe-name-fields').val()==0) ? '' : '<input id="leadin-subscribe-fname" name="fname" type="text" placeholder="First Name" required /><input id="leadin-subscribe-lname" name="lname" type="text" placeholder="Last Name" required />') +
                    (($('#leadin-subscribe-phone-field').val()==0) ? '' : '<input id="leadin-subscribe-phone" name="phone" type="tel" placeholder="Phone" required />'),
                buttons: [$.extend({}, vex.dialog.buttons.YES, { text: ( $('#leadin-subscribe-btn-label').val() ? $('#leadin-subscribe-btn-label').val() : 'SUBSCRIBE' ) })],
                onSubmit: function ( data )
                {
                    $('.vex-dialog-form').fadeOut(300, function ( e ) {
                        $('.vex-dialog-form').html(
                            '

' +
                            '
Thanks!
You should receive a confirmation email in your inbox shortly.
' +
                            '
' +
                                'Powered by LeadIn' +
                                '' +
                            '
'
                        ).css('text-align', 'center').fadeIn(250);
                    });

                    leadin_submit_form($('.leadin-subscribe form'), $, 'subscribe');
                    $.cookie("li_subscribe", 'ignore', {path: "/", domain: ""});
                    return false;
                },
                callback: function(data) {
                    if (data === false) {
                        $.cookie("li_subscribe", 'ignore', {path: "/", domain: ""});
                    }

                    $.cookie("li_subscribe", 'ignore', {path: "/", domain: ""});
                }
            });

            //leadin_subscribe_show();

            $('.leadin-subscribe form.vex-dialog-form').append('Powered by LeadIn');
        };

        subscribe._open = function() {
            subscribe.vex.parent().removeClass('vex-closing');
        }

        subscribe.close = function() {

            if (!subscribe.vex) {
                return;
            }
            subscribe.vex.parent().addClass('vex-closing');
        }

        subscribe.init();
        window.subscribe = subscribe;
    })();
}

function leadin_subscribe_check_mobile( $ )
{
    var is_mobile = false;

    if ( $('#leadin-subscribe-mobile-check').css('display')=='none' )
        is_mobile = true;

    return is_mobile;
}

function leadin_subscribe_show ()
{
    jQuery.ajax({
        type: 'POST',
        url: li_ajax.ajax_url,
        data: {
            "action": "leadin_subscribe_show"
        },
        success: function(data){
        },
        error: function ( error_data ) {
            //alert(error_data);
        }
    });
}


text:
<?php

namespace Theintz\PhpDaemon\Lock;

use Theintz\PhpDaemon\IPlugin;

/**
 * Implements the lock provider and plugin interfaces to make development easier.
 * Before version 2.0 of PHP Simple Daemon a lock provider was required, so this was used to satisfy that requirement
 * during development.
 *
 * @author Shane Harter
 * @since 2011-07-28
 */
class Null extends Lock implements IPlugin
{
	public function setup()
	{
		// Nothing to setup
	}

	public function teardown()
	{
		// Nothing to teardown
	}

	public function check_environment(array $errors = array())
	{
		// Nothing to check
		return array();
	}

	public function set()
	{
		// Nothing to set
	}

	protected function get()
	{
		// False is a good thing -- it means no lock was detected.
		return false;
	}
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>LogImpl.Fatal Method (Object, Exception)</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

LogImpl.Fatal Method (Object, Exception)

 Logs a message object with the FATAL level

        [Visual Basic]

Overridable Overloads Public Sub Fatal( _
   ByVal message As Object, _
   ByVal exception As Exception _
) _
    Implements ILog.Fatal

        [C#]

public virtual void Fatal(
   object message,
   Exception exception
);

Parameters

          message

The message object to log.

          exception

The exception to log, including its stack trace.

Implements

        ILog.Fatal

Remarks

 Logs a message object with the FATAL level including the stack trace of the Exception exception passed as a parameter.

 See the Fatal form for more detailed information.

See Also

LogImpl Class | log4net.Core Namespace | LogImpl.Fatal Overload List | Fatal
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="Fatal method"></param><param name="Keyword" value="Fatal method, LogImpl class"></param><param name="Keyword" value="LogImpl.Fatal method"></param></object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
import './obligation-spec';
import './ts-test-spec';


text:
package lombok.javac.handlers.singulars;

import static lombok.javac.Javac.*;
import static lombok.javac.handlers.JavacHandlerUtil.*;

import java.util.Arrays;

import lombok.core.LombokImmutableList;
import lombok.core.handlers.HandlerUtil;
import lombok.javac.JavacNode;
import lombok.javac.JavacTreeMaker;
import lombok.javac.handlers.JavacHandlerUtil;
import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer;
import lombok.javac.handlers.JavacSingularsRecipes.SingularData;

import org.mangosdk.spi.ProviderFor;

import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;

@ProviderFor(JavacSingularizer.class)
public class JavacJavaUtilMapSingularizer extends JavacJavaUtilSingularizer {
	@Override public LombokImmutableList<String> getSupportedTypes() {
		return LombokImmutableList.of("java.util.Map", "java.util.SortedMap", "java.util.NavigableMap");
	}

	@Override public java.util.List<Name> listFieldsToBeGenerated(SingularData data, JavacNode builderType) {
		if (useGuavaInstead(builderType)) {
			return guavaMapSingularizer.listFieldsToBeGenerated(data, builderType);
		}

		String p = data.getPluralName().toString();
		return Arrays.asList(builderType.toName(p + "$key"), builderType.toName(p + "$value"));
	}

	@Override public java.util.List<Name> listMethodsToBeGenerated(SingularData data, JavacNode builderType) {
		if (useGuavaInstead(builderType)) {
			return guavaMapSingularizer.listMethodsToBeGenerated(data, builderType);
		}

		return super.listMethodsToBeGenerated(data, builderType);
	}

	@Override public java.util.List<JavacNode> generateFields(SingularData data, JavacNode builderType, JCTree source) {
		if (useGuavaInstead(builderType)) {
			return guavaMapSingularizer.generateFields(data, builderType, source);
		}

		JavacTreeMaker maker = builderType.getTreeMaker();

		JCVariableDecl buildKeyField; {
			JCExpression type = JavacHandlerUtil.chainDots(builderType, "java", "util", "ArrayList");
			type = addTypeArgs(1, false, builderType, type, data.getTypeArgs(), source);
			buildKeyField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), builderType.toName(data.getPluralName() + "$key"), type, null);
		}

		JCVariableDecl buildValueField; {
			JCExpression type = JavacHandlerUtil.chainDots(builderType, "java", "util", "ArrayList");
			List<JCExpression> tArgs = data.getTypeArgs();
			if (tArgs != null && tArgs.size() > 1) tArgs = tArgs.tail;
			else tArgs = List.nil();
			type = addTypeArgs(1, false, builderType, type, tArgs, source);
			buildValueField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), builderType.toName(data.getPluralName() + "$value"), type, null);
		}

		JavacNode valueFieldNode = injectFieldAndMarkGenerated(builderType, buildValueField);
		JavacNode keyFieldNode = injectFieldAndMarkGenerated(builderType, buildKeyField);

		return Arrays.asList(keyFieldNode, valueFieldNode);
	}

	@Override public void generateMethods(SingularData data, boolean deprecate, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
		if (useGuavaInstead(builderType)) {
			guavaMapSingularizer.generateMethods(data, deprecate, builderType, source, fluent, chain);
			return;
		}

		JavacTreeMaker maker = builderType.getTreeMaker();
		Symtab symbolTable = builderType.getSymbolTable();

		JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID));
		JCStatement returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
		generateSingularMethod(deprecate, maker, returnType, returnStatement, data, builderType, source, fluent);

		returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID));
		returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
		generatePluralMethod(deprecate, maker, returnType, returnStatement, data, builderType, source, fluent);

		returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID));
		returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
		generateClearMethod(deprecate, maker, returnType, returnStatement, data, builderType, source);
	}

	private void generateClearMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source) {
		JCModifiers mods = makeMods(maker, builderType, deprecate);

		List<JCTypeParameter> typeParams = List.nil();
		List<JCExpression> thrown = List.nil();
		List<JCVariableDecl> params = List.nil();
		List<JCExpression> jceBlank = List.nil();

		JCExpression thisDotKeyField = chainDots(builderType, "this", data.getPluralName() + "$key");
		JCExpression thisDotKeyFieldDotClear = chainDots(builderType, "this", data.getPluralName() + "$key", "clear");
		JCExpression thisDotValueFieldDotClear = chainDots(builderType, "this", data.getPluralName() + "$value", "clear");
		JCStatement clearKeyCall = maker.Exec(maker.Apply(jceBlank, thisDotKeyFieldDotClear, jceBlank));
		JCStatement clearValueCall = maker.Exec(maker.Apply(jceBlank, thisDotValueFieldDotClear, jceBlank));
		JCExpression cond = maker.Binary(CTC_NOT_EQUAL, thisDotKeyField, maker.Literal(CTC_BOT, null));
		JCBlock clearCalls = maker.Block(0, List.of(clearKeyCall, clearValueCall));
		JCStatement ifSetCallClear = maker.If(cond, clearCalls, null);
		List<JCStatement> statements = returnStatement != null ? List.of(ifSetCallClear, returnStatement) : List.of(ifSetCallClear);

		JCBlock body = maker.Block(0, statements);
		Name methodName = builderType.toName(HandlerUtil.buildAccessorName("clear", data.getPluralName().toString()));
		JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null);
		injectMethod(builderType, method);
	}

	private void generateSingularMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
		List<JCTypeParameter> typeParams = List.nil();
		List<JCExpression> thrown = List.nil();
		JCModifiers mods = makeMods(maker, builderType, deprecate);

		ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
		statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source));
		Name keyName = builderType.toName(data.getSingularName().toString() + "Key");
		Name valueName = builderType.toName(data.getSingularName().toString() + "Value");
		/* this.pluralname$key.add(singularnameKey); */ {
			JCExpression thisDotKeyFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$key", "add");
			JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotKeyFieldDotAdd, List.<JCExpression>of(maker.Ident(keyName)));
			statements.append(maker.Exec(invokeAdd));
		}
		/* this.pluralname$value.add(singularnameValue); */ {
			JCExpression thisDotValueFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$value", "add");
			JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotValueFieldDotAdd, List.<JCExpression>of(maker.Ident(valueName)));
			statements.append(maker.Exec(invokeAdd));
		}
		if (returnStatement != null) statements.append(returnStatement);
		JCBlock body = maker.Block(0, statements.toList());
		long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());

		Name name = data.getSingularName();
		if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("put", name.toString()));
		JCExpression paramTypeKey = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		JCExpression paramTypeValue = cloneParamType(1, maker, data.getTypeArgs(), builderType, source);
		JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, paramTypeKey, null);
		JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, paramTypeValue, null);
		JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(paramKey, paramValue), thrown, body, null);
		injectMethod(builderType, method);
	}

	private void generatePluralMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
		List<JCTypeParameter> typeParams = List.nil();
		List<JCExpression> jceBlank = List.nil();
		JCModifiers mods = makeMods(maker, builderType, deprecate);
		ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
		statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source));
		long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
		long baseFlags = JavacHandlerUtil.addFinalIfNeeded(0, builderType.getContext());
		Name entryName = builderType.toName("$lombokEntry");

		JCExpression forEachType = chainDots(builderType, "java", "util", "Map", "Entry");
		forEachType = addTypeArgs(2, true, builderType, forEachType, data.getTypeArgs(), source);
		JCExpression keyArg = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(entryName), builderType.toName("getKey")), List.<JCExpression>nil());
		JCExpression valueArg = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(entryName), builderType.toName("getValue")), List.<JCExpression>nil());
		JCExpression addKey = maker.Apply(List.<JCExpression>nil(), chainDots(builderType, "this", data.getPluralName() + "$key", "add"), List.of(keyArg));
		JCExpression addValue = maker.Apply(List.<JCExpression>nil(), chainDots(builderType, "this", data.getPluralName() + "$value", "add"), List.of(valueArg));
		JCBlock forEachBody = maker.Block(0, List.<JCStatement>of(maker.Exec(addKey), maker.Exec(addValue)));
		JCExpression entrySetInvocation = maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("entrySet")), jceBlank);
		JCStatement forEach = maker.ForeachLoop(maker.VarDef(maker.Modifiers(baseFlags), entryName, forEachType, null), entrySetInvocation, forEachBody);
		statements.append(forEach);

		if (returnStatement != null) statements.append(returnStatement);
		JCBlock body = maker.Block(0, statements.toList());
		Name name = data.getPluralName();
		if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("putAll", name.toString()));
		JCExpression paramType = chainDots(builderType, "java", "util", "Map");
		paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs(), source);
		JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
		JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), jceBlank, body, null);
		injectMethod(builderType, method);
	}

	@Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName) {
		if (useGuavaInstead(builderType)) {
			guavaMapSingularizer.appendBuildCode(data, builderType, source, statements, targetVariableName);
			return;
		}

		JavacTreeMaker maker = builderType.getTreeMaker();

		if (data.getTargetFqn().equals("java.util.Map")) {
			statements.appendList(createJavaUtilSetMapInitialCapacitySwitchStatements(maker, data, builderType, true, "emptyMap", "singletonMap", "LinkedHashMap", source));
		} else {
			statements.appendList(createJavaUtilSimpleCreationAndFillStatements(maker, data, builderType, true, true, false, true, "TreeMap", source));
		}
	}
}


text:
let fn = async (name, value, options = {}) => {
  await Promise.resolve([]);
}


text:
Example:
==========
**http://wysiwygjs.github.io/**

API changed:
==========

* Mar 30, 2015: camelcase wysiwyg.js: onkeypress->onKeyDown, onselection->onSelection, onplaceholder->onPlaceholder, hijackcontextmenu->hijackContextmenu'
* Mar 11, 2015: dropfileClick->selectImage

wysiwyg.js
==========

'wysiwyg.js' is a (uglified) 12k contenteditable-editor with no dependencies.
It does only:
* Transforms any HTML-element into contenteditable
* onselection-event: e.g. to open a toolbar
* onkeypress-event: e.g. to handle hotkeys
* onplaceholder-event: show/hide a placeholder
* handle popups
* .bold(), .forecolor(), .inserthtml(), ... functions

It works with:
* Internet Explorer 6+
* Firefox 3.5+
* Chrome 4+
* Safari 3.1+

If a <textarea> was used as 'element', the library:
* keeps the <textarea> in sync
* falls back to the <textarea> if the browser does not support 'contenteditable'
* Old iOS and Android 2.3- also degrade to <textarea>

There is also a (uglified) 10k jQuery-plugin '$.wysiwyg()' - plus (minified) 2k CSS -
to create a featured editor which depends on:
* wysiwyg.js
* jQuery
* FontAwesome (or JPG/PNG/GIF/SVG images)

The toolbar is easy to extend - e.g. smiley, fontname and fontsize buttons below.
It is used on a website with 300M page impressions a month.

$.wysiwyg()-API:
==========

````javascript
// create editor:
$(element).wysiwyg({
    classes: 'some-more-classes',
    toolbar: 'selection'|'top'|'top-selection'|'bottom'|'bottom-selection',
    buttons: {
        buttonname: {
            title: 'tooltip text',
            // How should the button look like?
            image: '\u1234' | '<img src="path/to/image.jpg">',
            html: '<raw html>',
            // What should the button do?
            popup: function( $popup, $button ) { ... },
            click: function( $button ) { ... },
            // Where should the button be placed?
            showstatic: true, // on the static toolbar
            showselection: true // on selection toolbar
        },
        // build-in:
        insertimage: { ... },
        insertvideo: { ... },
        insertlink: { ... },
        bold: { ... },
        italic: { ... },
        underline: { ... },
        strikethrough: { ... },
        forecolor: { ... },
        highlight: { ... },
        alignleft: { ... },
        aligncenter: { ... },
        alignright: { ... },
        alignjustify: { ... },
        subscript: { ... },
        superscript: { ... },
        indent: { ... },
        outdent: { ... },
        orderedList: { ... },
        unorderedList: { ... },
        removeformat: { ... }
    },
    submit: { ... },
    selectImage: 'Click or drop image',
    placeholderUrl: 'www.example.com',
    placeholderEmbed: '<embed/>',
    maxImageSize: [600,200],
    onKeyDown: function( key, character, shiftKey, altKey, ctrlKey, metaKey ) { ... },
    onKeyPress: function( key, character, shiftKey, altKey, ctrlKey, metaKey ) { ... },
    onKeyUp: function( key, character, shiftKey, altKey, ctrlKey, metaKey ) { ... },
    onAutocomplete: function( tyed, key, character, shiftKey, altKey, ctrlKey, metaKey ) { ... },
    onImageUpload: function( insert_image ) { ... },
    forceImageUpload: false,
    videoFromUrl: function( url ) { ... }
});

// surrounding div:
$(element).wysiwyg('container');

// accessing 'wysiwyg.js':
$(element).wysiwyg('shell').bold();
$(element).wysiwyg('shell').forecolor( '#ff0000' );
$(element).wysiwyg('shell').insertHTML( '<b>some text</b>' );
````

wysiwyg.js-API:
==========

````javascript
// create wysiwyg:
var wysiwygeditor = wysiwyg({
    element: 'editor-id' || document.getElementById('editor-id'),
    onKeyDown: function( key, character, shiftKey, altKey, ctrlKey, metaKey ) {
        },
    onKeyPress: function( key, character, shiftKey, altKey, ctrlKey, metaKey ) {
        },
    onKeyUp: function( key, character, shiftKey, altKey, ctrlKey, metaKey ) {
        },
    onSelection: function( collapsed, rect, nodes, rightclick ) {
        },
    onPlaceholder: function( visible ) {
        },
    onClosepopup: function() {
        },
    hijackContextmenu: false
});

// properties:
wysiwygeditor.getElement();
wysiwygeditor.getHTML(); -> 'html'
wysiwygeditor.setHTML( html );
wysiwygeditor.getSelectedHTML(); -> 'html'|false
wysiwygeditor.sync();
wysiwygeditor.readOnly(); // -> query
wysiwygeditor.readOnly( true|false );

// selection and popup:
wysiwygeditor.collapseSelection();
wysiwygeditor.expandSelection( preceding, following );
wysiwygeditor.openPopup(); -> popup-handle
wysiwygeditor.closePopup();

// exec commands:
wysiwygeditor.removeFormat();
wysiwygeditor.bold();
wysiwygeditor.italic();
wysiwygeditor.underline();
wysiwygeditor.strikethrough();
wysiwygeditor.forecolor( color );
wysiwygeditor.highlight( color );
wysiwygeditor.fontName( fontname );
wysiwygeditor.fontSize( fontsize );
wysiwygeditor.subscript();
wysiwygeditor.superscript();
wysiwygeditor.align( 'left'|'center'|'right'|'justify' );
wysiwygeditor.format( tagname );
wysiwygeditor.indent( outdent );
wysiwygeditor.insertLink( url );
wysiwygeditor.insertImage( url );
wysiwygeditor.insertHTML( html );
wysiwygeditor.insertList( ordered );
````


text:
ITEM.name = "Медицина"
ITEM.desc = "Simple."
ITEM.category = "Медицина"
ITEM.model = "models/weapons/w_pistol.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.healSeconds = 10
ITEM.health = 0
ITEM.sound = "hgn/crussaria/items/itm_clothing_up.wav"

local function Heal(client, target, amount, seconds)
	hook.Run("OnPlayerHeal", client, target, amount, seconds)

	if (client:Alive() and target:Alive()) then
	local medic = client:getChar():getAttrib("mdc")
	local id = "nutHeal_"..FrameTime()
		timer.Create(id, 1, seconds, function()
			if (!target:IsValid() or !target:Alive()) then
				timer.Destroy(id)
			end
			target:SetHealth(math.Clamp(target:Health() + ((amount+(medic/5))/seconds), 0, target:GetMaxHealth()))
			if target:getChar():getData("bleeding") then
				target:getChar():setData("bleeding_level", target:getChar():getData("bleeding_level") - 1)
			end
		end)
		client:getChar():updateAttrib("mdc", amount*0.0025)
	end
end

ITEM.functions.Use = {
	name = "Использовать",
	icon = "icon16/add.png",
	onRun = function(item)
	local client = item.player;
	local char = client:getChar()
			Heal(client,client,item.health, item.healSeconds)
			client:EmitSound(item.sound, 60, 100)

	return true
	end,

	onCanRun = function(item)
		return (!IsValid(item.entity))
	end
}

ITEM.functions.UseOn = {
	name = "Использовать на ...",
	icon = "icon16/arrow_up.png",
	onRun = function(item)
	local char = item.player:getChar()
	local client = item.player
	local trace = client:GetEyeTraceNoCursor() -- We don't need cursors.
	local target = trace.Entity

	if (target and target:IsValid() and target:IsPlayer() and target:Alive()) then
			Heal(client,target,item.health, item.healSeconds)
			target:EmitSound(item.sound, 60, 100)
			return true
	end

	return false
	end,
	onCanRun = function(item)
		return (!IsValid(item.entity))
	end
}


text:
require "test_helper"
load "test/models/search/users.rb"
load "test/models/search/on_name/test_helper.rb"

# Single Search model test.
class SearchOnNameParOr2ndParIdCommonsIncludedDefTest < ActiveSupport::TestCase
  test "search on name parent or 2nd parent id commons included by default" do
    name = names(:argyle_apple)
    params = ActiveSupport::HashWithIndifferentAccess.new(
      query_target: "name",
      query_string: "parent-or-second-parent-id: #{name.id}",
      current_user: build_edit_user
    )
    search = Search::Base.new(params)
    confirm_results_class(search.executed_query.results)
    assert_equal 1,
                 search.executed_query.results.size,
                 "Expected common name for parent or 2nd parent ID query"
  end
end


text:
'''
MNIST dataset with TensorFlow TFRecords. Refer to:
    https://github.com/fchollet/keras/blob/master/examples/mnist_tfrecord.py

This is an implementation for multi-GPU systems.

Call this example:
    # best achieved performance with 2 GPUs
    time CUDA_VISIBLE_DEVICES=0,1 python mnist_tfrecord_mgpu.py
    # or no timeing info:
    CUDA_VISIBLE_DEVICES=0,1 python mnist_tfrecord_mgpu.py

    # vary CUDA_VISIBLE_DEVICES for more than 2 GPUs. Performance starts to
    # degrade.
    time CUDA_VISIBLE_DEVICES=0,1,3,4 python mnist_tfrecord_mgpu.py

    # compare 2 GPUs to one GPU
    time CUDA_VISIBLE_DEVICES=0 python mnist_tfrecord_mgpu.py

    time CUDA_VISIBLE_DEVICES=0,1 python mnist_tfrecord_mgpu.py
    # The overall walltime for this whole example might be faster with 1 GPU
    # due to startup time being longer for multigpu case, but the training
    # portion is faster with 2 GPUs. Running on P100s 50 epochs:
    #     nGPUs | training (sec). | walltime (sec.)
    #         1 | ~ 2             | ~ 16
    #         2 | ~ 1             | ~ 12
    #
    # Degrades with > 2 GPUs because the mnist model is not significant enough
    # to stress the computing of the GPUs so the startup/comm. Overhead is
    # greater than speedup achieved due to data-parallelism.

Using TFRecord queues with Keras can be a significant performance booster. When
the model and batch sizes are signifcantly large, using multigpu with TFRecord
queue can give additional performance boost to Keras.

'''
import time

import numpy as np

import tensorflow as tf
from keras import backend as KB
from keras.models import Model
from keras.layers import (
    Dense, Dropout, Flatten, Input, Conv2D, MaxPooling2D)
from keras.optimizers import RMSprop

from keras.models import Sequential
import keras.layers as KL

from keras.callbacks import ModelCheckpoint

from keras.utils import to_categorical

from tensorflow.contrib.learn.python.learn.datasets import mnist

from keras_tf_multigpu.avolkov1 import (
    get_available_gpus, make_parallel, print_mgpu_modelsummary)

if KB.backend() != 'tensorflow':
    raise RuntimeError('This example can only run with the '
                       'TensorFlow backend, '
                       'because it requires TFRecords, which '
                       'are not supported on other platforms.')

def cnn_layers_list(nclasses):
    ll = []
    ll.append(Conv2D(32, (3, 3), activation='relu', padding='valid'))
    ll.append(Conv2D(64, (3, 3), activation='relu'))
    ll.append(MaxPooling2D(pool_size=(2, 2)))
    ll.append(Dropout(0.25))
    ll.append(Flatten())
    ll.append(Dense(128, activation='relu'))
    ll.append(Dropout(0.5))
    ll.append(Dense(nclasses, activation='softmax', name='x_train_out'))

    return ll

def cnn_layers(x_train_input, nclasses):
    ll = cnn_layers_list(nclasses)
    x = x_train_input
    for il in ll:
        x = il(x)

    return x

def make_model(x_train_input, nclasses):
    '''Non-functional model definition.'''
    model = Sequential()
    model.add(KL.InputLayer(input_tensor=x_train_input))
    ll = cnn_layers_list(nclasses)
    for il in ll:
        model.add(il)

    return model

def main():
    # user options
    batch_size = 128
    val_in_train = False
    use_model_checkpt = False

    # demo processing
    sess = tf.Session()
    KB.set_session(sess)

    gdev_list = get_available_gpus()
    ngpus = len(gdev_list)
    batch_size = batch_size * ngpus

    data = mnist.load_mnist()
    X_train = data.train.images
    X_test = data.test.images
    train_samples = X_train.shape[0]  # 60000
    test_samples = X_test.shape[0]  # 10000
    height_nrows = 28
    width_ncols = 28
    batch_shape = [batch_size, height_nrows, width_ncols, 1]
    epochs = 5
    steps_per_epoch = train_samples / batch_size
    validations_steps = test_samples / batch_size
    nclasses = 10

    # The capacity variable controls the maximum queue size
    # allowed when prefetching data for training.
    capacity = 10000

    # min_after_dequeue is the minimum number elements in the queue
    # after a dequeue, which ensures sufficient mixing of elements.
    min_after_dequeue = 3000

    # If `enqueue_many` is `False`, `tensors` is assumed to represent a
    # single example.  An input tensor with shape `[x, y, z]` will be output
    # as a tensor with shape `[batch_size, x, y, z]`.
    #
    # If `enqueue_many` is `True`, `tensors` is assumed to represent a
    # batch of examples, where the first dimension is indexed by example,
    # and all members of `tensors` should have the same size in the
    # first dimension.  If an input tensor has shape `[*, x, y, z]`, the
    # output will have shape `[batch_size, x, y, z]`.
    enqueue_many = True

    x_train_batch, y_train_batch = tf.train.shuffle_batch(
        tensors=[data.train.images, data.train.labels.astype(np.int32)],
        batch_size=batch_size,
        capacity=capacity,
        min_after_dequeue=min_after_dequeue,
        enqueue_many=enqueue_many,
        num_threads=8)

    x_train_batch = tf.cast(x_train_batch, tf.float32)
    x_train_batch = tf.reshape(x_train_batch, shape=batch_shape)

    y_train_batch = tf.cast(y_train_batch, tf.int32)
    y_train_batch = tf.one_hot(y_train_batch, nclasses)

    x_train_input = Input(tensor=x_train_batch)

    x_test_batch, y_test_batch = tf.train.batch(
        tensors=[data.test.images, data.test.labels.astype(np.int32)],
        batch_size=batch_size,
        capacity=capacity,
        enqueue_many=enqueue_many,
        num_threads=8)

    # I like the non-functional definition of model more.
    # model_init = make_model(x_train_input, nclasses)
    # x_train_out = model_init.output
    # train_model = Model(inputs=[x_train_input], outputs=[x_train_out])

    x_train_out = cnn_layers(x_train_input, nclasses)
    train_model = Model(inputs=[x_train_input], outputs=[x_train_out])
    if ngpus > 1:
        train_model = make_parallel(train_model, gdev_list)

    lr = 2e-3 * ngpus
    train_model.compile(optimizer=RMSprop(lr=lr, decay=1e-5),
                        loss='categorical_crossentropy',
                        metrics=['accuracy'],
                        target_tensors=[y_train_batch])

    if ngpus > 1:
        print_mgpu_modelsummary(train_model)
    else:
        train_model.summary()

    # Callbacks
    if use_model_checkpt:
        mon = 'val_acc' if val_in_train else 'acc'
        checkpoint = ModelCheckpoint(
            'saved_wt.h5', monitor=mon, verbose=0,
            save_best_only=True,
            save_weights_only=True)
        checkpoint = [checkpoint]
    else:
        checkpoint = []

    callbacks = checkpoint
    # Training slower with callback. Multigpu slower with callback during
    # training than 1 GPU. Again, mnist is too trivial of a model and dataset
    # to benchmark or stress GPU compute capabilities. I set up this example
    # to illustrate potential for speedup of multigpu case trying to use mnist
    # as a stressor.
    # It's like comparing a 5 ft race between a person and a truck. A truck is
    # obviously faster than a person but in a 5 ft race the person will likely
    # win due to slower startup for the truck.
    # I will re-implement this with Cifar that should be a better benchmark.

    # Start the queue runners.
    tf.train.start_queue_runners(sess=sess)

    # Fit the model using data from the TFRecord data tensors.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess, coord)

    start_time = time.time()
    train_model.fit(
        validation_data=(x_test_batch, y_test_batch) if val_in_train else None,
        validation_steps=validations_steps if val_in_train else None,
        steps_per_epoch=steps_per_epoch,
        epochs=epochs,
        callbacks=callbacks)
    elapsed_time = time.time() - start_time
    print('[{}] finished in {} ms'.format('TRAINING',
                                          int(elapsed_time * 1000)))

    if not checkpoint:  # empty list
        train_model.save_weights('./saved_wt.h5')

    # Clean up the TF session.
    coord.request_stop()
    coord.join(threads)

    KB.clear_session()

    # Second Session. Demonstrate that the model works and is independent of
    # the TFRecord pipeline, and to test loading trained model without tensors.
    x_test = np.reshape(data.validation.images,
                        (data.validation.images.shape[0], 28, 28, 1))
    y_test = data.validation.labels
    x_test_inp = KL.Input(shape=(x_test.shape[1:]))
    test_out = cnn_layers(x_test_inp, nclasses)
    test_model = Model(inputs=x_test_inp, outputs=test_out)

    test_model.load_weights('saved_wt.h5')
    test_model.compile(optimizer='rmsprop',
                       loss='categorical_crossentropy',
                       metrics=['accuracy'])
    test_model.summary()

    loss, acc = test_model.evaluate(x_test,
                                    to_categorical(y_test),
                                    nclasses)
    print('\nTest loss: {0}'.format(loss))
    print('\nTest accuracy: {0}'.format(acc))

if __name__ == '__main__':
    main()


text:
yum install libtool
yum install gcc make gcc-c++ openssl openssl-devel
src_dir=/usr/local/src
rc_dir=/usr/local/src
cur_dir=$(cd "$(dirname "$0")"; pwd)
#
cd /usr/local/src

if [ ! -e $src_dir/sphinx-2.1.7-release.tar.gz  ]; then
	cd /usr/local/src
	wget http://sphinxsearch.com/files/sphinx-2.1.7-release.tar.gz
	tar -zxvf sphinx-2.1.7-release.tar.gz
fi

cd  sphinx-2.1.7-release
./configure -prefix=/usr/local/sphinx
make && make install

cp $cur_dir/sys_config/sphinx.conf /usr/local/sphinx/etc/
cp $cur_dir/init_sh/sphinx /etc/init.d/


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Build.Shared;
using Microsoft.Build.Shared.EscapingStringExtensions;
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

namespace Microsoft.Build.Internal
{
    internal struct FileSpecMatcherTester
    {
        private readonly string _currentDirectory;
        private readonly string _unescapedFileSpec;
        private readonly Regex _regex;

        private FileSpecMatcherTester(string currentDirectory, string unescapedFileSpec, Regex regex)
        {
            Debug.Assert(!string.IsNullOrEmpty(unescapedFileSpec));

            _currentDirectory = currentDirectory;
            _unescapedFileSpec = unescapedFileSpec;
            _regex = regex;
        }

        public static FileSpecMatcherTester Parse(string currentDirectory, string fileSpec)
        {
            string unescapedFileSpec = fileSpec.Unescape();
            Regex regex = EngineFileUtilities.FilespecHasWildcards(fileSpec) ? CreateRegex(unescapedFileSpec, currentDirectory) : null;

            return new FileSpecMatcherTester(currentDirectory, unescapedFileSpec, regex);
        }

        public bool IsMatch(string fileToMatch)
        {
            Debug.Assert(!string.IsNullOrEmpty(fileToMatch));

            // check if there is a regex matching the file
            if (_regex != null)
            {
                var normalizedFileToMatch = FileUtilities.GetFullPathNoThrow(Path.Combine(_currentDirectory, fileToMatch));
                return _regex.IsMatch(normalizedFileToMatch);
            }

            return FileUtilities.ComparePathsNoThrow(_unescapedFileSpec, fileToMatch, _currentDirectory);
        }

        // this method parses the glob and extracts the fixed directory part in order to normalize it and make it absolute
        // without this normalization step, strings pointing outside the globbing cone would still match when they shouldn't
        // for example, we dont want "**/*.cs" to match "../Shared/Foo.cs"
        // todo: glob rooting knowledge partially duplicated with MSBuildGlob.Parse and FileMatcher.ComputeFileEnumerationCacheKey
        private static Regex CreateRegex(string unescapedFileSpec, string currentDirectory)
        {
            Regex regex = null;
            string fixedDirPart = null;
            string wildcardDirectoryPart = null;
            string filenamePart = null;

            FileMatcher.Default.SplitFileSpec(
                unescapedFileSpec,
                out fixedDirPart,
                out wildcardDirectoryPart,
                out filenamePart);

            if (FileUtilities.PathIsInvalid(fixedDirPart))
            {
                return null;
            }

            var absoluteFixedDirPart = Path.Combine(currentDirectory, fixedDirPart);
            var normalizedFixedDirPart = string.IsNullOrEmpty(absoluteFixedDirPart)
                // currentDirectory is empty for some in-memory projects
                ? Directory.GetCurrentDirectory()
                : FileUtilities.GetFullPathNoThrow(absoluteFixedDirPart);

            normalizedFixedDirPart = FileUtilities.EnsureTrailingSlash(normalizedFixedDirPart);

            var recombinedFileSpec = string.Join("", normalizedFixedDirPart, wildcardDirectoryPart, filenamePart);

            bool isRecursive;
            bool isLegal;

            FileMatcher.Default.GetFileSpecInfoWithRegexObject(
                recombinedFileSpec,
                out regex,
                out isRecursive,
                out isLegal);

            return isLegal ? regex : null;
        }
    }
}


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

{% load url from future %}
{% block title %} Weekly FMC - Oops {% endblock %}

{% block content %}

Oops, this page does not exist!

{% endblock %}


text:
package client.server;

import java.io.Serializable;

import shared.TableData;

/**
 * Holds information necessary to interact with server, including hostname, port, and
 * nickname.
 *
 * @author Chae Jubb
 * @version 1.0
 *
 */
public class ServerProfile implements TableData, Serializable {

	private static final long serialVersionUID = 2460806966800521724L;
	public boolean delete;
	public String hostname;
	public int port;
	public String nickname;

	/**
	 * Constructor. All fields required
	 *
	 * @param hostname
	 *          Hostname of server. May be text or IP.
	 * @param port
	 *          Port through which to connect. (4444 is default)
	 * @param nickname
	 *          Text nickname for server. Will be returned in toString method
	 */
	public ServerProfile(String hostname, int port, String nickname){
		this.hostname = hostname;
		this.port = port;
		this.nickname = nickname;
	}

	/**
	 * Returns nickname of server
	 *
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString(){
		return this.nickname;
	}

	/**
	 * @return the hostname
	 */
	public String getHostname(){
		return hostname;
	}

	/**
	 * @param hostname
	 *          the hostname to set
	 */
	public void setHostname(String hostname){
		this.hostname = hostname;
	}

	/**
	 * @return the port
	 */
	public int getPort(){
		return port;
	}

	/**
	 * @param port
	 *          the port to set
	 */
	public void setPort(int port){
		this.port = port;
	}

	@Override
	public boolean getDelete(){
		return this.delete;
	}

	@Override
	public void setDelete(boolean in){
		this.delete = in;
	}
}


text:
class SessionsController < ApplicationController

  # render new.rhtml
  def new
  end

  def create
    logout_keeping_session!
    user = User.authenticate(params[:email], params[:password])
    if user
      # Protects against session fixation attacks, causes request forgery
      # protection if user resubmits an earlier form using back
      # button. Uncomment if you understand the tradeoffs.
      # reset_session
      self.current_user = user
      new_cookie_flag = (params[:remember_me] == "1")
      handle_remember_cookie! new_cookie_flag
      redirect_back_or_default('/')
      flash[:notice] = t('logged_in_successfully')
    else
      note_failed_signin
      @login       = params[:email]
      @remember_me = params[:remember_me]
      render :action => 'new'
    end
  end

  def destroy
    logout_killing_session!
    flash[:notice] = t('you_have_been_logged_out')
    redirect_back_or_default('/')
  end

protected
  # Track failed login attempts
  def note_failed_signin
    flash[:error] = t('could_not_log_you_in_as', :name => params[:email])
    logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip} at #{Time.now.utc}"
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Can. J. Bot. 67(5): 1281 (1989)

#### Original name
Corollospora armoricana Kohlm. & Volkm.-Kohlm., 1989

### Remarks
null