text:
package org.intellimate.izou.sdk.resource;

import org.intellimate.izou.identification.Identification;
import org.intellimate.izou.resource.ResourceModel;

import java.util.ArrayList;
import java.util.List;

/**
 * An Resource is an object which is used to pass data from one part of the application to another.
 * Note! This Object is immutable!
 */
public class Resource<T> implements ResourceModel<T> {
    private final String resourceID;
    private final Identification provider;
    private final Identification consumer;
    private final T resource;

    /**
     * creates a new Resource.
     * @param resourceID the ID of the Resource
     */
    public Resource(String resourceID) {
        this(resourceID, null, null, null);
    }

    /**
     * creates a new Resource.
     * @param resourceID the ID of the Resource
     * @param provider the Provider of the Resource
     */
    public Resource(String resourceID, Identification provider) {
        this(resourceID, provider, null, null);
    }

    /**
     * creates a new Resource.
     * @param resourceID the ID of the Resource
     * @param provider the Provider of the Resource
     * @param t the resource
     */
    public Resource(String resourceID, Identification provider, T t) {
        this(resourceID, provider, t, null);
    }

    /**
     * creates a new Resource.
     * @param resourceID the ID of the Resource
     * @param consumer the ID of the Consumer
     * @param t the resource
     */
    public Resource(String resourceID, T t, Identification consumer) {
        this(resourceID, null, t, consumer);
    }

    /**
     * creates a new Resource.
     * @param resourceID the ID of the Resource
     * @param provider the Provider of the Resource
     * @param consumer the ID of the Consumer
     */
    public Resource(String resourceID, Identification provider, Identification consumer) {
        this(resourceID, provider, null, consumer);
    }

    /**
     * creates a new Resource.
     * @param resourceID the ID of the Resource
     * @param provider the Provider of the Resource
     * @param t the resource
     * @param consumer the ID of the Consumer
     */
    public Resource(String resourceID, Identification provider, T t, Identification consumer) {
        this.resourceID = resourceID;
        this.provider = provider;
        this.resource = t;
        this.consumer = consumer;
    }

    /**
     * returns the associated Resource data if set.
     * This method is thread-safe.
     * @return null or resource data
     */
    @Override
    public T getResource() {
        return resource;
    }

    /**
     * sets the Resource data.
     *

     * Note! this Object is immutable!
     *

     * @param resource the data to set
     * @return the Resource
     */
    public Resource<T> setResource(T resource) {
        return new Resource<>(resourceID, provider, resource, consumer);
    }

    /**
     * returns the ID of the Resource.
     * This method is thread-safe.
     * @return a String containing the ID of the resource
     */
    @Override
    public String getResourceID() {
        return resourceID;
    }

    /**
     * returns the provider of the Resource.
     * This method is thread-safe.
     * @return an Identification describing the provider of the Resource or null if not set
     */
    @Override
    public Identification getProvider() {
        return provider;
    }

    /**
     * returns whether a provider is set
     * @return true if this resource has an provider, false if not
     */
    @Override
    public boolean hasProvider() {
        return provider != null;
    }

    /**
     * sets who should or has provided the Resource Object.
     *

     * Note! this Object is immutable!
     *

     * @param provider an Identification describing the provider of the Resource
     * @return the Resource
     */
    public Resource<T> setProvider(Identification provider) {
        return new Resource<>(resourceID, provider, resource, consumer);
    }

    /**
     * returns the consumer of the object (if set).
     * @return null or an Identification describing the consumer of the Resource
     */
    @Override
    public Identification getConsumer() {
        return consumer;
    }

    /**
     * sets who should or has consumed the Resource Object.
     *

     * Note! this Object is immutable!
     *

     * @param consumer an Identification describing the consumer of the Resource
     * @return new Resource
     */
    public Resource<T> setConsumer(Identification consumer) {
        return new Resource<>(resourceID, provider, resource, consumer);
    }

    /**
     * creates a list with this Element in it.
     * @return a list
     */
    public List<Resource> toList() {
        List<Resource> resourceList = new ArrayList<>();
        resourceList.add(this);
        return resourceList;
    }

    /**
     * An ID must always be unique.
     * A Class like Activator or OutputPlugin can just provide their .class.getCanonicalName()
     * If you have to implement this interface multiple times, just concatenate unique Strings to
     * .class.getCanonicalName()
     *
     * @return A String containing an ID
     */
    @Override
    public String getID() {
        return resourceID;
    }

    @Override
    public String toString() {
        return "Resource{" +
                "resourceID='" + resourceID + '\'' +
                ", provider=" + provider +
                ", consumer=" + consumer +
                ", resource=" + resource +
                '}';
    }
}


text:
//---------------------------------------------------------------------
// <copyright file="LinqResultComparerDataServiceContextAdapter.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Astoria.Client
{
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.OData.Client;
    using Microsoft.Test.Taupo.Common;
    using Microsoft.Test.Taupo.Query.Contracts.Linq;

    /// <summary>
    /// Handles Context specific operations that are required for comparer to determine if values are equal
    ///  For DataServiceContext the only operation required is to determine what entities are tracked
    ///  by the context, all other methods are not required to do anything
    /// </summary>
    [ImplementationName(typeof(ILinqResultComparerContextAdapter), "DataContextComparerContextAdapter")]
    public class LinqResultComparerDataServiceContextAdapter : ILinqResultComparerContextAdapter
    {
        private List<object> currentEntities;

        /// <summary>
        /// Prepares the context for comparison.
        /// </summary>
        /// <param name="context">The context to prepare</param>
        public void PrepareContext(object context)
        {
        }

        /// <summary>
        /// On comparison of navigation properties, entities that were previously
        /// queried may be in the graph where null was expected
        /// </summary>
        /// <param name="value">value to be checked for tracking</param>
        /// <returns>True if the value is tracked</returns>
        public bool IsObjectTrackedByContext(object value)
        {
            return this.currentEntities.Contains(value);
        }

        /// <summary>
        /// Method is called directly after a query is executed
        /// useful for getting a list of entities tracked in the context
        /// </summary>
        /// <param name="context">Context that is used for the query execute</param>
        public void AfterQueryExecuted(object context)
        {
            var dataServiceContext = this.GetDataServiceContext(context);
            this.currentEntities = dataServiceContext.Entities.Select(c => c.Entity).ToList();
        }

        /// <summary>
        /// Restore the context to the state before the comparison (basically reverts the PrepareContext method)
        /// </summary>
        /// <param name="context">The context to restore</param>
        public void RestoreContext(object context)
        {
        }

        /// <summary>
        /// Get the object context from the strongly typed context (typically from generated code)
        /// </summary>
        /// <param name="stronglyTypedContext">The strongly typed context</param>
        /// <returns>The object context for the strongly typed context</returns>
        protected virtual DataServiceContext GetDataServiceContext(object stronglyTypedContext)
        {
            var objectContext = stronglyTypedContext as DataServiceContext;
            ExceptionUtilities.Assert(objectContext != null, "Strongly typed context is not of Type DataServiceContext: {0}", stronglyTypedContext);

            return objectContext;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.refactoring.rename;

import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.ide.actions.CopyReferenceAction;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageNamesValidation;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.undo.BasicUndoableAction;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.command.undo.UndoableAction;
import com.intellij.openapi.command.undo.UnexpectedUndoException;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.PomTargetPsiElement;
import com.intellij.psi.*;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.meta.PsiMetaOwner;
import com.intellij.psi.meta.PsiWritableMetaData;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import com.intellij.refactoring.listeners.UndoRefactoringElementListener;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.NonCodeSearchDescriptionLocation;
import com.intellij.refactoring.util.NonCodeUsageInfo;
import com.intellij.refactoring.util.TextOccurrencesUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageInfoFactory;
import com.intellij.util.IncorrectOperationException;
import java.util.HashMap;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

public class RenameUtil {
  private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.RenameUtil");

  private RenameUtil() {
  }

  @NotNull
  public static UsageInfo[] findUsages(@NotNull final PsiElement element,
                                       final String newName,
                                       boolean searchInStringsAndComments,
                                       boolean searchForTextOccurrences,
                                       Map<? extends PsiElement, String> allRenames) {
    final List<UsageInfo> result = Collections.synchronizedList(new ArrayList<UsageInfo>());

    PsiManager manager = element.getManager();
    GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject());
    RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(element);

    Collection<PsiReference> refs = processor.findReferences(element, searchInStringsAndComments);
    for (final PsiReference ref : refs) {
      if (ref == null) {
        LOG.error("null reference from processor " + processor);
        continue;
      }
      PsiElement referenceElement = ref.getElement();
      result.add(processor.createUsageInfo(element, ref, referenceElement));
    }

    processor.findCollisions(element, newName, allRenames, result);

    final PsiElement searchForInComments = processor.getElementToSearchInStringsAndComments(element);

    if (searchInStringsAndComments && searchForInComments != null) {
      String stringToSearch = ElementDescriptionUtil.getElementDescription(searchForInComments, NonCodeSearchDescriptionLocation.STRINGS_AND_COMMENTS);
      if (stringToSearch.length() > 0) {
        final String stringToReplace = getStringToReplace(element, newName, false, processor);
        UsageInfoFactory factory = new NonCodeUsageInfoFactory(searchForInComments, stringToReplace);
        TextOccurrencesUtil.addUsagesInStringsAndComments(searchForInComments, stringToSearch, result, factory);
      }
    }

    if (searchForTextOccurrences && searchForInComments != null) {
      String stringToSearch = ElementDescriptionUtil.getElementDescription(searchForInComments, NonCodeSearchDescriptionLocation.NON_JAVA);
      if (stringToSearch.length() > 0) {
        final String stringToReplace = getStringToReplace(element, newName, true, processor);
        addTextOccurrence(searchForInComments, result, projectScope, stringToSearch, stringToReplace);
      }

      final Pair<String, String> additionalStringToSearch = processor.getTextOccurrenceSearchStrings(searchForInComments, newName);
      if (additionalStringToSearch != null && additionalStringToSearch.first.length() > 0) {
        addTextOccurrence(searchForInComments, result, projectScope, additionalStringToSearch.first, additionalStringToSearch.second);
      }
    }

    return result.toArray(UsageInfo.EMPTY_ARRAY);
  }

  private static void addTextOccurrence(final PsiElement element, final List<UsageInfo> result, final GlobalSearchScope projectScope,
                                        final String stringToSearch, final String stringToReplace) {
    UsageInfoFactory factory = new UsageInfoFactory() {
      @Override
      public UsageInfo createUsageInfo(@NotNull PsiElement usage, int startOffset, int endOffset) {
        TextRange textRange = usage.getTextRange();
        int start = textRange == null ? 0 : textRange.getStartOffset();
        return NonCodeUsageInfo.create(usage.getContainingFile(), start + startOffset, start + endOffset, element, stringToReplace);
      }
    };
    TextOccurrencesUtil.addTextOccurences(element, stringToSearch, projectScope, result, factory);
  }

  public static void buildPackagePrefixChangedMessage(final VirtualFile[] virtualFiles, StringBuffer message, final String qualifiedName) {
    if (virtualFiles.length > 0) {
      message.append(RefactoringBundle.message("package.occurs.in.package.prefixes.of.the.following.source.folders.n", qualifiedName));
      for (final VirtualFile virtualFile : virtualFiles) {
        message.append(virtualFile.getPresentableUrl()).append("\n");
      }
      message.append(RefactoringBundle.message("these.package.prefixes.will.be.changed"));
    }
  }

  private static String getStringToReplace(PsiElement element, String newName, boolean nonJava, final RenamePsiElementProcessor theProcessor) {
    if (element instanceof PsiMetaOwner) {
      final PsiMetaOwner psiMetaOwner = (PsiMetaOwner)element;
      final PsiMetaData metaData = psiMetaOwner.getMetaData();
      if (metaData != null) {
        return metaData.getName();
      }
    }

    if (theProcessor != null) {
      String result = theProcessor.getQualifiedNameAfterRename(element, newName, nonJava);
      if (result != null) {
        return result;
      }
    }

    if (element instanceof PsiNamedElement) {
      return newName;
    }
    else {
      LOG.error("Unknown element type : " + element);
      return null;
    }
  }

  public static void checkRename(PsiElement element, String newName) throws IncorrectOperationException {
    if (element instanceof PsiCheckedRenameElement) {
      ((PsiCheckedRenameElement)element).checkSetName(newName);
    }
  }

  public static void doRename(final PsiElement element, String newName, UsageInfo[] usages, final Project project,
                              @Nullable final RefactoringElementListener listener) throws IncorrectOperationException{
    final RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(element);
    final String fqn = element instanceof PsiFile ? ((PsiFile)element).getVirtualFile().getPath() : CopyReferenceAction.elementToFqn(element);
    if (fqn != null) {
      UndoableAction action = new BasicUndoableAction() {
        @Override
        public void undo() throws UnexpectedUndoException {
          if (listener instanceof UndoRefactoringElementListener) {
            ((UndoRefactoringElementListener)listener).undoElementMovedOrRenamed(element, fqn);
          }
        }

        @Override
        public void redo() throws UnexpectedUndoException {
        }
      };
      UndoManager.getInstance(project).undoableActionPerformed(action);
    }
    processor.renameElement(element, newName, usages, listener);
  }

  public static void showErrorMessage(final IncorrectOperationException e, final PsiElement element, final Project project) {
    // may happen if the file or package cannot be renamed. e.g. locked by another application
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      throw new RuntimeException(e);
      //LOG.error(e);
      //return;
    }
    ApplicationManager.getApplication().invokeLater(() -> {
      final String helpID = RenamePsiElementProcessor.forElement(element).getHelpID(element);
      String message = e.getMessage();
      if (StringUtil.isEmpty(message)) {
        message = RefactoringBundle.message("rename.not.supported");
      }
      CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("rename.title"), message, helpID, project);
    });
  }

  public static void doRenameGenericNamedElement(@NotNull PsiElement namedElement, String newName, UsageInfo[] usages,
                                                 @Nullable RefactoringElementListener listener) throws IncorrectOperationException {
    PsiWritableMetaData writableMetaData = null;
    if (namedElement instanceof PsiMetaOwner) {
      final PsiMetaData metaData = ((PsiMetaOwner)namedElement).getMetaData();
      if (metaData instanceof PsiWritableMetaData) {
        writableMetaData = (PsiWritableMetaData)metaData;
      }
    }
    if (writableMetaData == null && !(namedElement instanceof PsiNamedElement)) {
      LOG.error("Unknown element type:" + namedElement);
    }

    boolean hasBindables = false;
    for (UsageInfo usage : usages) {
      if (!(usage.getReference() instanceof BindablePsiReference)) {
        rename(usage, newName);
      } else {
        hasBindables = true;
      }
    }

    if (writableMetaData != null) {
      writableMetaData.setName(newName);
    }
    else {
      PsiElement namedElementAfterRename = ((PsiNamedElement)namedElement).setName(newName);
      if (namedElementAfterRename != null) namedElement = namedElementAfterRename;
    }

    if (hasBindables) {
      for (UsageInfo usage : usages) {
        final PsiReference ref = usage.getReference();
        if (ref instanceof BindablePsiReference) {
          boolean fallback = true;
          if (!(ref instanceof FragmentaryPsiReference
                && ((FragmentaryPsiReference)ref).isFragmentOnlyRename())) {
            try {
              ref.bindToElement(namedElement);
              fallback = false;
            }
            catch (IncorrectOperationException ignored) {
            }
          }
          if (fallback) {//fall back to old scheme
            ref.handleElementRename(newName);
          }
        }
      }
    }
    if (listener != null) {
      listener.elementRenamed(namedElement);
    }
  }

  public static void rename(UsageInfo info, String newName) throws IncorrectOperationException {
    if (info.getElement() == null) return;
    PsiReference ref = info.getReference();
    if (ref == null) return;
    ref.handleElementRename(newName);
  }

  @Nullable
  public static List<UnresolvableCollisionUsageInfo> removeConflictUsages(Set<UsageInfo> usages) {
    final List<UnresolvableCollisionUsageInfo> result = new ArrayList<>();
    for (Iterator<UsageInfo> iterator = usages.iterator(); iterator.hasNext();) {
      UsageInfo usageInfo = iterator.next();
      if (usageInfo instanceof UnresolvableCollisionUsageInfo) {
        result.add((UnresolvableCollisionUsageInfo)usageInfo);
        iterator.remove();
      }
    }
    return result.isEmpty() ? null : result;
  }

  public static void addConflictDescriptions(UsageInfo[] usages, MultiMap<PsiElement, String> conflicts) {
    for (UsageInfo usage : usages) {
      if (usage instanceof UnresolvableCollisionUsageInfo) {
        conflicts.putValue(usage.getElement(), ((UnresolvableCollisionUsageInfo)usage).getDescription());
      }
    }
  }

  public static void renameNonCodeUsages(@NotNull Project project, @NotNull NonCodeUsageInfo[] usages) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    Map<Document, List<UsageOffset>> docsToOffsetsMap = new HashMap<>();
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    for (NonCodeUsageInfo usage : usages) {
      PsiElement element = usage.getElement();

      if (element == null) continue;
      element = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(element, true);
      if (element == null) continue;

      final ProperTextRange rangeInElement = usage.getRangeInElement();
      if (rangeInElement == null) continue;

      final PsiFile containingFile = element.getContainingFile();
      final Document document = psiDocumentManager.getDocument(containingFile);

      final Segment segment = usage.getSegment();
      LOG.assertTrue(segment != null);
      int fileOffset = segment.getStartOffset();

      List<UsageOffset> list = docsToOffsetsMap.get(document);
      if (list == null) {
        list = new ArrayList<>();
        docsToOffsetsMap.put(document, list);
      }

      list.add(new UsageOffset(fileOffset, fileOffset + rangeInElement.getLength(), usage.newText));
    }

    for (Document document : docsToOffsetsMap.keySet()) {
      List<UsageOffset> list = docsToOffsetsMap.get(document);
      LOG.assertTrue(list != null, document);
      UsageOffset[] offsets = list.toArray(new UsageOffset[0]);
      Arrays.sort(offsets);

      for (int i = offsets.length - 1; i >= 0; i--) {
        UsageOffset usageOffset = offsets[i];
        document.replaceString(usageOffset.startOffset, usageOffset.endOffset, usageOffset.newText);
      }
      PsiDocumentManager.getInstance(project).commitDocument(document);
    }
    PsiDocumentManager.getInstance(project).commitAllDocuments();
  }

  public static boolean isValidName(final Project project, final PsiElement psiElement, final String newName) {
    if (newName == null || newName.length() == 0) {
      return false;
    }
    final Condition<String> inputValidator = RenameInputValidatorRegistry.getInputValidator(psiElement);
    if (inputValidator != null) {
      return inputValidator.value(newName);
    }
    if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) {
      return newName.indexOf('\\') < 0 && newName.indexOf('/') < 0;
    }
    if (psiElement instanceof PomTargetPsiElement) {
      return !StringUtil.isEmptyOrSpaces(newName);
    }

    final PsiFile file = psiElement.getContainingFile();
    final Language elementLanguage = psiElement.getLanguage();

    final Language fileLanguage = file == null ? null : file.getLanguage();
    Language language = fileLanguage == null ? elementLanguage : fileLanguage.isKindOf(elementLanguage) ? fileLanguage : elementLanguage;

    return LanguageNamesValidation.INSTANCE.forLanguage(language).isIdentifier(newName.trim(), project);
  }

  private static class UsageOffset implements Comparable<UsageOffset> {
    final int startOffset;
    final int endOffset;
    final String newText;

    UsageOffset(int startOffset, int endOffset, String newText) {
      this.startOffset = startOffset;
      this.endOffset = endOffset;
      this.newText = newText;
    }

    @Override
    public int compareTo(final UsageOffset o) {
      return startOffset - o.startOffset;
    }
  }
}


text:
/* lib/Basics/local-configuration.h.  Generated from local-configuration.h.in by configure.  */
////////////////////////////////////////////////////////////////////////////////
/// @brief High-Performance Database Framework made by triagens
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#ifndef ARANGODB_BASICS_C_LOCAL__CONFIGURATION__WIN_H
#define ARANGODB_BASICS_C_LOCAL__CONFIGURATION__WIN_H 1

#ifndef TRI_WITHIN_COMMON
#error use <Basics/Common.h>
#endif

// -----------------------------------------------------------------------------
// --SECTION--                                     Special Configuration Options
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief enable calculation of timing figures
////////////////////////////////////////////////////////////////////////////////

#define TRI_ENABLE_FIGURES 1

////////////////////////////////////////////////////////////////////////////////
/// @brief enable hiresolution timer for figures
////////////////////////////////////////////////////////////////////////////////

/* #undef TRI_ENABLE_HIRES_FIGURES */

////////////////////////////////////////////////////////////////////////////////
/// @brief enable logging
////////////////////////////////////////////////////////////////////////////////

#define TRI_ENABLE_LOGGER 1

////////////////////////////////////////////////////////////////////////////////
/// @brief enable logging of timings
////////////////////////////////////////////////////////////////////////////////

#define TRI_ENABLE_LOGGER_TIMING 1

////////////////////////////////////////////////////////////////////////////////
/// @brief enable timings
////////////////////////////////////////////////////////////////////////////////

#define TRI_ENABLE_TIMING 1

////////////////////////////////////////////////////////////////////////////////
/// @brief enable maintainer mode
////////////////////////////////////////////////////////////////////////////////

/* #undef TRI_ENABLE_MAINTAINER_MODE */

////////////////////////////////////////////////////////////////////////////////
/// @brief enable failure testing
////////////////////////////////////////////////////////////////////////////////

/* #undef TRI_ENABLE_FAILURE_TESTS */

////////////////////////////////////////////////////////////////////////////////
/// @brief configure command
////////////////////////////////////////////////////////////////////////////////

#define TRI_CONFIGURE_COMMAND " './configure'"

////////////////////////////////////////////////////////////////////////////////
/// @brief configure options
////////////////////////////////////////////////////////////////////////////////

#define TRI_CONFIGURE_OPTIONS " "

////////////////////////////////////////////////////////////////////////////////
/// @brief configure flags
////////////////////////////////////////////////////////////////////////////////

#define TRI_CONFIGURE_FLAGS " "

////////////////////////////////////////////////////////////////////////////////
/// @brief repository version
////////////////////////////////////////////////////////////////////////////////

#define TRI_REPOSITORY_VERSION "1.4.0-alpha2"

#endif

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:


text:
"""Operations for TPUs."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import platform

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops

if platform.system() != "Windows":
  # pylint: disable=wildcard-import,unused-import,g-import-not-at-top
  from tensorflow.contrib.tpu.ops import gen_tpu_ops
  from tensorflow.contrib.tpu.ops.gen_tpu_ops import *

  from tensorflow.contrib.util import loader
  from tensorflow.python.platform import resource_loader
  # pylint: enable=wildcard-import,unused-import,g-import-not-at-top

  _tpu_ops = loader.load_op_library(
      resource_loader.get_path_to_datafile("_tpu_ops.so"))

  @ops.RegisterGradient("CrossReplicaSum")
  def _cross_replica_sum_grad(op, grad):
    del op  # Unused
    # The gradient of a cross replica sum is also a cross-replica sum.
    return gen_tpu_ops.cross_replica_sum(grad)

  # This extra type checking exists to give a more helpful error message in
  # the common case that uint8 and int64 values are infed. Remove when both
  # types are supported.

  _SUPPORTED_INFEED_DTYPES = set([
      dtypes.bool, dtypes.int32, dtypes.int64, dtypes.bfloat16, dtypes.float32,
      dtypes.complex64
  ])

  def infeed_dequeue(dtype, shape, name=None):
    """A placeholder op for a value that will be fed into the computation.

    Args:
      dtype: A `tf.DType`. The type of elements in the tensor.
      shape: A `tf.TensorShape` or list of `ints`. The shape of the tensor.
      name: A name for the operation (optional).

    Returns:
      A `Tensor` of type `dtype`.
      A tensor that will be provided using the infeed mechanism.

    Raises:
      TypeError: If 'dtype` is not a supported infeed type.
    """
    if dtype not in _SUPPORTED_INFEED_DTYPES:
      raise TypeError(
          "{} is not a supported TPU infeed type. Supported types are: "
          "{}".format(dtype, list(_SUPPORTED_INFEED_DTYPES)))

    return gen_tpu_ops.infeed_dequeue(dtype, shape, name=name)

  # pylint: disable=redefined-outer-name
  def infeed_dequeue_tuple(dtypes, shapes, name=None):
    """A placeholder op for values fed into the TPU simultaneously as a tuple.

    Args:
      dtypes: A list of `tf.DType`s that has length `>= 1`.
        The element types of each element in `outputs`.
      shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`).
        The shapes of each tensor in `outputs`.
      name: A name for the operation (optional).

    Returns:
      A list of `Tensor` objects of type `dtypes`.
      A list of tensors that will be provided using the infeed mechanism.

    Raises:
      TypeError: If a type in 'dtypes` is not a supported infeed type.
    """
    for dtype in dtypes:
      if dtype not in _SUPPORTED_INFEED_DTYPES:
        raise TypeError(
            "{} is not a supported TPU infeed type. Supported types are: "
            "{}".format(dtype, list(_SUPPORTED_INFEED_DTYPES)))
    return gen_tpu_ops.infeed_dequeue_tuple(dtypes, shapes, name=name)
  # pylint: enable=redefined-outer-name

else:
  # We have already built the appropriate libraries into the binary via CMake
  # if we have built contrib, so we don't need this
  pass


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal"
    >
    <ImageView
        android:id="@+id/custom_song_icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:layout_gravity="center_vertical"
        android:src="@drawable/liudehua" />
    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:layout_marginLeft="15dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_custom_song_name"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="倩女幽魂"
            android:textColor="@color/text_gray"
            android:textSize="12sp"/>
        <TextView
            android:id="@+id/tv_custom_song_singer"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:textSize="10sp"
            android:textColor="@color/text_gray"
            android:text="张学友"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_custom_button"
        android:layout_width="160dp"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="horizontal" >
        <ImageView
            android:id="@+id/btn_custom_prev"
            android:src="@drawable/ic_music_back"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="10dp"/>
        <ImageView
            android:id="@+id/btn_custom_play"
            android:contentDescription="播放"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="10dp"
            android:src="@drawable/ic_music_pause" />
        <ImageView
            android:id="@+id/btn_custom_next"
            android:contentDescription="下一首"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="10dp"
            android:src="@drawable/ic_music_next" />
    </LinearLayout>
</LinearLayout>


text:
@interface LinkmanTableViewController : UITableViewController

@end


text:
<map>
  <entry>
    <string>plugin_status</string>
    <string>deprecated</string>
  </entry>
  <entry>
    <string>plugin_identifier</string>
    <string>org.lockss.plugin.minerva.MinervaPlugin</string>
  </entry>
  <entry>
    <string>au_def_pause_time</string>
    <long>6000</long>
  </entry>
  <entry>
    <string>plugin_version</string>
    <string>3</string>
  </entry>
  <entry>
    <string>au_name</string>
    <string>"Minerva Plugin, Base URL %s, Volume %s", base_url, volume_name</string>
  </entry>
  <entry>
    <string>au_def_new_content_crawl</string>
    <long>1209600000</long>
  </entry>
  <entry>
    <string>plugin_name</string>
    <string>Minerva Plugin</string>
  </entry>
  <entry>
    <string>au_crawlrules</string>
    <list>
      <string>4,"^(%s|%s)", base_url, base_url2</string>
      <string>1,"%s~philos/vol%s/index.html", base_url, volume_name</string>
      <string>1,"%s~philos/vol%s/", base_url, volume_name</string>
      <string>1,"%sstephen/vol%s/", base_url2, volume_name</string>
      <string>1,"%sstephen/.*\.[pP][dD][fF]", base_url2</string>
      <string>1,"%sstephen/permission\.htm", base_url2</string>
      <string>1,".*\.([cC][sS][sS]|[gG][iI][fF]|[jJ][pP][eE][gG]|[jJ][pP][gG]|[jJ][sS]|[pP][nN][gG])$"</string>
    </list>
  </entry>
  <entry>
    <string>au_start_url</string>
    <string>"%s~philos/vol%s/index.html", base_url, volume_name</string>
  </entry>
  <entry>
    <string>au_manifest</string>
    <list>
      <string>"%s~philos/vol%s/index.html", base_url, volume_name</string>
      <string>"%sstephen/permission.htm", base_url2</string>
    </list>
  </entry>
  <entry>
    <string>plugin_config_props</string>
    <list>
      <org.lockss.daemon.ConfigParamDescr>
        <key>volume_name</key>
        <displayName>Volume Name</displayName>
        <type>1</type>
        <size>20</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>base_url</key>
        <displayName>Base URL</displayName>
        <description>Usually of the form http://<journal-name>.com/</description>
        <type>3</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>base_url2</key>
        <displayName>Second Base URL</displayName>
        <description>Use if AU spans two hosts</description>
        <type>3</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
    </list>
  </entry>
</map>


text:
require 'time'
if defined?(Encoding::ASCII_8BIT)
  require 'open-uri' # for encoding
end

# A namespace module for HTTP Message definitions used by HTTPClient.
module HTTP

  # Represents HTTP response status code.  Defines constants for HTTP response
  # and some conditional methods.
  module Status
    OK = 200
    CREATED = 201
    ACCEPTED = 202
    NON_AUTHORITATIVE_INFORMATION = 203
    NO_CONTENT = 204
    RESET_CONTENT = 205
    PARTIAL_CONTENT = 206
    MOVED_PERMANENTLY = 301
    FOUND = 302
    SEE_OTHER = 303
    TEMPORARY_REDIRECT = MOVED_TEMPORARILY = 307
    BAD_REQUEST = 400
    UNAUTHORIZED = 401
    PROXY_AUTHENTICATE_REQUIRED = 407
    INTERNAL = 500

    # Status codes for successful HTTP response.
    SUCCESSFUL_STATUS = [
      OK, CREATED, ACCEPTED,
      NON_AUTHORITATIVE_INFORMATION, NO_CONTENT,
      RESET_CONTENT, PARTIAL_CONTENT
    ]

    # Status codes which is a redirect.
    REDIRECT_STATUS = [
      MOVED_PERMANENTLY, FOUND, SEE_OTHER,
      TEMPORARY_REDIRECT, MOVED_TEMPORARILY
    ]

    # Returns true if the given status represents successful HTTP response.
    # See also SUCCESSFUL_STATUS.
    def self.successful?(status)
      SUCCESSFUL_STATUS.include?(status)
    end

    # Returns true if the given status is thought to be redirect.
    # See also REDIRECT_STATUS.
    def self.redirect?(status)
      REDIRECT_STATUS.include?(status)
    end
  end

  # Represents a HTTP message.  A message is for a request or a response.
  #
  # Request message is generated from given parameters internally so users
  # don't need to care about it.  Response message is the instance that
  # methods of HTTPClient returns so users need to know how to extract
  # HTTP response data from Message.
  #
  # Some attributes are only for a request or a response, not both.
  #
  # == How to use HTTP response message
  #
  # 1. Gets response message body.
  #
  #     res = clnt.get(url)
  #     p res.content #=> String
  #
  # 2. Gets response status code.
  #
  #     res = clnt.get(url)
  #     p res.status #=> 200, 501, etc. (Integer)
  #
  # 3. Gets response header.
  #
  #     res = clnt.get(url)
  #     res.header['set-cookie'].each do |value|
  #       p value
  #     end
  #     assert_equal(1, res.header['last-modified'].size)
  #     p res.header['last-modified'].first
  #
  class Message

    CRLF = "\r\n"

    # Represents HTTP message header.
    class Headers
      # HTTP version in a HTTP header.  String.
      attr_accessor :http_version
      # Size of body.  nil when size is unknown (e.g. chunked response).
      attr_reader :body_size
      # Request/Response is chunked or not.
      attr_accessor :chunked

      # Request only.  Requested method.
      attr_reader :request_method
      # Request only.  Requested URI.
      attr_accessor :request_uri
      # Request only.  Requested query.
      attr_accessor :request_query
      # Request only.  Requested via proxy or not.
      attr_accessor :request_absolute_uri

      # Response only.  HTTP status
      attr_reader :status_code
      # Response only.  HTTP status reason phrase.
      attr_accessor :reason_phrase

      # Used for dumping response.
      attr_accessor :body_type # :nodoc:
      # Used for dumping response.
      attr_accessor :body_charset # :nodoc:
      # Used for dumping response.
      attr_accessor :body_date # :nodoc:
      # Used for keeping content encoding.
      attr_reader :body_encoding # :nodoc:

      # HTTP response status code to reason phrase mapping definition.
      STATUS_CODE_MAP = {
        Status::OK => 'OK',
        Status::CREATED => "Created",
        Status::NON_AUTHORITATIVE_INFORMATION => "Non-Authoritative Information",
        Status::NO_CONTENT => "No Content",
        Status::RESET_CONTENT => "Reset Content",
        Status::PARTIAL_CONTENT => "Partial Content",
        Status::MOVED_PERMANENTLY => 'Moved Permanently',
        Status::FOUND => 'Found',
        Status::SEE_OTHER => 'See Other',
        Status::TEMPORARY_REDIRECT => 'Temporary Redirect',
        Status::MOVED_TEMPORARILY => 'Temporary Redirect',
        Status::BAD_REQUEST => 'Bad Request',
        Status::INTERNAL => 'Internal Server Error',
      }

      # $KCODE to charset mapping definition.
      CHARSET_MAP = {
        'NONE' => 'us-ascii',
        'EUC'  => 'euc-jp',
        'SJIS' => 'shift_jis',
        'UTF8' => 'utf-8',
      }

      # Creates a Message::Headers.  Use init_request, init_response, or
      # init_connect_request for acutual initialize.
      def initialize
        @http_version = '1.1'
        @body_size = nil
        @chunked = false

        @request_method = nil
        @request_uri = nil
        @request_query = nil
        @request_absolute_uri = nil

        @status_code = nil
        @reason_phrase = nil

        @body_type = nil
        @body_charset = nil
        @body_date = nil
        @body_encoding = nil

        @is_request = nil
        @header_item = []
        @dumped = false
      end

      # Initialize this instance as a CONNECT request.
      def init_connect_request(uri)
        @is_request = true
        @request_method = 'CONNECT'
        @request_uri = uri
        @request_query = nil
        @http_version = '1.0'
      end

      # Placeholder URI object for nil uri.
      NIL_URI = HTTPClient::Util.urify('http://nil-uri-given/')
      # Initialize this instance as a general request.
      def init_request(method, uri, query = nil)
        @is_request = true
        @request_method = method
        @request_uri = uri || NIL_URI
        @request_query = query
        @request_absolute_uri = false
      end

      # Initialize this instance as a response.
      def init_response(status_code, req = nil)
        @is_request = false
        self.status_code = status_code
        if req
          @request_method = req.request_method
          @request_uri = req.request_uri
          @request_query = req.request_query
        end
      end

      # Sets status code and reason phrase.
      def status_code=(status_code)
        @status_code = status_code
        @reason_phrase = STATUS_CODE_MAP[@status_code]
      end

      # Returns 'Content-Type' header value.
      def content_type
        self['Content-Type'][0]
      end

      # Sets 'Content-Type' header value.  Overrides if already exists.
      def content_type=(content_type)
        delete('Content-Type')
        self['Content-Type'] = content_type
      end

      alias contenttype content_type
      alias contenttype= content_type=

      if defined?(Encoding::ASCII_8BIT)
        def set_body_encoding
          if type = self.content_type
            OpenURI::Meta.init(o = '')
            o.meta_add_field('content-type', type)
            @body_encoding = o.encoding
          end
        end
      else
        def set_body_encoding
          @body_encoding = nil
        end
      end

      # Sets byte size of message body.
      # body_size == nil means that the body is_a? IO
      def body_size=(body_size)
        @body_size = body_size
      end

      # Dumps message header part and returns a dumped String.
      def dump
        set_header
        str = nil
        if @is_request
          str = request_line
        else
          str = response_status_line
        end
        str + @header_item.collect { |key, value|
          "#{ key }: #{ value }#{ CRLF }"
        }.join
      end

      # Set Date header
      def set_date_header
        set('Date', Time.now.httpdate)
      end

      # Adds a header.  Addition order is preserved.
      def add(key, value)
        if value.is_a?(Array)
          value.each do |v|
            @header_item.push([key, v])
          end
        else
          @header_item.push([key, value])
        end
      end

      # Sets a header.
      def set(key, value)
        delete(key)
        add(key, value)
      end

      # Returns an Array of headers for the given key.  Each element is a pair
      # of key and value.  It returns an single element Array even if the only
      # one header exists.  If nil key given, it returns all headers.
      def get(key = nil)
        if key.nil?
          all
        else
          key = key.upcase
          @header_item.find_all { |k, v| k.upcase == key }
        end
      end

      # Returns an Array of all headers.
      def all
        @header_item
      end

      # Deletes headers of the given key.
      def delete(key)
        key = key.upcase
        @header_item.delete_if { |k, v| k.upcase == key }
      end

      # Adds a header.  See set.
      def []=(key, value)
        set(key, value)
      end

      # Returns an Array of header values for the given key.
      def [](key)
        get(key).collect { |item| item[1] }
      end

      def set_headers(headers)
        headers.each do |key, value|
          add(key, value)
        end
        set_body_encoding
      end

      def create_query_uri()
        if @request_method == 'CONNECT'
          return "#{@request_uri.host}:#{@request_uri.port}"
        end
        path = @request_uri.path
        path = '/' if path.nil? or path.empty?
        if query_str = create_query_part()
          path += "?#{query_str}"
        end
        path
      end

      def create_query_part()
        query_str = nil
        if @request_uri.query
          query_str = @request_uri.query
        end
        if @request_query
          if query_str
            query_str += "&#{Message.create_query_part_str(@request_query)}"
          else
            query_str = Message.create_query_part_str(@request_query)
          end
        end
        query_str
      end

    private

      def request_line
        path = create_query_uri()
        if @request_absolute_uri
          path = "#{ @request_uri.scheme }://#{ @request_uri.host }:#{ @request_uri.port }#{ path }"
        end
        "#{ @request_method } #{ path } HTTP/#{ @http_version }#{ CRLF }"
      end

      def response_status_line
        if defined?(Apache)
          "HTTP/#{ @http_version } #{ @status_code } #{ @reason_phrase }#{ CRLF }"
        else
          "Status: #{ @status_code } #{ @reason_phrase }#{ CRLF }"
        end
      end

      def set_header
        if @is_request
          set_request_header
        else
          set_response_header
        end
      end

      def set_request_header
        return if @dumped
        @dumped = true
        keep_alive = Message.keep_alive_enabled?(@http_version)
        if !keep_alive and @request_method != 'CONNECT'
          set('Connection', 'close')
        end
        if @chunked
          set('Transfer-Encoding', 'chunked')
        elsif @body_size and (keep_alive or @body_size != 0)
          set('Content-Length', @body_size.to_s)
        end
        if @http_version >= '1.1' and get('Host').empty?
          if @request_uri.port == @request_uri.default_port
            # GFE/1.3 dislikes default port number (returns 404)
            set('Host', "#{@request_uri.hostname}")
          else
            set('Host', "#{@request_uri.hostname}:#{@request_uri.port}")
          end
        end
      end

      def set_response_header
        return if @dumped
        @dumped = true
        if defined?(Apache) && self['Date'].empty?
          set_date_header
        end
        keep_alive = Message.keep_alive_enabled?(@http_version)
        if @chunked
          set('Transfer-Encoding', 'chunked')
        else
          if keep_alive or @body_size != 0
            set('Content-Length', @body_size.to_s)
          end
        end
        if @body_date
          set('Last-Modified', @body_date.httpdate)
        end
        if self['Content-Type'].empty?
          set('Content-Type', "#{ @body_type || 'text/html' }; charset=#{ charset_label }")
        end
      end

      def charset_label
        # TODO: should handle response encoding for 1.9 correctly.
        if RUBY_VERSION > "1.9"
          CHARSET_MAP[@body_charset] || 'us-ascii'
        else
          CHARSET_MAP[@body_charset || $KCODE] || 'us-ascii'
        end
      end
    end

    # Represents HTTP message body.
    class Body
      # Size of body.  nil when size is unknown (e.g. chunked response).
      attr_reader :size
      # maxbytes of IO#read for streaming request.  See DEFAULT_CHUNK_SIZE.
      attr_accessor :chunk_size

      # Default value for chunk_size
      DEFAULT_CHUNK_SIZE = 1024 * 16

      # Creates a Message::Body.  Use init_request or init_response
      # for acutual initialize.
      def initialize
        @body = nil
        @size = nil
        @positions = nil
        @chunk_size = nil
      end

      # Initialize this instance as a request.
      def init_request(body = nil, boundary = nil)
        @boundary = boundary
        @positions = {}
        set_content(body, boundary)
        @chunk_size = DEFAULT_CHUNK_SIZE
      end

      # Initialize this instance as a response.
      def init_response(body = nil)
        @body = body
        if @body.respond_to?(:bytesize)
          @size = @body.bytesize
        elsif @body.respond_to?(:size)
          @size = @body.size
        else
          @size = nil
        end
      end

      # Dumps message body to given dev.
      # dev needs to respond to <<.
      #
      # Message header must be given as the first argument for performance
      # reason. (header is dumped to dev, too)
      # If no dev (the second argument) given, this method returns a dumped
      # String.
      def dump(header = '', dev = '')
        if @body.is_a?(Parts)
          dev << header
          @body.parts.each do |part|
            if Message.file?(part)
              reset_pos(part)
              dump_file(part, dev)
            else
              dev << part
            end
          end
        elsif Message.file?(@body)
          dev << header
          reset_pos(@body)
          dump_file(@body, dev)
        elsif @body
          dev << header + @body
        else
          dev << header
        end
        dev
      end

      # Dumps message body with chunked encoding to given dev.
      # dev needs to respond to <<.
      #
      # Message header must be given as the first argument for performance
      # reason. (header is dumped to dev, too)
      # If no dev (the second argument) given, this method returns a dumped
      # String.
      def dump_chunked(header = '', dev = '')
        dev << header
        if @body.is_a?(Parts)
          @body.parts.each do |part|
            if Message.file?(part)
              reset_pos(part)
              dump_chunks(part, dev)
            else
              dev << dump_chunk(part)
            end
          end
          dev << (dump_last_chunk + CRLF)
        elsif @body
          reset_pos(@body)
          dump_chunks(@body, dev)
          dev << (dump_last_chunk + CRLF)
        end
        dev
      end

      # Returns a message body itself.
      def content
        @body
      end

    private

      def set_content(body, boundary = nil)
        if Message.file?(body)
          # uses Transfer-Encoding: chunked if body does not respond to :size.
          # bear in mind that server may not support it. at least ruby's CGI doesn't.
          @body = body
          remember_pos(@body)
          @size = body.respond_to?(:size) ? body.size - body.pos : nil
        elsif boundary and Message.multiparam_query?(body)
          @body = build_query_multipart_str(body, boundary)
          @size = @body.size
        else
          @body = Message.create_query_part_str(body)
          @size = @body.bytesize
        end
      end

      def remember_pos(io)
        # IO may not support it (ex. IO.pipe)
        @positions[io] = io.pos if io.respond_to?(:pos)
      end

      def reset_pos(io)
        io.pos = @positions[io] if @positions.key?(io)
      end

      def dump_file(io, dev)
        buf = ''
        while !io.read(@chunk_size, buf).nil?
          dev << buf
        end
      end

      def dump_chunks(io, dev)
        buf = ''
        while !io.read(@chunk_size, buf).nil?
          dev << dump_chunk(buf)
        end
      end

      def dump_chunk(str)
        dump_chunk_size(str.bytesize) + (str + CRLF)
      end

      def dump_last_chunk
        dump_chunk_size(0)
      end

      def dump_chunk_size(size)
        sprintf("%x", size) + CRLF
      end

      class Parts
        attr_reader :size

        def initialize
          @body = []
          @size = 0
          @as_stream = false
        end

        def add(part)
          if Message.file?(part)
            @as_stream = true
            @body << part
            if part.respond_to?(:lstat)
              @size += part.lstat.size
            elsif part.respond_to?(:size)
              if sz = part.size
                @size += sz
              else
                @size = nil
              end
            else
              # use chunked upload
              @size = nil
            end
          elsif @body[-1].is_a?(String)
            @body[-1] += part.to_s
            @size += part.to_s.bytesize if @size
          else
            @body << part.to_s
            @size += part.to_s.bytesize if @size
          end
        end

        def parts
          if @as_stream
            @body
          else
            [@body.join]
          end
        end
      end

      def build_query_multipart_str(query, boundary)
        parts = Parts.new
        query.each do |attr, value|
          headers = ["--#{boundary}"]
          if Message.file?(value)
            remember_pos(value)
            param_str = params_from_file(value).collect { |k, v|
              "#{k}=\"#{v}\""
            }.join("; ")
            if value.respond_to?(:mime_type)
              content_type = value.mime_type
            elsif value.respond_to?(:content_type)
              content_type = value.content_type
            else
              path = value.respond_to?(:path) ? value.path : nil
              content_type = Message.mime_type(path)
            end
            headers << %{Content-Disposition: form-data; name="#{attr}"; #{param_str}}
            headers << %{Content-Type: #{content_type}}
          elsif attr.is_a?(Hash)
            h = attr
            value = h[:content]
            h.each do |h_key, h_val|
              headers << %{#{h_key}: #{h_val}} if h_key != :content
            end
            remember_pos(value) if Message.file?(value)
          else
            headers << %{Content-Disposition: form-data; name="#{attr}"}
            value = value.to_s
          end
          parts.add(headers.join(CRLF) + CRLF + CRLF)
          parts.add(value)
          parts.add(CRLF)
        end
        parts.add("--#{boundary}--" + CRLF + CRLF) # empty epilogue
        parts
      end

      def params_from_file(value)
        params = {}
        path = value.respond_to?(:path) ? value.path : nil
        params['filename'] = File.basename(path || '')
        # Creation time is not available from File::Stat
        if value.respond_to?(:mtime)
          params['modification-date'] = value.mtime.rfc822
        end
        if value.respond_to?(:atime)
          params['read-date'] = value.atime.rfc822
        end
        params
      end
    end

    class << self
      private :new

      # Creates a Message instance of 'CONNECT' request.
      # 'CONNECT' request does not have Body.
      # uri:: an URI that need to connect.  Only uri.host and uri.port are used.
      def new_connect_request(uri)
        m = new
        m.http_header.init_connect_request(uri)
        m.http_header.body_size = nil
        m
      end

      # Creates a Message instance of general request.
      # method:: HTTP method String.
      # uri:: an URI object which represents an URL of web resource.
      # query:: a Hash or an Array of query part of URL.
      #         e.g. { "a" => "b" } => 'http://host/part?a=b'
      #         Give an array to pass multiple value like
      #         [["a", "b"], ["a", "c"]] => 'http://host/part?a=b&a=c'
      # body:: a Hash or an Array of body part.
      #        e.g. { "a" => "b" } => 'a=b'.
      #        Give an array to pass multiple value like
      #        [["a", "b"], ["a", "c"]] => 'a=b&a=c'.
      # boundary:: When the boundary given, it is sent as
      #            a multipart/form-data using this boundary String.
      def new_request(method, uri, query = nil, body = nil, boundary = nil)
        m = new
        m.http_header.init_request(method, uri, query)
        m.http_body = Body.new
        m.http_body.init_request(body || '', boundary)
        if body
          m.http_header.body_size = m.http_body.size
          m.http_header.chunked = true if m.http_body.size.nil?
        else
          m.http_header.body_size = nil
        end
        m
      end

      # Creates a Message instance of response.
      # body:: a String or an IO of response message body.
      def new_response(body, req = nil)
        m = new
        m.http_header.init_response(Status::OK, req)
        m.http_body = Body.new
        m.http_body.init_response(body)
        m.http_header.body_size = m.http_body.size || 0
        m
      end

      @@mime_type_handler = nil

      # Sets MIME type handler.
      #
      # handler must respond to :call with a single argument :path and returns
      # a MIME type String e.g. 'text/html'.
      # When the handler returns nil or an empty String,
      # 'application/octet-stream' is used.
      #
      # When you set nil to the handler, internal_mime_type is used instead.
      # The handler is nil by default.
      def mime_type_handler=(handler)
        @@mime_type_handler = handler
      end

      # Returns MIME type handler.
      def mime_type_handler
        @@mime_type_handler
      end

      # For backward compatibility.
      alias set_mime_type_func mime_type_handler=
      alias get_mime_type_func mime_type_handler

      def mime_type(path) # :nodoc:
        if @@mime_type_handler
          res = @@mime_type_handler.call(path)
          if !res || res.to_s == ''
            return 'application/octet-stream'
          else
            return res
          end
        else
          internal_mime_type(path)
        end
      end

      # Default MIME type handler.
      # See mime_type_handler=.
      def internal_mime_type(path)
        case path
        when /\.txt$/i
          'text/plain'
        when /\.(htm|html)$/i
          'text/html'
        when /\.doc$/i
          'application/msword'
        when /\.png$/i
          'image/png'
        when /\.gif$/i
          'image/gif'
        when /\.(jpg|jpeg)$/i
          'image/jpeg'
        else
          'application/octet-stream'
        end
      end

      # Returns true if the given HTTP version allows keep alive connection.
      # version:: String
      def keep_alive_enabled?(version)
        version >= '1.1'
      end

      # Returns true if the given query (or body) has a multiple parameter.
      def multiparam_query?(query)
        query.is_a?(Array) or query.is_a?(Hash)
      end

      # Returns true if the given object is a File.  In HTTPClient, a file is;
      # * must respond to :read for retrieving String chunks.
      # * must respond to :pos and :pos= to rewind for reading.
      #   Rewinding is only needed for following HTTP redirect.  Some IO impl
      #   defines :pos= but raises an Exception for pos= such as StringIO
      #   but there's no problem as far as using it for non-following methods
      #   (get/post/etc.)
      def file?(obj)
        obj.respond_to?(:read) and obj.respond_to?(:pos) and
          obj.respond_to?(:pos=)
      end

      def create_query_part_str(query) # :nodoc:
        if multiparam_query?(query)
          escape_query(query)
        elsif query.respond_to?(:read)
          query = query.read
        else
          query.to_s
        end
      end

      def Array.try_convert(value)
        return value if value.instance_of?(Array)
        return nil if !value.respond_to?(:to_ary)
        converted = value.to_ary
        return converted if converted.instance_of?(Array)

        cname = value.class.name
        raise TypeError, "can't convert %s to %s (%s#%s gives %s)" %
          [cname, Array.name, cname, :to_ary, converted.class.name]
      end unless Array.respond_to?(:try_convert)

      def escape_query(query) # :nodoc:
        pairs = []
        query.each { |attr, value|
          left = escape(attr.to_s) << '='
          if values = Array.try_convert(value)
            values.each { |value|
              if value.respond_to?(:read)
                value = value.read
              end
              pairs.push(left + escape(value.to_s))
            }
          else
            if value.respond_to?(:read)
              value = value.read
            end
            pairs.push(left << escape(value.to_s))
          end
        }
        pairs.join('&')
      end

      # from CGI.escape
      if defined?(Encoding::ASCII_8BIT)
        def escape(str) # :nodoc:
          str.dup.force_encoding(Encoding::ASCII_8BIT).gsub(/([^ a-zA-Z0-9_.-]+)/) {
            '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
          }.tr(' ', '+')
        end
      else
        def escape(str) # :nodoc:
          str.gsub(/([^ a-zA-Z0-9_.-]+)/n) {
            '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
          }.tr(' ', '+')
        end
      end

      # from CGI.parse
      def parse(query)
        params = Hash.new([].freeze)
        query.split(/[&;]/n).each do |pairs|
          key, value = pairs.split('=',2).collect{|v| unescape(v) }
          if params.has_key?(key)
            params[key].push(value)
          else
            params[key] = [value]
          end
        end
        params
      end

      # from CGI.unescape
      def unescape(string)
        string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
          [$1.delete('%')].pack('H*')
        end
      end
    end

    # HTTP::Message::Headers:: message header.
    attr_accessor :http_header

    # HTTP::Message::Body:: message body.
    attr_reader :http_body

    # OpenSSL::X509::Certificate:: response only.  server certificate which is
    #                              used for retrieving the response.
    attr_accessor :peer_cert

    # Creates a Message.  This method should be used internally.
    # Use Message.new_connect_request, Message.new_request or
    # Message.new_response instead.
    def initialize # :nodoc:
      @http_header = Headers.new
      @http_body = @peer_cert = nil
    end

    # Dumps message (header and body) to given dev.
    # dev needs to respond to <<.
    def dump(dev = '')
      str = @http_header.dump + CRLF
      if @http_header.chunked
        dev = @http_body.dump_chunked(str, dev)
      elsif @http_body
        dev = @http_body.dump(str, dev)
      else
        dev << str
      end
      dev
    end

    # Sets a new body.  header.body_size is updated with new body.size.
    def http_body=(body)
      @http_body = body
      @http_header.body_size = @http_body.size if @http_header
    end
    alias body= http_body=

    # Returns HTTP version in a HTTP header.  String.
    def http_version
      @http_header.http_version
    end

    # Sets HTTP version in a HTTP header.  String.
    def http_version=(http_version)
      @http_header.http_version = http_version
    end

    VERSION_WARNING = 'Message#version (Float) is deprecated. Use Message#http_version (String) instead.'
    def version
      warn(VERSION_WARNING)
      @http_header.http_version.to_f
    end

    def version=(version)
      warn(VERSION_WARNING)
      @http_header.http_version = version
    end

    # Returns HTTP status code in response.  Integer.
    def status
      @http_header.status_code
    end

    alias code status
    alias status_code status

    # Sets HTTP status code of response.  Integer.
    # Reason phrase is updated, too.
    def status=(status)
      @http_header.status_code = status
    end

    # Returns  HTTP status reason phrase in response.  String.
    def reason
      @http_header.reason_phrase
    end

    # Sets  HTTP status reason phrase of response.  String.
    def reason=(reason)
      @http_header.reason_phrase = reason
    end

    # Returns 'Content-Type' header value.
    def content_type
      @http_header.content_type
    end

    # Sets 'Content-Type' header value.  Overrides if already exists.
    def content_type=(content_type)
      @http_header.content_type = content_type
    end
    alias contenttype content_type
    alias contenttype= content_type=

    # Returns content encoding
    def body_encoding
      @http_header.body_encoding
    end

    # Returns a content of message body.  A String or an IO.
    def content
      @http_body.content
    end

    alias header http_header
    alias body content

    # Returns Hash of header. key and value are both String. Each key has a
    # single value so you can't extract exact value when a message has multiple
    # headers like 'Set-Cookie'. Use header['Set-Cookie'] for that purpose.
    # (It returns an Array always)
    def headers
      Hash[*http_header.all.flatten]
    end

    # Extracts cookies from 'Set-Cookie' header.
    # Supports 'Set-Cookie' in response header only.
    # Do we need 'Cookie' support in request header?
    def cookies
      set_cookies = http_header['set-cookie']
      unless set_cookies.empty?
        uri = http_header.request_uri
        set_cookies.map { |str|
          cookie = WebAgent::Cookie.new
          cookie.parse(str, uri)
          cookie
        }
      end
    end

    # Convenience method to return boolean of whether we had a successful request
    def ok?
      HTTP::Status.successful?(status)
    end

    def redirect?
      HTTP::Status.redirect?(status)
    end

    # SEE_OTHER is a redirect, but it should sent as GET
    def see_other?
      status == HTTP::Status::SEE_OTHER
    end
  end

end


text:
from cinder.api import common
from cinder.api import microversions as mv
from cinder import utils

class ViewBuilder(common.ViewBuilder):
    """Model group API responses as a python dictionary."""

    _collection_name = "groups"

    def __init__(self):
        """Initialize view builder."""
        super(ViewBuilder, self).__init__()

    def summary_list(self, request, groups):
        """Show a list of groups without many details."""
        return self._list_view(self.summary, request, groups)

    def detail_list(self, request, groups):
        """Detailed view of a list of groups ."""
        return self._list_view(self.detail, request, groups)

    def summary(self, request, group):
        """Generic, non-detailed view of a group."""
        return {
            'group': {
                'id': group.id,
                'name': group.name
            }
        }

    def detail(self, request, group):
        """Detailed view of a single group."""
        group_ref = {
            'group': {
                'id': group.id,
                'status': group.status,
                'availability_zone': group.availability_zone,
                'created_at': group.created_at,
                'name': group.name,
                'description': group.description,
                'group_type': group.group_type_id,
                'volume_types': [v_type.id for v_type in group.volume_types],
            }
        }

        req_version = request.api_version_request
        # Add group_snapshot_id and source_group_id if min version is greater
        # than or equal to GROUP_SNAPSHOTS.
        if req_version.matches(mv.GROUP_SNAPSHOTS, None):
            group_ref['group']['group_snapshot_id'] = group.group_snapshot_id
            group_ref['group']['source_group_id'] = group.source_group_id

        # Add volumes if min version is greater than or equal to
        # GROUP_VOLUME_LIST.
        if req_version.matches(mv.GROUP_VOLUME_LIST, None):
            if utils.get_bool_param('list_volume', request.params):
                group_ref['group']['volumes'] = [volume.id
                                                 for volume in group.volumes]

        # Add replication_status if min version is greater than or equal
        # to GROUP_REPLICATION.
        if req_version.matches(mv.GROUP_REPLICATION, None):
            group_ref['group']['replication_status'] = group.replication_status

        return group_ref

    def _list_view(self, func, request, groups):
        """Provide a view for a list of groups."""
        groups_list = [
            func(request, group)['group']
            for group in groups]
        grp_links = self._get_collection_links(request,
                                               groups,
                                               self._collection_name)
        groups_dict = dict(groups=groups_list)
        if grp_links:
            groups_dict['group_links'] = grp_links

        return groups_dict


text: This is the login page


text:
package org.springframework.social.auth0.security;

import org.springframework.social.auth0.api.Auth0;
import org.springframework.social.auth0.connect.Auth0ConnectionFactory;
import org.springframework.social.security.provider.OAuth2AuthenticationService;

public class Auth0AuthenticationService extends OAuth2AuthenticationService<Auth0> {

	public Auth0AuthenticationService(String domain, String apiKey, String appSecret) {
		super(new Auth0ConnectionFactory(domain, apiKey, appSecret));
	}

}


text:
#ifndef NFC_WORLDNET_CLIENT_MODULE_H
#define NFC_WORLDNET_CLIENT_MODULE_H

//  the cause of sock'libariy, thenfore "NFCNet.h" much be included first.

#include "NFComm/NFMessageDefine/NFMsgDefine.h"
#include "NFComm/NFPluginModule/NFIWorldToMasterModule.h"
#include "NFComm/NFPluginModule/NFIWorldLogicModule.h"
#include "NFComm/NFPluginModule/NFINetModule.h"
#include "NFComm/NFPluginModule/NFIClassModule.h"
#include "NFComm/NFPluginModule/NFIElementModule.h"
#include "NFComm/NFPluginModule/NFILogModule.h"
#include "NFComm/NFPluginModule/NFIWorldNet_ServerModule.h"
#include "NFComm/NFPluginModule/NFINetClientModule.hpp"

class NFCWorldToMasterModule
	: public NFIWorldToMasterModule
{
public:
	NFCWorldToMasterModule(NFIPluginManager* p)
	{
		pPluginManager = p;
		mLastReportTime = 0;
	}

	virtual bool Init();
	virtual bool BeforeShut();
	virtual bool Shut();
	virtual bool Execute();
	virtual bool AfterInit();
	virtual NFINetClientModule* GetNetClientModule();
	virtual void AddServerInfoExt(const std::string& key, const std::string& value);
protected:

	void OnSocketMSEvent(const int nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet);

	void OnClientDisconnect(const int nAddress);

	void OnClientConnected(const int nAddress);

	virtual void LogServerInfo(const std::string& strServerInfo);

	void Register(NFINet* pNet);
	void ServerReport();
	void RefreshWorldInfo();

	void OnSelectServerProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
	void OnKickClientProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);

	void InvalidMessage(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
private:
	NFINT64 mLastReportTime;

	NFILogModule* m_pLogModule;
	NFIElementModule* m_pElementModule;
	NFIClassModule* m_pClassModule;
	NFIWorldNet_ServerModule* m_pWorldNet_ServerModule;
	NFINetClientModule* m_pNetClientModule;
	std::map<std::string, std::string> m_mServerInfoExt;
};

#endif


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

namespace _09_Extract_Mid_Elements
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] answer = Console.ReadLine()
                .Split(' ')
                .Select(int.Parse)
                .ToArray();

            if (answer.Length == 1)
            {
                Console.WriteLine($"{{ {answer[0]} }}");
            }
            else if (answer.Length % 2 == 0)
            {
                Console.WriteLine($"{{ {answer[answer.Length / 2 - 1]}, {answer[answer.Length / 2]} }}");
            }
            else
            {
                Console.WriteLine($"{{ {answer[answer.Length / 2 - 1]}, {answer[answer.Length / 2]}, {answer[answer.Length / 2 + 1]} }}");
            }
        }
    }
}


text:
load('../base.js');
load('create-many-closures.js');

var success = true;

function PrintResult(name, result) {
  print(name + '-ManyClosures(Score): ' + result);
}

function PrintError(name, error) {
  PrintResult(name, error);
  success = false;
}

BenchmarkSuite.config.doWarmup = undefined;
BenchmarkSuite.config.doDeterministic = undefined;

BenchmarkSuite.RunSuites({ NotifyResult: PrintResult,
                           NotifyError: PrintError });


text:
<meta charset="UTF-8">
<title>tick - </title>
<link rel="stylesheet" href="../../style.css">

io.sureshg.extn / kotlin.String / tick

tick

inline val String.tick: String

OK option string.


text:
package com.gu.logback.appender.kinesis;

import java.net.URI;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.firehose.FirehoseAsyncClient;
import software.amazon.awssdk.services.firehose.FirehoseAsyncClientBuilder;
import software.amazon.awssdk.services.firehose.model.DeliveryStreamStatus;
import software.amazon.awssdk.services.firehose.model.DescribeDeliveryStreamRequest;
import software.amazon.awssdk.services.firehose.model.DescribeDeliveryStreamResponse;
import software.amazon.awssdk.services.firehose.model.ResourceNotFoundException;
import com.gu.logback.appender.kinesis.helpers.FirehoseStatsReporter;

import ch.qos.logback.core.spi.DeferredProcessingAware;

/**
 * LOGBack Appender implementation to support sending data from java
 * applications directly into a Kinesis Firehose stream.
 *
 * More details are available
 * here
 *
 * @since 1.4
 */
public class FirehoseAppender<Event extends DeferredProcessingAware>
    extends BaseKinesisAppender<Event, FirehoseAsyncClient> {

  private FirehoseStatsReporter asyncCallHandler = new FirehoseStatsReporter(this);

  @Override
  protected FirehoseAsyncClient createClient(AwsCredentialsProvider credentials, ClientOverrideConfiguration configuration, ThreadPoolExecutor executor, Region region, Optional<URI> endpointOverride) {
    FirehoseAsyncClientBuilder builder = FirehoseAsyncClient.builder()
      .credentialsProvider(credentials)
      .asyncConfiguration(b -> b.advancedOption(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, executor))
      .overrideConfiguration(configuration)
      .region(region);

    endpointOverride.ifPresent(endpoint -> builder.endpointOverride(endpoint));

    return builder.build();
  }

  @Override
  protected void validateStreamName(FirehoseAsyncClient client, String streamName) {
    DescribeDeliveryStreamResponse describeResponse;
    try {
      describeResponse = getClient()
        .describeDeliveryStream(b -> b.deliveryStreamName(streamName).build())
        .get();
      DeliveryStreamStatus streamStatus = describeResponse.deliveryStreamDescription().deliveryStreamStatus();
      if(!DeliveryStreamStatus.ACTIVE.equals(streamStatus)) {
        setInitializationFailed(true);
        addError("Stream " + streamName + " is not ready (in active status) for appender: " + name);
      }
    }
    catch(InterruptedException ie) {
      setInitializationFailed(true);
      addError("Interrupted while attempting to describe " + streamName, ie);
    }
    catch(ExecutionException ee) {
      setInitializationFailed(true);
      addError("Error executing the operation", ee);
    }
    catch(ResourceNotFoundException rnfe) {
      setInitializationFailed(true);
      addError("Stream " + streamName + " doesn't exist for appender: " + name, rnfe);
    }
    catch(AwsServiceException ase) {
      setInitializationFailed(true);
      addError("Error connecting to AWS to verify stream " + streamName + " for appender: " + name, ase);
    }
  }

  @Override
  protected void putMessage(String message) throws Exception {
    SdkBytes data = SdkBytes.fromByteArray(message.getBytes(getEncoding()));
    getClient().putRecord(builder ->
      builder
        .deliveryStreamName(getStreamName())
        .record(b -> b.data(data).build())
        .build()).whenCompleteAsync(asyncCallHandler);
  }

}


text:
module Luggage
  class Mailbox
    include Enumerable

    attr_reader :connection, :name

    def self.convert_mailbox_name(mailbox_name)
      case mailbox_name
      when :g_all
        "[Gmail]/All Mail"
      when :g_sent
        "[Gmail]/Sent"
      when :g_trash
        "[Gmail]/Trash"
      when :inbox, :spam, :sent, :trash
        mailbox_name.to_s.upcase
      when Symbol
        mailbox_name.to_s
      when String
        mailbox_name
      else
        nil
      end
    end

    # This provides an interface to a remote Imap mailbox
    #
    # `connection` should be an authenticated Net::IMAP
    #
    # `name` is the name of the remote mailbox
    #
    def initialize(connection, name, &block)
      @connection = connection
      @name = name

      instance_eval &block if block_given?
    end

    # Constructs an Message whose mailbox will be set to this instance
    #
    # `args` will be passed to ImapFactorY::Message#new_local - see that method for details
    #
    def message(args = {}, &block)
      Message.new_local(connection, self, args, &block)
    end

    # Returns true if this mailbox exists on the remote server, false otherwise
    #
    def exists?
      return @exists if instance_variable_defined?(:@exists)

      @exists = !connection.list("", name).nil?
    end

    # Deletes this mailbox on the remote server
    #
    def delete!
      connection.delete(name)
      @exists = false
    end

    # Selects this mailbox for future Imap commands.
    #
    def select!
       connection.select(name)
    end

    # Creates the mailbox on the remote server if it doesn't exist already
    #
    def save!
      unless exists?
        connection.create(name)
      end
    end

    # Removes 'deleted' messages on the remote server.  Message#delete! marks
    # messages with the 'Deleted' flag, but leaves them on the server.  This removes
    # them entirely
    #
    def expunge!
      select!
      connection.expunge()
    end

    # Returns an array of Message instances describing all emails in the remote mailbox
    #
    def all
      MailboxQueryBuilder.new(self)
    end

    # Returns a Message instance describing the first email on the remote mailbox
    #
    def first
      all.first
    end

    # Iterates over Mailbox#each
    #
    def each(&block)
      all.each(&block)
    end

    # Filters emails on the remote server
    #
    # Returns a MailboxQueryBuilder - see MailboxQueryBuilder#where for usage details
    #
    def where(*args)
      all.where(*args)
    end

    def inspect
      "#<Luggage::Mailbox server: \"#{host}\", name: \"#{name}\">"
    end

    def host
      connection.instance_variable_get(:@host)
    end
  end
end


text:
//-----------------------------------------------------------------------
// <copyright file="AnalysisType.cs" company="SonarSource SA and Microsoft Corporation">
//   Copyright (c) SonarSource SA and Microsoft Corporation.  All rights reserved.
//   Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------

namespace SonarQube.Common
{
    /* If we move to a plug-in model (i.e. so handlers for new types of analyzers
       can be plugged in at runtime e.g. using MEF) then this enum would be removed.
       For the time being we are only supported a known set of analyzers.
    */

    /// <summary>
    /// Lists the known types of analyzers that are handled by the properties generator
    /// </summary>
    public enum AnalysisType
    {
        /// <summary>
        /// List of files that should be analyzed
        /// </summary>
        /// <remarks>The files could be of any type and any language</remarks>
        FilesToAnalyze,

        /// <summary>
        /// An FxCop results file
        /// </summary>
        FxCop,

        /// <summary>
        /// An XML code coverage report produced by the Visual Studio code coverage tool
        /// </summary>
        VisualStudioCodeCoverage
    }
}


text:
require 'facter'
#require 'CFPropertyList'
Facter.add(:xcode_installed) do
  confine :kernel => 'Darwin'
  setcode do
    if Facter.value(:xcode_version) #!= nil
      true
    else
      false
    end
  end
end


text:
@interface SPDYTests : SenTestCase

@end


text:
package io.dropwizard.util;

import java.io.IOException;
import java.io.Reader;

/**
 * @since 2.0
 */
public final class CharStreams {

    private CharStreams() {
    }

    public static String toString(Reader reader) throws IOException {
        final StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int length;
        while ((length = reader.read(buffer)) != -1) {
            builder.append(buffer, 0, length);
        }
        return builder.toString();
    }
}


text:
Snpr::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  OH_REDIRECT_URL = 'https://opensnp.org/openhumans/authorize'

  # The production environment is meant for finished, "live" apps.
  # Code is not reloaded between requests
  config.cache_classes = true

  # Full error reports are disabled and caching is turned on
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Specifies the header that your server uses for sending files
  # config.action_dispatch.x_sendfile_header = "X-Sendfile"

  # For nginx:
  # see https://github.com/mperham/sidekiq/wiki/Problems-and-Troubleshooting#sidekiq-web-does-not-render-correctly-in-production-but-works-fine-in-development
  config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'

  # If you have no front-end server that supports something like X-Sendfile,
  # just comment this out and Rails will serve the files

  # See everything in the log (default is :info)
  config.log_level = :info

  # Use a different logger for distributed setups
  config.logger = Logger.new($stdout)

  # Use a different cache store in production
  # config.cache_store = :mem_cache_store

  # Serve files from /public directory
  config.serve_static_files = false

  # Enable serving of images, stylesheets, and javascripts from an asset server
  # config.action_controller.asset_host = "http://assets.example.com"
  config.action_mailer.delivery_method = :sendmail
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_options = {
    from: 'no-reply@opensnp.org'
  }
  config.action_mailer.asset_host = "https://opensnp.org"

  # Enable threaded mode
  # config.threadsafe!

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners
  config.active_support.deprecation = :notify

  # Compress JavaScript and CSS
  config.assets.compress = true
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :yui

  # Don't fallback to assets pipeline
  config.assets.compile = false

  # Generate digests for assets URLs
  config.assets.digest = true

  config.lograge.enabled = true

  # Eager load code on boot.
  config.eager_load = true

  # Make ActiveJob and hence ActionMailer use Sidekiq
  config.active_job.queue_adapter = :sidekiq
end


text:
<?php

namespace RadioSolution\PodcastBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PodcastBundle extends Bundle
{
}


text:
from flatland.util import Maybe

YES = (u'1', u'true', u'True', u't', u'on', u'yes')
NO = (u'0', u'false', u'False', u'nil', u'off', u'no')
MAYBE = (u'auto',)

def parse_trool(value):
    if value is True or value is False or value is Maybe:
        return value
    if isinstance(value, unicode):
        value = value.lower()
    else:
        value = unicode(value).lower()
    if value in YES:
        return True
    if value in NO:
        return False
    if value in MAYBE:
        return Maybe
    return Maybe


text:
<?php defined('DOCROOT') or die('No direct access allowed.');

class Benchmark_FirstLine {

	public $string = "Hello World!\nThis is just\nsome test string";

	public function substr()
	{
		return substr($this->string, 0, strpos($this->string, "\n"));
	}

	public function substr2()
	{
		return substr($this->string, 0, strpos($this->string, chr(10)));
	}

	public function strtok()
	{
		return strtok($this->string, "\n");
	}

	public function explode()
	{
		list($line_1, $remaining) = explode("\n", $this->string, 2);
		return $line_1;
	}

	public function str_replace()
	{
		return str_replace(strstr($this->string, "\n"), "", $this->string);
	}

}


text:
<?php

namespace DesignPatterns\Creational\StaticFactory;

/**
 * Note1: Remember, static means global state which is evil because it can't be mocked for tests
 * Note2: Cannot be subclassed or mock-upped or have multiple different instances.
 */
final class StaticFactory
{
    /**
     * @param string $type
     *
     * @return FormatterInterface
     */
    public static function factory(string $type): FormatterInterface
    {
        if ($type == 'number') {
            return new FormatNumber();
        }

        if ($type == 'string') {
            return new FormatString();
        }

        throw new \InvalidArgumentException('Unknown format given');
    }
}


text:
import React, {Component} from 'react';
// import Loader from 'components/Loader';
import _ from 'lodash';
import './payment-methods.less'

class PaymentMethods extends Component {
  state = {
    configs: {}
  }

  render() {
    const braintreeData = _.get(this.props, 'braintreeData');
    const cards = braintreeData.creditCards;
    const paypalAccounts = braintreeData.paypalAccounts
    const paypal = _.get(this.props.user, 'details.braintree_data.data.paypalAccount');
    const cancelToken = _.get(this.props.subscription, 'deletePaymentMethodLoading');
    console.log(this.props.resourceId, 'dddd')
    return (

        {
          cards && cards.length ?

{paypal ? 'Connected Paypal Account' : 'Payment Method'}

            {
              _.map(cards, (us, i) => {
                return (

Card: {`${us.cardType} ending ${us.last4}`}

Subscriptions: {_.filter(us.subscriptions, (s) => s.status === 'Active').length}

                     <button disabled={cancelToken === us.token} onClick={this.deletePayentMethod.bind(this, us)} style={{height: "35px", lineHeight: '20px'}} className="primary-btn-large">
                        {
                          cancelToken === us.token ?
                          'Removing' : 'Remove'
                        }
                      </button>

 {this.setState({renderPaymentMethodForm: 'update', upateCard: us})}}>Update Card

                )
              })
            }

 : null
        }
        {
          paypalAccounts && paypalAccounts.length ?

Connected Paypal Accounts

            {
              _.map(paypalAccounts, (us, n) => {
                return (
                  <div key={`n-${n}`} className="flex" style={{justifyContent: 'space-between'}}>

Email: {us.email}

Subscriptions: {_.filter(us.subscriptions, (s) => s.status === 'Active').length}

                   <button disabled={cancelToken === us.token} onClick={this.deletePayentMethod.bind(this, us)} style={{height: "35px", lineHeight: '20px'}} className="primary-btn-large">
                      {
                        cancelToken === us.token ?
                        'Removing' : 'Remove'
                      }
                    </button>

                )
              })
            }

 : null
        }
        {
          this.state.renderPaymentMethodForm ?
          this.renderPaymentMethodForm() : null
        }

    );
  }

  resetStateFromForm() {
    if (!this.state.submitting) {
      this.setState({success: null, error: false, renderPaymentMethodForm: null, upateCard: null})
    }
  }

  renderPaymentMethodForm() {
    return (
      <div className={`payment-form-wrapper ${this.state.renderPaymentMethodForm}`} onClick={this.resetStateFromForm.bind(this)}>

 e.stopPropagation()}>
         render form

    )
  }

  async deletePayentMethod(us) {
    if (window.confirm("Deleting Your Card Will Remove Your Plan. Do You Want To Continue?")) {
      const deletedCard = await this.props.deletelBraintreePaymentMethod(us.token, this.props.resourceId);
    }
  }

}

export default PaymentMethods


text:
<?php
/* @var $this OpenVragenAntwoordenController */
/* @var $model OpenVragenAntwoorden */

$this->breadcrumbs=array(
	'Open Vragen Antwoordens'=>array('index'),
	$model->open_vragen_antwoorden_ID,
);

$this->menu=array(
	array('label'=>'List OpenVragenAntwoorden', 'url'=>array('index')),
	array('label'=>'Create OpenVragenAntwoorden', 'url'=>array('create')),
	array('label'=>'Update OpenVragenAntwoorden', 'url'=>array('update', 'id'=>$model->open_vragen_antwoorden_ID)),
	array('label'=>'Delete OpenVragenAntwoorden', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->open_vragen_antwoorden_ID),'confirm'=>'Are you sure you want to delete this item?')),
	array('label'=>'Manage OpenVragenAntwoorden', 'url'=>array('admin')),
);
?>

View OpenVragenAntwoorden #<?php echo $model->open_vragen_antwoorden_ID; ?>

<?php $this->widget('zii.widgets.CDetailView', array(
	'data'=>$model,
	'attributes'=>array(
		'open_vragen_antwoorden_ID',
		'open_vragen_ID',
		'group_ID',
		'vraag',
		'antwoord_spelers',
		'checked',
		'correct',
		'score',
		'create_time',
		'create_user_ID',
		'update_time',
		'update_user_ID',
	),
)); ?>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.authorization.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Specifying the claims to be included in a token. */
@Fluent
public final class OptionalClaim {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(OptionalClaim.class);

    /*
     * Claim name.
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * Claim source.
     */
    @JsonProperty(value = "source")
    private String source;

    /*
     * Is this a required claim.
     */
    @JsonProperty(value = "essential")
    private Boolean essential;

    /*
     * Any object
     */
    @JsonProperty(value = "additionalProperties")
    private Object additionalProperties;

    /**
     * Get the name property: Claim name.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: Claim name.
     *
     * @param name the name value to set.
     * @return the OptionalClaim object itself.
     */
    public OptionalClaim withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the source property: Claim source.
     *
     * @return the source value.
     */
    public String source() {
        return this.source;
    }

    /**
     * Set the source property: Claim source.
     *
     * @param source the source value to set.
     * @return the OptionalClaim object itself.
     */
    public OptionalClaim withSource(String source) {
        this.source = source;
        return this;
    }

    /**
     * Get the essential property: Is this a required claim.
     *
     * @return the essential value.
     */
    public Boolean essential() {
        return this.essential;
    }

    /**
     * Set the essential property: Is this a required claim.
     *
     * @param essential the essential value to set.
     * @return the OptionalClaim object itself.
     */
    public OptionalClaim withEssential(Boolean essential) {
        this.essential = essential;
        return this;
    }

    /**
     * Get the additionalProperties property: Any object.
     *
     * @return the additionalProperties value.
     */
    public Object additionalProperties() {
        return this.additionalProperties;
    }

    /**
     * Set the additionalProperties property: Any object.
     *
     * @param additionalProperties the additionalProperties value to set.
     * @return the OptionalClaim object itself.
     */
    public OptionalClaim withAdditionalProperties(Object additionalProperties) {
        this.additionalProperties = additionalProperties;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LythumOSL.Indigo.Metadata
{
	public interface IColumnDictionaryDesc
	{
		ITableDesc TableDesc { get; }
		int IdColumn { get; }
		int NameColumn { get; }
	}
}


text: SIP in idiomatic Go


text:
var Backbone = require('backbone');

var Request = require('../../../source/js/models/request');

// Declare internals

var internals = {};

describe('Request', function () {

    describe('#hasError', function () {

        it('returns true if request timed out', function () {

            var request = new Request({ responseTimeout: true });

            expect(request.hasError()).to.be.true;
        });

        it('returns true if status code is 500', function () {

            var request = new Request({ statusCode: 500 });

            expect(request.hasError()).to.be.true;
        });

        it('returns false otherwise', function () {

            var request = new Request();

            expect(request.hasError()).to.be.false;
        });

    });

    describe('#hasWarning', function () {

        it('returns true if statusCode inbetween 400 and 500', function () {

            var request = new Request({ statusCode: 422 });

            expect(request.hasWarning()).to.be.true;
        });

        it('returns false otherwise', function () {

            var request = new Request({ statusCode: 200 });

            expect(request.hasWarning()).to.be.false;
        });

    });

    describe('#toJSON', function () {

        it('parses all subcomponents', function () {

            var request = new Request({ statusCode: 200 });
            request.set('serverLogs', new Backbone.Collection([{ foo: 'bar', bar: 'baz' }]));

            expect(request.toJSON().serverLogs).to.be.an.instanceOf(Array);
        });

    });

});


text:
angular.module('app.directives')
.directive("menu", function() {
  return {
  restrict : 'E',
  templateURL: "template/menuConnection.html",
  controller: "menuConnectionCtrl",
  controllerAs: "vm"
  }
})