text:
"""Finds android browsers that can be started and controlled by telemetry."""

from __future__ import absolute_import
import contextlib
import logging
import os
import platform
import posixpath
import shutil
import subprocess

from devil import base_error
from devil.android import apk_helper
from devil.android import flag_changer
from devil.android.sdk import version_codes
from py_utils import dependency_util
from py_utils import file_util
from py_utils import tempfile_ext
from telemetry import compat_mode_options
from telemetry import decorators
from telemetry.core import exceptions
from telemetry.core import platform as telemetry_platform
from telemetry.core import util
from telemetry.internal.backends import android_browser_backend_settings
from telemetry.internal.backends.chrome import android_browser_backend
from telemetry.internal.backends.chrome import chrome_startup_args
from telemetry.internal.browser import browser
from telemetry.internal.browser import possible_browser
from telemetry.internal.platform import android_device
from telemetry.internal.util import binary_manager
from telemetry.internal.util import format_for_logging
from telemetry.internal.util import local_first_binary_manager

ANDROID_BACKEND_SETTINGS = (
    android_browser_backend_settings.ANDROID_BACKEND_SETTINGS)

@contextlib.contextmanager
def _ProfileWithExtraFiles(profile_dir, profile_files_to_copy):
  """Yields a temporary directory populated with input files.

  Args:
    profile_dir: A directory whose contents will be copied to the output
      directory.
    profile_files_to_copy: A list of (source, dest) tuples to be copied to
      the output directory.

  Yields: A path to a temporary directory, named "_default_profile". This
    directory will be cleaned up when this context exits.
  """
  with tempfile_ext.NamedTemporaryDirectory() as tempdir:
    # TODO(csharrison): "_default_profile" was chosen because this directory
    # will be pushed to the device's sdcard. We don't want to choose a
    # random name due to the extra failure mode of filling up the sdcard
    # in the case of unclean test teardown. We should consider changing
    # PushProfile to avoid writing to this intermediate location.
    host_profile = os.path.join(tempdir, '_default_profile')
    if profile_dir:
      shutil.copytree(profile_dir, host_profile)
    else:
      os.mkdir(host_profile)

    # Add files from |profile_files_to_copy| into the host profile
    # directory. Don't copy files if they already exist.
    for source, dest in profile_files_to_copy:
      host_path = os.path.join(host_profile, dest)
      if not os.path.exists(host_path):
        file_util.CopyFileWithIntermediateDirectories(source, host_path)
    yield host_profile

class PossibleAndroidBrowser(possible_browser.PossibleBrowser):
  """A launchable android browser instance."""

  def __init__(self, browser_type, finder_options, android_platform,
               backend_settings, local_apk=None, target_os='android'):
    super().__init__(
        browser_type, target_os, backend_settings.supports_tab_control)
    assert browser_type in FindAllBrowserTypes(), (
        'Please add %s to android_browser_finder.FindAllBrowserTypes' %
        browser_type)
    self._platform = android_platform
    self._platform_backend = (
        android_platform._platform_backend)  # pylint: disable=protected-access
    self._backend_settings = backend_settings
    self._local_apk = local_apk
    self._flag_changer = None
    self._modules_to_install = None
    self._compile_apk = finder_options.compile_apk
    self._finder_options = finder_options
    self._browser_package = None

    if self._local_apk is None and finder_options.chrome_root is not None:
      self._local_apk = self._backend_settings.FindLocalApk(
          self._platform_backend.device, finder_options.chrome_root)

    # At this point the local_apk, if any, must exist.
    assert self._local_apk is None or os.path.exists(self._local_apk)
    self._build_dir = util.GetBuildDirFromHostApkPath(self._local_apk)

    if finder_options.modules_to_install:
      self._modules_to_install = set(['base'] +
                                     finder_options.modules_to_install)

    self._support_apk_list = []
    if (self._backend_settings.requires_embedder or
        self._backend_settings.has_additional_apk):
      if finder_options.webview_embedder_apk:
        self._support_apk_list = finder_options.webview_embedder_apk
      else:
        self._support_apk_list = self._backend_settings.FindSupportApks(
            self._local_apk, finder_options.chrome_root)
    elif finder_options.webview_embedder_apk:
      logging.warning(
          'No embedder needed for %s, ignoring --webview-embedder-apk option',
          self._backend_settings.browser_type)

    # At this point the apks in _support_apk_list, if any, must exist.
    for apk in self._support_apk_list:
      assert os.path.exists(apk)

  def __repr__(self):
    return 'PossibleAndroidBrowser(browser_type=%s)' % self.browser_type

  @property
  def settings(self):
    """Get the backend_settings for this possible browser."""
    return self._backend_settings

  @property
  def browser_package(self):
    if not self._browser_package:
      self._browser_package = self._backend_settings.package
      if self._backend_settings.IsWebView():
        self._browser_package = (
            self._backend_settings.
            GetEmbedderPackageName(self._finder_options))
    return self._browser_package

  @property
  def browser_directory(self):
    # On Android L+ the directory where base APK resides is also used for
    # keeping extracted native libraries and .odex. Here is an example layout:
    # /data/app/$package.apps.chrome-1/
    #                                  base.apk
    #                                  lib/arm/libchrome.so
    #                                  oat/arm/base.odex
    # Declaring this toplevel directory as 'browser_directory' allows the cold
    # startup benchmarks to flush OS pagecache for the native library, .odex and
    # the APK.
    apks = self._platform_backend.device.GetApplicationPaths(
        self.browser_package)
    # A package can map to multiple APKs if the package overrides the app on
    # the system image. Such overrides should not happen on perf bots. The
    # package can also map to multiple apks if splits are used. In all cases, we
    # want the directory that contains base.apk.
    for apk in apks:
      if apk.endswith('/base.apk'):
        return apk[:-9]
    return None

  @property
  def profile_directory(self):
    return self._platform_backend.GetProfileDir(self.browser_package)

  @property
  def last_modification_time(self):
    if self._local_apk:
      return os.path.getmtime(self._local_apk)
    return -1

  def _GetPathsForOsPageCacheFlushing(self):
    return [self.profile_directory, self.browser_directory]

  def _InitPlatformIfNeeded(self):
    pass

  def _SetupProfile(self):
    if self._browser_options.dont_override_profile:
      return

    # Just remove the existing profile if we don't have any files to copy over.
    # This is because PushProfile does not support pushing completely empty
    # directories.
    profile_files_to_copy = self._browser_options.profile_files_to_copy
    if not self._browser_options.profile_dir and not profile_files_to_copy:
      self._platform_backend.RemoveProfile(
          self.browser_package,
          self._backend_settings.profile_ignore_list)
      return

    with _ProfileWithExtraFiles(self._browser_options.profile_dir,
                                profile_files_to_copy) as profile_dir:
      self._platform_backend.PushProfile(self.browser_package,
                                         profile_dir)

  def SetUpEnvironment(self, browser_options):
    super().SetUpEnvironment(browser_options)
    self._platform_backend.DismissCrashDialogIfNeeded()
    device = self._platform_backend.device
    startup_args = self.GetBrowserStartupArgs(self._browser_options)
    device.adb.Logcat(clear=True)

    # use legacy commandline path if in compatibility mode
    self._flag_changer = flag_changer.FlagChanger(
        device, self._backend_settings.command_line_name, use_legacy_path=
        compat_mode_options.LEGACY_COMMAND_LINE_PATH in
        browser_options.compatibility_mode)
    self._flag_changer.ReplaceFlags(startup_args, log_flags=False)
    formatted_args = format_for_logging.ShellFormat(
        startup_args, trim=browser_options.trim_logs)
    logging.info('Flags set on device were %s', formatted_args)
    # Stop any existing browser found already running on the device. This is
    # done *after* setting the command line flags, in case some other Android
    # process manages to trigger Chrome's startup before we do.
    self._platform_backend.StopApplication(self.browser_package)
    self._SetupProfile()

    # Remove any old crash dumps
    self._platform_backend.device.RemovePath(
        self._platform_backend.GetDumpLocation(self.browser_package),
        recursive=True, force=True)

  def _TearDownEnvironment(self):
    self._RestoreCommandLineFlags()

  def _RestoreCommandLineFlags(self):
    if self._flag_changer is not None:
      try:
        self._flag_changer.Restore()
      finally:
        self._flag_changer = None

  def Create(self):
    """Launch the browser on the device and return a Browser object."""
    return self._GetBrowserInstance(existing=False)

  def FindExistingBrowser(self):
    """Find a browser running on the device and bind a Browser object to it.

    The returned Browser object will only be bound to a running browser
    instance whose package name matches the one specified by the backend
    settings of this possible browser.

    A BrowserGoneException is raised if the browser cannot be found.
    """
    return self._GetBrowserInstance(existing=True)

  def _GetBrowserInstance(self, existing):
    # Init the LocalFirstBinaryManager if this is the first time we're creating
    # a browser. Note that we use the host's OS and architecture since the
    # retrieved dependencies are used on the host, not the device.
    if local_first_binary_manager.LocalFirstBinaryManager.NeedsInit():
      local_first_binary_manager.LocalFirstBinaryManager.Init(
          self._build_dir, self._local_apk, platform.system().lower(),
          platform.machine())

    browser_backend = android_browser_backend.AndroidBrowserBackend(
        self._platform_backend, self._finder_options,
        self.browser_directory, self.profile_directory,
        self._backend_settings, build_dir=self._build_dir,
        local_apk_path=self._local_apk)
    try:
      return browser.Browser(
          browser_backend, self._platform_backend, startup_args=(),
          find_existing=existing)
    except Exception:
      browser_backend.Close()
      raise

  def GetBrowserStartupArgs(self, browser_options):
    startup_args = chrome_startup_args.GetFromBrowserOptions(browser_options)
    # use the flag `--ignore-certificate-errors` if in compatibility mode
    supports_spki_list = (
        self._backend_settings.supports_spki_list and
        compat_mode_options.IGNORE_CERTIFICATE_ERROR
        not in browser_options.compatibility_mode)
    startup_args.extend(chrome_startup_args.GetReplayArgs(
        self._platform_backend.network_controller_backend,
        supports_spki_list=supports_spki_list))
    startup_args.append('--enable-remote-debugging')
    startup_args.append('--disable-fre')
    startup_args.append('--disable-external-intent-requests')

    # Need to specify the user profile directory for
    # --ignore-certificate-errors-spki-list to work.
    startup_args.append('--user-data-dir=' + self.profile_directory)

    # Needed so that non-browser-process crashes avoid automatic dump upload
    # and subsequent deletion. The extra "Crashpad" is necessary because
    # crashpad_stackwalker.py is hard-coded to look for a "Crashpad" directory
    # in the dump directory that it is provided.
    startup_args.append('--breakpad-dump-location=' + posixpath.join(
        self._platform_backend.GetDumpLocation(self.browser_package),
        'Crashpad'))

    return startup_args

  def SupportsOptions(self, browser_options):
    if len(browser_options.extensions_to_load) != 0:
      return False
    return True

  def IsAvailable(self):
    """Returns True if the browser is or can be installed on the platform."""
    has_local_apks = self._local_apk and (
        not self._backend_settings.requires_embedder or self._support_apk_list)
    return has_local_apks or self.platform.CanLaunchApplication(
        self.settings.package)

  @decorators.Cache
  def UpdateExecutableIfNeeded(self):
    # TODO(crbug.com/815133): This logic should belong to backend_settings.
    for apk in self._support_apk_list:
      logging.warning('Installing %s on device if needed.', apk)
      self.platform.InstallApplication(apk)

    apk_name = self._backend_settings.GetApkName(
        self._platform_backend.device)
    is_webview_apk = apk_name is not None and ('SystemWebView' in apk_name or
                                               'system_webview' in apk_name or
                                               'TrichromeWebView' in apk_name or
                                               'trichrome_webview' in apk_name)
    # The WebView fallback logic prevents sideloaded WebView APKs from being
    # installed and set as the WebView implementation correctly. Disable the
    # fallback logic before installing the WebView APK to make sure the fallback
    # logic doesn't interfere.
    if is_webview_apk:
      self._platform_backend.device.SetWebViewFallbackLogic(False)

    if self._local_apk:
      logging.warning('Installing %s on device if needed.', self._local_apk)
      self.platform.InstallApplication(
          self._local_apk, modules=self._modules_to_install)
      if self._compile_apk:
        package_name = apk_helper.GetPackageName(self._local_apk)
        logging.warning('Compiling %s.', package_name)
        self._platform_backend.device.RunShellCommand(
            ['cmd', 'package', 'compile', '-m', self._compile_apk, '-f',
             package_name],
            check_return=True,
            timeout=120)

    sdk_version = self._platform_backend.device.build_version_sdk
    # Bundles are in the ../bin directory, so it's safer to just check the
    # correct name is part of the path.
    is_monochrome = apk_name is not None and (apk_name == 'Monochrome.apk' or
                                              'monochrome_bundle' in apk_name)
    if ((is_webview_apk or
         (is_monochrome and sdk_version < version_codes.Q)) and
        sdk_version >= version_codes.NOUGAT):
      package_name = apk_helper.GetPackageName(self._local_apk)
      logging.warning('Setting %s as WebView implementation.', package_name)
      self._platform_backend.device.SetWebViewImplementation(package_name)

  def GetTypExpectationsTags(self):
    tags = super().GetTypExpectationsTags()
    if 'webview' in self.browser_type:
      tags.append('android-webview')
    else:
      tags.append('android-not-webview')
    if 'weblayer' in self.browser_type:
      tags.append('android-weblayer')
    return tags

def SelectDefaultBrowser(possible_browsers):
  """Return the newest possible browser."""
  if not possible_browsers:
    return None
  return max(possible_browsers, key=lambda b: b.last_modification_time)

def CanFindAvailableBrowsers():
  return android_device.CanDiscoverDevices()

def _CanPossiblyHandlePath(apk_path):
  if not apk_path:
    return False
  try:
    apk_helper.ToHelper(apk_path)
    return True
  except apk_helper.ApkHelperError:
    return False

def FindAllBrowserTypes():
  browser_types = [b.browser_type for b in ANDROID_BACKEND_SETTINGS]
  return browser_types + ['exact', 'reference']

def _FetchReferenceApk(android_platform, is_bundle=False):
  """Fetch the apk for reference browser type from gcloud.

  Local path to the apk will be returned upon success.
  Otherwise, None will be returned.
  """
  os_version = dependency_util.GetChromeApkOsVersion(
      android_platform.GetOSVersionName())
  if is_bundle:
    os_version += '_bundle'
  arch = android_platform.GetArchName()
  try:
    reference_build = binary_manager.FetchPath(
        'chrome_stable', 'android', arch, os_version)
    if reference_build and os.path.exists(reference_build):
      return reference_build
  except binary_manager.NoPathFoundError:
    logging.warning('Cannot find path for reference apk for device %s',
                    android_platform.GetDeviceId())
  except binary_manager.CloudStorageError:
    logging.warning('Failed to download reference apk for device %s',
                    android_platform.GetDeviceId())
  return None

def _GetReferenceAndroidBrowser(android_platform, finder_options):
  reference_build = _FetchReferenceApk(android_platform)
  if reference_build:
    return PossibleAndroidBrowser(
        'reference',
        finder_options,
        android_platform,
        android_browser_backend_settings.ANDROID_CHROME,
        reference_build)
  return None

def _FindAllPossibleBrowsers(finder_options, android_platform):
  """Testable version of FindAllAvailableBrowsers."""
  if not android_platform:
    return []
  possible_browsers = []

  for apk in finder_options.webview_embedder_apk:
    if not os.path.exists(apk):
      raise exceptions.PathMissingError(
          'Unable to find apk specified by --webview-embedder-apk=%s' % apk)

  # Add the exact APK if given.
  if _CanPossiblyHandlePath(finder_options.browser_executable):
    if not os.path.exists(finder_options.browser_executable):
      raise exceptions.PathMissingError(
          'Unable to find exact apk specified by --browser-executable=%s' %
          finder_options.browser_executable)

    package_name = apk_helper.GetPackageName(finder_options.browser_executable)
    try:
      backend_settings = next(
          b for b in ANDROID_BACKEND_SETTINGS if b.package == package_name)
    except StopIteration as e:
      raise exceptions.UnknownPackageError(
          '%s specified by --browser-executable has an unknown package: %s' %
          (finder_options.browser_executable, package_name)) from e

    possible_browsers.append(PossibleAndroidBrowser(
        'exact',
        finder_options,
        android_platform,
        backend_settings,
        finder_options.browser_executable))

  if finder_options.IsBrowserTypeRelevant('reference'):
    reference_browser = _GetReferenceAndroidBrowser(
        android_platform, finder_options)
    if reference_browser:
      possible_browsers.append(reference_browser)

  # Add any other known available browsers.
  for settings in ANDROID_BACKEND_SETTINGS:
    if finder_options.IsBrowserTypeRelevant(settings.browser_type):
      local_apk = None
      if finder_options.IsBrowserTypeReference():
        local_apk = _FetchReferenceApk(
            android_platform, finder_options.IsBrowserTypeBundle())

      if settings.IsWebView():
        p_browser = PossibleAndroidBrowser(
            settings.browser_type, finder_options, android_platform, settings,
            local_apk=local_apk, target_os='android_webview')
      else:
        p_browser = PossibleAndroidBrowser(
            settings.browser_type, finder_options, android_platform, settings,
            local_apk=local_apk)
      if p_browser.IsAvailable():
        possible_browsers.append(p_browser)
  return possible_browsers

def FindAllAvailableBrowsers(finder_options, device):
  """Finds all the possible browsers on one device.

  The device is either the only device on the host platform,
  or |finder_options| specifies a particular device.
  """
  if not isinstance(device, android_device.AndroidDevice):
    return []

  try:
    android_platform = telemetry_platform.GetPlatformForDevice(
        device, finder_options)
    return _FindAllPossibleBrowsers(finder_options, android_platform)
  except base_error.BaseError as e:
    logging.error('Unable to find browsers on %s: %s', device.device_id, str(e))
    ps_output = subprocess.check_output(['ps', '-ef'])
    logging.error('Ongoing processes:\n%s', ps_output)
  return []


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.azure.servicebus.primitives;

/**
 * this exception is thrown when user attempts to send a event data or brokered message that has exceeded the
 * allowed payload size as defined by the service. Note that in a batch send scenario the limit can include possible
 * batch overhead.
 * @see http://go.microsoft.com/fwlink/?LinkId=761101
 * @since 1.0
 */
public class PayloadSizeExceededException extends ServiceBusException {
    private static final long serialVersionUID = 3627182744252750014L;

    PayloadSizeExceededException() {
        super(false);
    }

    PayloadSizeExceededException(final String message) {
        super(false, message);
    }

    PayloadSizeExceededException(final Throwable cause) {
        super(false, cause);
    }

    PayloadSizeExceededException(final String message, final Throwable cause) {
        super(false, message, cause);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.sksamuel.avro4s.encoders

import com.sksamuel.avro4s.typeutils.{CaseClassShape, DatatypeShape, SealedTraitShape}
import com.sksamuel.avro4s.{Encoder, SchemaFor}
import magnolia1.{CaseClass, AutoDerivation, SealedTrait, TypeInfo}
import org.apache.avro.{Schema, SchemaBuilder}

import scala.deriving.Mirror

trait MagnoliaDerivedEncoder extends AutoDerivation[Encoder] :
  override def join[T](ctx: CaseClass[Encoder, T]): Encoder[T] = new RecordEncoder(ctx)

  override def split[T](ctx: SealedTrait[Encoder, T]): Encoder[T] =
    DatatypeShape.of[T](ctx) match {
      case SealedTraitShape.TypeUnion => TypeUnions.encoder(ctx)
      case SealedTraitShape.Enum => SealedTraits.encoder(ctx)
    }


text:
const path = require('path');
const matched = require('matched');

var curPackFiles = null;  //当前包的所有的文件
var mentry = 'multientry:entry-point';
function multiInput(options) {
    let packPath = options ? options.path : null;   // 除了制定输入以外,这个目录下的也可以认为是内部文件,可以引用
    if (packPath) {
        packPath = path.join(__dirname, packPath);
    }

    function pathInPack(p) {
        if (!packPath)
            return false;    // 没有设置,则认为false,
        let r = path.relative(packPath, p);
        if (r.startsWith('..'))  //TODO 如果盘符都变了这样是不对的
            return false;
        return true;
    }

    var include = [];
    var exclude = [];
    function configure(config) {
        if (typeof config === 'string') {
            include = [config];
        } else if (Array.isArray(config)) {
            include = config;
        } else {
            include = config.include || [];
            exclude = config.exclude || [];

            if (config.exports === false) {
                exporter = function exporter(p) {
                    if (p.substr(p.length - 3) == '.ts') {
                        p = p.substr(0, p.length - 3);
                    }
                    return `import ${JSON.stringify(p)};`;
                };
            }
        }
    }

    var exporter = function exporter(p) {
        if (p.substr(p.length - 3) == '.ts') {
            p = p.substr(0, p.length - 3);
        }
        return `export * from ${JSON.stringify(p)};`;
    };

    return (
        {
            options(options) {
                // console.log('===', options.input)
                configure(options.input);
                options.input = mentry;
            },

            resolveId(id, importer) {//entry是个特殊字符串,rollup并不识别,所以假装这里解析一下
                if (id === mentry) {
                    return mentry;
                }
                if (mentry == importer)
                    return;
                var importfile = path.join(path.dirname(importer), id);
                var ext = path.extname(importfile);
                if (ext != '.ts' && ext != '.glsl' && ext != '.vs' && ext != '.ps' && ext != '.fs') {
                    importfile += '.ts';
                }
                // console.log('import ', importfile);
                if (importfile.endsWith('.json')) {
                    console.log('import ', importfile);
                }
                //console.log('id=',id);
                // 不在本包所在目录,并且不在指定的目录中
                if (curPackFiles.indexOf(importfile) < 0 && !pathInPack(importfile)) {
                    //其他包里的文件
                     //console.log('other pack:',id,'impo   rter=', importer);
                    return 'Laya';
                }
            },
            load(id) {
                if (id === mentry) {
                    if (!include.length) {
                        return Promise.resolve('');
                    }

                    var patterns = include.concat(exclude.map(function (pattern) {
                        return '!' + pattern;
                    }));
                    return matched.promise(patterns, { realpath: true }).then(function (paths) {
                        curPackFiles = paths;   // 记录一下所有的文件
                        paths.sort();
                        //console.log(curPackFiles);
                        return paths.map(exporter).join('\n');
                    });
                } else {
                    //console.log('load ',id);
                }
            }
        }
    );
}

module.exports = multiInput;


text:
<?php

namespace cascade\models;

use cascade\components\db\ActiveRecordTrait;

/**
 * DeferredAction is the model class for table "deferred_action".
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class DeferredAction extends \canis\db\models\DeferredAction
{
    use ActiveRecordTrait;
}


text:
package org.hisp.dhis.feedback;

import org.hisp.dhis.common.DxfNamespaces;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.google.common.base.MoreObjects;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@JacksonXmlRootElement( localName = "stats", namespace = DxfNamespaces.DXF_2_0 )
public class Stats
{
    private int created;

    private int updated;

    private int deleted;

    private int ignored;

    public Stats()
    {
    }

    public void merge( Stats stats )
    {
        created += stats.getCreated();
        updated += stats.getUpdated();
        deleted += stats.getDeleted();
        ignored += stats.getIgnored();
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public int getTotal()
    {
        return created + updated + deleted + ignored;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public int getCreated()
    {
        return created;
    }

    public void incCreated()
    {
        created++;
    }

    public void incCreated( int n )
    {
        created += n;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public int getUpdated()
    {
        return updated;
    }

    public void incUpdated()
    {
        updated++;
    }

    public void incUpdated( int n )
    {
        updated += n;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public int getDeleted()
    {
        return deleted;
    }

    public void incDeleted()
    {
        deleted++;
    }

    public void incDeleted( int n )
    {
        deleted += n;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public int getIgnored()
    {
        return ignored;
    }

    public void incIgnored()
    {
        ignored++;
    }

    public void incIgnored( int n )
    {
        ignored += n;
    }

    public void ignored()
    {
        ignored += created;
        ignored += updated;
        ignored += deleted;

        created = 0;
        updated = 0;
        deleted = 0;
    }

    @Override
    public String toString()
    {
        return MoreObjects.toStringHelper( this )
            .add( "created", created )
            .add( "updated", updated )
            .add( "deleted", deleted )
            .add( "ignored", ignored )
            .toString();
    }
}


text:
<?php

namespace Spl;

interface Stack extends Collection {

    /**
     * @param mixed $object
     *
     * @throws TypeException if $object is not the correct type.
     * @throws FullException if the Stack is full.
     * @return void
     */
    function pushBack($object);

    /**
     * @throws EmptyException if the Stack is empty.
     * @return mixed
     */
    function popBack();

    /**
     * @throws EmptyException if the Stack is empty.
     * @return mixed
     */
    function peekBack();

}


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

namespace SharpFlame.Core.Parsers.Ini
{
    public class IniReader
    {
        private static string rootSectionName = "Global";
        public static string RootSectionName {
            get { return rootSectionName; }
            set { rootSectionName = value; }
        }

        public static List<Section> ReadString (string txt) {
            var result = new List<Section> ();

            var currentSection = new Section (RootSectionName);

            foreach (var line in txt.Split(new[]{"\n"}, StringSplitOptions.RemoveEmptyEntries)
                     .Where(t => !string.IsNullOrWhiteSpace(t))
                     .Select(t => t.Trim())) {

                if (line.StartsWith("[") && line.EndsWith("]"))
                {
                    currentSection = new Section (line.Substring(1, line.LastIndexOf("]", StringComparison.InvariantCulture) - 1).Trim());
                    result.Add(currentSection);
                    continue;
                }

                var idx = line.IndexOf("=", 0, StringComparison.InvariantCulture);
                if (idx == -1) {
                    currentSection.Data.Add (new Token { Name = line.Substring(0, idx).Trim(), Data = "" });
                } else {
                    currentSection.Data.Add (new Token { Name = line.Substring(0, idx).Trim(), Data = line.Substring(idx + 1).Trim()});
                }
            }

            if (currentSection.Name == RootSectionName && currentSection.Data.Count() > 0) {
                result.Add(currentSection);
            }

            return result;

        }

        public static List<Section> ReadFile (string file)
        {
            var txt = File.ReadAllText(file, Encoding.UTF8);
            return ReadString (txt);
        }

        public static int ReadHealthPercent(string text) {
            var pos = text.IndexOf ('%');
            if (pos <= 0)
            {
                return int.Parse (text);
            }

            return int.Parse (text.Substring (0, pos));
        }
    }
}


text:
import hashlib
import json
import re
from enum import Enum
from os import listdir, makedirs
from os.path import dirname, isfile, join, realpath

import jsonschema
import yaml
from jinja2 import Environment, PackageLoader
from yaml import MarkedYAMLError

from binary import FixedEntryListTypes, FixedLengthTypes, FixedListTypes, FixedMapTypes
from cpp import cpp_ignore_service_list, cpp_types_decode, cpp_types_encode, get_size, is_trivial
from cs import cs_escape_keyword, cs_ignore_service_list, cs_types_decode, cs_types_encode
from java import java_types_decode, java_types_encode
from md import internal_services
from py import (
    py_escape_keyword,
    py_get_import_path_holders,
    py_ignore_service_list,
    py_param_name,
    py_types_encode_decode,
)
from ts import (
    ts_escape_keyword,
    ts_get_import_path_holders,
    ts_ignore_service_list,
    ts_types_decode,
    ts_types_encode,
)

MAJOR_VERSION_MULTIPLIER = 10000
MINOR_VERSION_MULTIPLIER = 100
PATCH_VERSION_MULTIPLIER = 1

def java_name(type_name):
    return "".join([capital(part) for part in type_name.split("_")])

def cs_name(type_name):
    return "".join(
        [capital(part) for part in type_name.replace("(", "").replace(")", "").split("_")]
    )

def cpp_name(type_name):
    return "".join(
        [capital(part) for part in type_name.replace("(", "").replace(")", "").split("_")]
    )

def param_name(type_name):
    return type_name[0].lower() + type_name[1:]

def is_fixed_type(param):
    return param["type"] in FixedLengthTypes

def capital(txt):
    return txt[0].capitalize() + txt[1:]

def to_upper_snake_case(camel_case_str):
    return re.sub("((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", r"_\1", camel_case_str).upper()
    # s1 = re.sub('(.)([A-Z]+[a-z]+)', r'\1_\2', camel_case_str)
    # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).upper()

def version_to_number(major, minor, patch=0):
    return (
        MAJOR_VERSION_MULTIPLIER * major
        + MINOR_VERSION_MULTIPLIER * minor
        + PATCH_VERSION_MULTIPLIER * patch
    )

def get_version_as_number(version):
    if not isinstance(version, str):
        version = str(version)
    return version_to_number(*map(int, version.split(".")))

def fixed_params(params):
    return [p for p in params if is_fixed_type(p)]

def var_size_params(params):
    return [p for p in params if not is_fixed_type(p)]

def new_params(since, params):
    """
    Returns the list of parameters that are added later than given version.
    Because the method should precede all the parameters that are added
    latter, a simple equality check between the versions that the method and
    the parameter is added is enough.
    """
    return [p for p in params if p["since"] != since]

def filter_new_params(params, version):
    """
    Returns the filtered list of parameters such that,
    the resulting list contains only the ones that are added
    before or at the same time with the given version.
    """
    version_as_number = get_version_as_number(version)
    return [p for p in params if version_as_number >= get_version_as_number(p["since"])]

def generate_codecs(services, template, output_dir, lang, env):
    makedirs(output_dir, exist_ok=True)
    id_fmt = "0x%02x%02x%02x"
    if lang is SupportedLanguages.CPP:
        curr_dir = dirname(realpath(__file__))
        cpp_dir = "%s/cpp" % curr_dir
        f = open(join(cpp_dir, "header_includes.txt"), "r")
        save_file(join(output_dir, "codecs.h"), f.read(), "w")
        f = open(join(cpp_dir, "source_header.txt"), "r")
        save_file(join(output_dir, "codecs.cpp"), f.read(), "w")

    for service in services:
        if service["name"] in language_service_ignore_list[lang]:
            print("[%s] is in ignore list so ignoring it." % service["name"])
            continue
        if "methods" in service:
            methods = service["methods"]
            if methods is None:
                raise NotImplementedError("Methods not found for service " + service)

        for method in service["methods"]:
            if (service["name"] + "." + method["name"]) in language_service_ignore_list[lang]:
                print(
                    "[%s] is in ignore list so ignoring it."
                    % (service["name"] + "." + method["name"])
                )
                continue

            method["request"]["id"] = int(id_fmt % (service["id"], method["id"], 0), 16)
            method["response"]["id"] = int(id_fmt % (service["id"], method["id"], 1), 16)
            events = method.get("events", None)
            if events is not None:
                for i in range(len(events)):
                    method["events"][i]["id"] = int(
                        id_fmt % (service["id"], method["id"], i + 2), 16
                    )

            codec_file_name = file_name_generators[lang](service["name"], method["name"])
            try:
                if lang is SupportedLanguages.CPP:
                    codec_template = env.get_template("codec-template.h.j2")
                    content = codec_template.render(service_name=service["name"], method=method)
                    save_file(join(output_dir, "codecs.h"), content, "a+")

                    codec_template = env.get_template("codec-template.cpp.j2")
                    content = codec_template.render(service_name=service["name"], method=method)
                    save_file(join(output_dir, "codecs.cpp"), content, "a+")
                else:
                    content = template.render(service_name=service["name"], method=method)
                    save_file(join(output_dir, codec_file_name), content)
            except NotImplementedError:
                print("[%s] contains missing type mapping so ignoring it." % codec_file_name)

    if lang is SupportedLanguages.CPP:
        f = open(join(cpp_dir, "footer.txt"), "r")
        content = f.read()
        save_file(join(output_dir, "codecs.h"), content, "a+")
        save_file(join(output_dir, "codecs.cpp"), content, "a+")

def generate_custom_codecs(services, template, output_dir, lang, env):
    makedirs(output_dir, exist_ok=True)
    if lang == SupportedLanguages.CPP:
        cpp_header_template = env.get_template("custom-codec-template.h.j2")
        cpp_source_template = env.get_template("custom-codec-template.cpp.j2")
    for service in services:
        if "customTypes" in service:
            custom_types = service["customTypes"]
            for codec in custom_types:
                try:
                    if lang == SupportedLanguages.CPP:
                        file_name_prefix = codec["name"].lower() + "_codec"
                        header_file_name = file_name_prefix + ".h"
                        source_file_name = file_name_prefix + ".cpp"
                        codec_file_name = header_file_name
                        content = cpp_header_template.render(codec=codec)
                        save_file(join(output_dir, header_file_name), content)
                        codec_file_name = source_file_name
                        content = cpp_source_template.render(codec=codec)
                        save_file(join(output_dir, source_file_name), content)
                    else:
                        codec_file_name = file_name_generators[lang](codec["name"])
                        content = template.render(codec=codec)
                        save_file(join(output_dir, codec_file_name), content)
                except NotImplementedError:
                    print("[%s] contains missing type mapping so ignoring it." % codec_file_name)

def generate_documentation(services, custom_definitions, template, output_dir):
    makedirs(output_dir, exist_ok=True)
    content = template.render(
        services=list(filter(lambda s: s["name"] not in internal_services, services)),
        custom_definitions=custom_definitions,
    )
    file_name = join(output_dir, "documentation.md")
    with open(file_name, "w", newline="\n") as file:
        file.writelines(content)

def item_type(lang_name, param_type):
    if param_type.startswith("List_") or param_type.startswith("ListCN_"):
        return lang_name(param_type.split("_", 1)[1])

def key_type(lang_name, param_type):
    return lang_name(param_type.split("_", 2)[1])

def value_type(lang_name, param_type):
    return lang_name(param_type.split("_", 2)[2])

def is_var_sized_list(param_type):
    return param_type.startswith("List_") and param_type not in FixedListTypes

def is_var_sized_list_contains_nullable(param_type):
    return param_type.startswith("ListCN_") and param_type not in FixedListTypes

def is_var_sized_map(param_type):
    return param_type.startswith("Map_") and param_type not in FixedMapTypes

def is_var_sized_entry_list(param_type):
    return param_type.startswith("EntryList_") and param_type not in FixedEntryListTypes

def load_services(protocol_def_dir):
    service_list = listdir(protocol_def_dir)
    services = []
    for service_file in service_list:
        file_path = join(protocol_def_dir, service_file)
        if isfile(file_path):
            with open(file_path, "r") as file:
                try:
                    data = yaml.load(file, Loader=yaml.Loader)
                except MarkedYAMLError as err:
                    print(err)
                    exit(-1)
                services.append(data)
    return services

def validate_services(services, schema_path, no_id_check, protocol_versions):
    valid = True
    with open(schema_path, "r") as schema_file:
        schema = json.load(schema_file)
        for i in range(len(services)):
            service = services[i]
            if not validate_against_schema(service, schema):
                return False

            if not no_id_check:
                # Validate id ordering of services.
                service_id = service["id"]
                if i != service_id:
                    print(
                        "Check the service id of the %s. Expected: %s, found: %s."
                        % (service["name"], i, service_id)
                    )
                    valid = False
                # Validate id ordering of definition methods.
                methods = service["methods"]
                for j in range(len(methods)):
                    method = methods[j]
                    method_id = method["id"]
                    if (j + 1) != method_id:
                        print(
                            "Check the method id of %s#%s. Expected: %s, found: %s"
                            % (service["name"], method["name"], (j + 1), method_id)
                        )
                        valid = False
                    request_params = method["request"].get("params", [])
                    method_name = service["name"] + "#" + method["name"]
                    if not is_parameters_ordered_and_semantically_correct(
                        method["since"], method_name + "#request", request_params, protocol_versions
                    ):
                        valid = False
                    response_params = method["response"].get("params", [])
                    if not is_parameters_ordered_and_semantically_correct(
                        method["since"],
                        method_name + "#response",
                        response_params,
                        protocol_versions,
                    ):
                        valid = False
                    events = method.get("events", [])
                    for event in events:
                        event_params = event.get("params", [])
                        if not is_parameters_ordered_and_semantically_correct(
                            event["since"],
                            method_name + "#" + event["name"] + "#event",
                            event_params,
                            protocol_versions,
                        ):
                            valid = False
    return valid

def is_semantically_correct_param(version, protocol_versions):
    is_semantically_correct = True
    if version != protocol_versions[0]:
        # Not 2.0
        if version % MINOR_VERSION_MULTIPLIER == 0:
            # Minor version
            if (version - MINOR_VERSION_MULTIPLIER) not in protocol_versions:
                # since is set to 2.x but 2.(x-1) is not in the protocol definitions
                is_semantically_correct = False
        elif version % PATCH_VERSION_MULTIPLIER == 0:
            # Patch version
            if (version - PATCH_VERSION_MULTIPLIER) not in protocol_versions:
                # since is set to 2.x.y but 2.x.(y-1) is not in the protocol definitions
                is_semantically_correct = False
    return is_semantically_correct

def is_parameters_ordered_and_semantically_correct(since, name, params, protocol_versions):
    is_ordered = True
    is_semantically_correct = True
    version = get_version_as_number(since)

    if not is_semantically_correct_param(version, protocol_versions):
        method_or_event_name = name[: name.rindex("#")]
        print(
            'Check the since value of the "%s"\n'
            'It is set to version "%s" but this protocol version does '
            "not semantically follow other protocol versions!" % (method_or_event_name, since)
        )
        is_semantically_correct = False

    for param in params:
        param_version = get_version_as_number(param["since"])
        if not is_semantically_correct_param(param_version, protocol_versions):
            print(
                'Check the since value of "%s" field of the "%s".\n'
                'It is set version "%s" but this protocol version does '
                "not semantically follow other protocol versions!"
                % (param["name"], name, param["since"])
            )
            is_semantically_correct = False

        if version > param_version:
            print(
                'Check the since value of "%s" field of the "%s".\n'
                "Parameters should be in the increasing order of since values!"
                % (param["name"], name)
            )
            is_ordered = False

        version = param_version
    return is_ordered and is_semantically_correct

def validate_custom_protocol_definitions(definition, schema_path, protocol_versions):
    valid = True
    with open(schema_path, "r") as schema_file:
        schema = json.load(schema_file)
    custom_types = definition[0]
    if not validate_against_schema(custom_types, schema):
        return False
    for custom_type in custom_types["customTypes"]:
        params = custom_type.get("params", [])
        if not is_parameters_ordered_and_semantically_correct(
            custom_type["since"], "CustomTypes#" + custom_type["name"], params, protocol_versions
        ):
            valid = False
    return valid

def validate_against_schema(service, schema):
    try:
        jsonschema.validate(service, schema)
    except jsonschema.ValidationError as e:
        print("Validation error on %s: %s" % (service.get("name", None), e))
        return False
    return True

def save_file(file, content, mode="w"):
    m = hashlib.md5()
    m.update(content.encode("utf-8"))
    codec_hash = m.hexdigest()
    with open(file, mode, newline="\n") as file:
        file.writelines(content.replace("!codec_hash!", codec_hash))

def get_protocol_versions(protocol_defs, custom_codec_defs):
    protocol_versions = set()
    if not custom_codec_defs:
        custom_codec_defs = []
    else:
        custom_codec_defs = custom_codec_defs[0]["customTypes"]

    for service in protocol_defs:
        for method in service["methods"]:
            protocol_versions.add(method["since"])
            for req_param in method["request"].get("params", []):
                protocol_versions.add(req_param["since"])
            for res_param in method["response"].get("params", []):
                protocol_versions.add(res_param["since"])
            for event in method.get("events", []):
                protocol_versions.add(event["since"])
                for event_param in event.get("params", []):
                    protocol_versions.add(event_param["since"])

    for custom_codec in custom_codec_defs:
        protocol_versions.add(custom_codec["since"])
        for param in custom_codec.get("params", []):
            protocol_versions.add(param["since"])

    return map(str, protocol_versions)

class SupportedLanguages(Enum):
    JAVA = "java"
    CPP = "cpp"
    CS = "cs"
    PY = "py"
    TS = "ts"
    # GO = 'go'
    MD = "md"

codec_output_directories = {
    SupportedLanguages.JAVA: "hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/",
    SupportedLanguages.CPP: "hazelcast/generated-sources/src/hazelcast/client/protocol/codec/",
    SupportedLanguages.CS: "src/Hazelcast.Net/Protocol/Codecs/",
    SupportedLanguages.PY: "hazelcast/protocol/codec/",
    SupportedLanguages.TS: "src/codec/",
    # SupportedLanguages.GO: 'internal/proto/'
    SupportedLanguages.MD: "documentation",
}

custom_codec_output_directories = {
    SupportedLanguages.JAVA: "hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/custom/",
    SupportedLanguages.CPP: "hazelcast/generated-sources/src/hazelcast/client/protocol/codec/",
    SupportedLanguages.CS: "src/Hazelcast.Net/Protocol/CustomCodecs/",
    SupportedLanguages.PY: "hazelcast/protocol/codec/custom/",
    SupportedLanguages.TS: "src/codec/custom",
    # SupportedLanguages.GO: 'internal/proto/'
}

def _capitalized_name_generator(extension):
    def inner(*names):
        return "%sCodec.%s" % ("".join(map(capital, names)), extension)

    return inner

def _snake_cased_name_generator(extension):
    def inner(*names):
        return "%s_codec.%s" % ("_".join(map(py_param_name, names)), extension)

    return inner

file_name_generators = {
    SupportedLanguages.JAVA: _capitalized_name_generator("java"),
    SupportedLanguages.CPP: _snake_cased_name_generator("cpp"),
    SupportedLanguages.CS: _capitalized_name_generator("cs"),
    SupportedLanguages.PY: _snake_cased_name_generator("py"),
    SupportedLanguages.TS: _capitalized_name_generator("ts"),
    # SupportedLanguages.GO: 'go'
    SupportedLanguages.MD: "md",
}

language_specific_funcs = {
    "lang_types_encode": {
        SupportedLanguages.JAVA: java_types_encode,
        SupportedLanguages.CS: cs_types_encode,
        SupportedLanguages.CPP: cpp_types_encode,
        SupportedLanguages.TS: ts_types_encode,
        SupportedLanguages.PY: py_types_encode_decode,
        SupportedLanguages.MD: lambda x: x,
    },
    "lang_types_decode": {
        SupportedLanguages.JAVA: java_types_decode,
        SupportedLanguages.CS: cs_types_decode,
        SupportedLanguages.CPP: cpp_types_decode,
        SupportedLanguages.TS: ts_types_decode,
        SupportedLanguages.PY: py_types_encode_decode,
        SupportedLanguages.MD: lambda x: x,
    },
    "lang_name": {
        SupportedLanguages.JAVA: java_name,
        SupportedLanguages.CS: cs_name,
        SupportedLanguages.CPP: cpp_name,
        SupportedLanguages.TS: java_name,
        SupportedLanguages.PY: java_name,
        SupportedLanguages.MD: lambda x: x,
    },
    "param_name": {
        SupportedLanguages.JAVA: param_name,
        SupportedLanguages.CS: param_name,
        SupportedLanguages.CPP: param_name,
        SupportedLanguages.TS: param_name,
        SupportedLanguages.PY: py_param_name,
        SupportedLanguages.MD: lambda x: x,
    },
    "escape_keyword": {
        SupportedLanguages.JAVA: lambda x: x,
        SupportedLanguages.CS: cs_escape_keyword,
        SupportedLanguages.CPP: lambda x: x,
        SupportedLanguages.TS: ts_escape_keyword,
        SupportedLanguages.PY: py_escape_keyword,
        SupportedLanguages.MD: lambda x: x,
    },
    "get_import_path_holders": {
        SupportedLanguages.JAVA: lambda x: x,
        SupportedLanguages.CS: lambda x: x,
        SupportedLanguages.CPP: lambda x: x,
        SupportedLanguages.TS: ts_get_import_path_holders,
        SupportedLanguages.PY: py_get_import_path_holders,
        SupportedLanguages.MD: lambda x: x,
    },
}

language_service_ignore_list = {
    SupportedLanguages.JAVA: set(),
    SupportedLanguages.CPP: cpp_ignore_service_list,
    SupportedLanguages.CS: cs_ignore_service_list,
    SupportedLanguages.PY: py_ignore_service_list,
    SupportedLanguages.TS: ts_ignore_service_list,
    # SupportedLanguages.GO: set()
}

def create_environment(lang, namespace):
    env = Environment(
        loader=PackageLoader(lang.value, "."),
        extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"],
    )
    env.trim_blocks = True
    env.lstrip_blocks = True
    env.keep_trailing_newline = False
    env.filters["capital"] = capital
    env.globals["to_upper_snake_case"] = to_upper_snake_case
    env.globals["fixed_params"] = fixed_params
    env.globals["var_size_params"] = var_size_params
    env.globals["new_params"] = new_params
    env.globals["filter_new_params"] = filter_new_params
    env.globals["is_var_sized_list"] = is_var_sized_list
    env.globals["is_var_sized_list_contains_nullable"] = is_var_sized_list_contains_nullable
    env.globals["is_var_sized_entry_list"] = is_var_sized_entry_list
    env.globals["is_var_sized_map"] = is_var_sized_map
    env.globals["item_type"] = item_type
    env.globals["key_type"] = key_type
    env.globals["value_type"] = value_type
    env.globals["namespace"] = namespace
    env.globals["lang_types_encode"] = language_specific_funcs["lang_types_encode"][lang]
    env.globals["lang_types_decode"] = language_specific_funcs["lang_types_decode"][lang]
    env.globals["lang_name"] = language_specific_funcs["lang_name"][lang]
    env.globals["param_name"] = language_specific_funcs["param_name"][lang]
    env.globals["escape_keyword"] = language_specific_funcs["escape_keyword"][lang]
    env.globals["get_size"] = get_size
    env.globals["is_trivial"] = is_trivial
    env.globals["get_import_path_holders"] = language_specific_funcs["get_import_path_holders"][
        lang
    ]

    return env


text:
#ifndef __itkGenericUtilities_h
#define __itkGenericUtilities_h

#include <utility>

/*
 *  This code was contributed in the Insight Journal paper:
 *  "A Streaming IO Base Class and Support for Streaming the MRC and VTK File Format"
 *  by Lowekamp B., Chen D.
 *  http://www.insight-journal.org/browse/publication/729
 *  http://hdl.handle.net/10380/3171
 *
 */

namespace itk
{
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// Generic Programming Algorithms
///////////////////////////////////////////////////

/// \brief returns the min and max of a sequence defined by two iterators
///
/// Uses the < operator to determin ordering
/// If first == last then return is pair(first,first);
/// otherwise is it pair(min, max)
template< class TInputIter >
std::pair< TInputIter, TInputIter > min_max_element(TInputIter first, TInputIter last)
{
  std::pair< TInputIter, TInputIter > result(first, first);

  if ( first == last )
    {
    return result;
    }

  while ( ++first != last )
    {
    TInputIter prev = first;
    if ( ++first == last )
      {
      if ( *prev < *( result.first ) )
        {
        result.first = prev;
        }
      if ( *( result.second ) < *prev )
        {
        result.second = prev;
        }
      break;
      }
    else if ( *first < *prev )
      {
      if ( *first < *( result.first ) )
        {
        result.first = first;
        }
      if ( *( result.second ) < *prev )
        {
        result.second = prev;
        }
      }
    else
      {
      if ( *prev < *( result.first ) )
        {
        result.first = prev;
        }
      if ( *( result.second ) < *first )
        {
        result.second = first;
        }
      }
    }
  return result;
}

/// \brief returns the min and max of a
///
/// Uses the provided binary functor
/// If first == last then return is pair(first,first);
/// otherwise is it pair(min, max)
template< class TInputIter, class TCompare >
std::pair< TInputIter, TInputIter > min_max_element(TInputIter first, TInputIter last, TCompare comp)
{
  std::pair< TInputIter, TInputIter > result(first, first);

  if ( first == last )
    {
    return result;
    }

  while ( ++first != last )
    {
    TInputIter prev = first;
    if ( ++first == last )
      {
      if ( comp( *prev, *( result.first ) ) )
        {
        result.first = prev;
        }
      if ( comp(*( result.second ), *prev) )
        {
        result.second = prev;
        }
      break;
      }
    else if ( comp(*first, *prev) )
      {
      if ( comp( *first, *( result.first ) ) )
        {
        result.first = first;
        }
      if ( comp(*( result.second ), *prev) )
        {
        result.second = prev;
        }
      }
    else
      {
      if ( comp( *prev, *( result.first ) ) )
        {
        result.first = prev;
        }
      if ( comp(*( result.second ), *first) )
        {
        result.second = first;
        }
      }
    }
  return result;
}
} // end itk namespace

#endif //__itkGenericUtilities_h


text:
package io.github.takzhanov.umbrella.hw09.domain;

import javax.persistence.*;

@MappedSuperclass
public abstract class DataSet {
    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    public long getId() {
        return id;
    }

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


text:
""" @Imports """
from django.test.testcases import TestCase
from cuescience_cart.tests.support.support import TestSupport

class TestCheckoutWizardWithBillingAddress(TestCase):
    def setUp(self):
        self.test_support = TestSupport(self)

    def test(self):
        """
         The code in this method is generated from: /cuescience-shop/shop/tests/views/checkout_wizard/test_checkout_wizard_with_billing_address.natspec
         Never change this method or any contents of this file, all local changes will we overwritten.
        """


text:
Maak de werkomgeving die u aanstaat

Uw bureaubladachtergrond kunt u makkelijk aanpassen en we bieden u een
selectie van prachtige achtergronden. Kies een van de vijf winnaars van onze
gemeenschapswedstrijd voor achtergronden - speciaal voor u uitgezocht!

Kleur overeenkomstig uw smaak! Met het nieuw vervaardigde gereedschap voor
thema-instellingen kunt u eenvoudig het uiterlijk van enkele kernaspecten
van de werkomgeving bijstellen.

 »  »  Instellingen van uw werkomgeving

 »  »  Thema-instelling


text:
package com.tomgibara.bits;

import com.tomgibara.streams.Streams;

public class StreamBitReaderTest extends AbstractBitReaderTest {

	@Override
	BitReader readerFor(BitStore vector) {
		vector = vector.mutableCopy();
		vector.permute().reverse();
		return new StreamBitReader(Streams.bytes(vector.toByteArray()).readStream());
	}

}


text:
class Page < ActiveRecord::Base
  attr_accessible :name
  has_many :items
end


text:
#!/usr/bin/python3

"""A script to check if all server metrics have documentation snippets."""

import os
import re
import sys
from pathlib import Path
from itertools import chain

from yaml import load, dump, YAMLError
try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml import Loader

# Usage:

def print_usage():
    """Print usage."""
    print("""Usage: utils/generateAllMetricsDocumentation.py [-h] [--help] [-d]

    -d:    if this option is given, a combined file with all metrics
           documentation snippets is written to
              Documentation/Metrics/allMetrics.yaml
           otherwise, this script only checks the format of all snippets and
           that there is one exactly one metrics declarations for each snippet.

    use -h or --help for this help.
""")

if len(sys.argv) > 1 and (sys.argv[1] == "-h" or sys.argv[1] == "--help"):
    print_usage()
    sys.exit(0)

# Some data:
CATEGORYNAMES = ["Health", "AQL", "Transactions", "Foxx", "Pregel",
                 "Statistics", "Replication", "Disk", "Errors",
                 "RocksDB", "Hotbackup", "k8s", "Connectivity", "Network",
                 "V8", "Agency", "Scheduler", "Maintenance", "kubearangodb",
                 "License"]

NODE_TYPES = ["coordinator", "dbserver", "agent", "single"]

# Check that we are in the right place:
LS_HERE = os.listdir(".")
if not("arangod" in LS_HERE and "arangosh" in LS_HERE and
       "Documentation" in LS_HERE and "CMakeLists.txt" in LS_HERE):
    print("Please execute me in the main source dir!")
    sys.exit(1)

# List files in Documentation/Metrics:
YAMLFILES = os.listdir("Documentation/Metrics")
YAMLFILES.sort()
if "allMetrics.yaml" in YAMLFILES:
    YAMLFILES.remove("allMetrics.yaml")
if "template.yaml" in YAMLFILES:
    YAMLFILES.remove("template.yaml")

# Read list of metrics from source:
METRICSLIST = []
LINEMATCHCOUNTER = re.compile(r"^\s*DECLARE_COUNTER\s*\(\s*([a-z_A-Z0-9]+)\s*,")
LINEMATCHGAUGE = re.compile(r"^\s*DECLARE_GAUGE\s*\(\s*([a-z_A-Z0-9]+)\s*,")
LINEMATCHHISTOGRAM = re.compile(r"^\s*DECLARE_HISTOGRAM\s*\(\s*([a-z_A-Z0-9]+)\s*,")
HEADERCOUNTER = re.compile(r"^\s*DECLARE_COUNTER\s*\(")
HEADERGAUGE = re.compile(r"^\s*DECLARE_GAUGE\s*\(")
HEADERHISTOGRAM = re.compile(r"^\s*DECLARE_HISTOGRAM\s*\(")
NAMEMATCH = re.compile(r"^\s*([a-z_A-Z0-9]+)\s*,")

files = chain(*[ Path(rootdir).glob(pattern)
            for rootdir in ["arangod", "lib", "enterprise"]
            for pattern in ["**/*.cpp", "**/*.h"] ])

for f in files:
    continuation = False
    with open(f, encoding="utf-8") as s:
        while True:
            l = s.readline()
            if not continuation:
                if l == "":
                    break
                m = LINEMATCHCOUNTER.search(l)
                if m:
                    METRICSLIST.append(m.group(1))
                    continue
                m = LINEMATCHGAUGE.search(l)
                if m:
                    METRICSLIST.append(m.group(1))
                    continue
                m = LINEMATCHHISTOGRAM.search(l)
                if m:
                    METRICSLIST.append(m.group(1))
                    continue
                m = HEADERCOUNTER.search(l)
                if m:
                    continuation = True
                m = HEADERGAUGE.search(l)
                if m:
                    continuation = True
                m = HEADERHISTOGRAM.search(l)
                if m:
                    continuation = True
            else:
                continuation = False
                m = NAMEMATCH.search(l)
                if m:
                    METRICSLIST.append(m.group(1))
if len(METRICSLIST) == 0:
    print("Did not find any metrics in arangod/RestServer/MetricsFeature.h!")
    sys.exit(2)

METRICSLIST.sort()

# Check that every listed metric has a .yaml documentation file:
MISSING = False
YAMLS = []
for i, metric in enumerate(METRICSLIST):
    bad = False
    if not metric + ".yaml" in YAMLFILES:
        print(f"Missing metric documentation for metric '{metric}'")
        bad = True
    else:
        # Check yaml:
        filename = os.path.join("Documentation", "Metrics", metric) + ".yaml"
        try:
            s = open(filename, encoding="utf-8")
        except FileNotFoundError:
            print(f"Could not open file '{filename}'")
            bad = True
        if not bad:
            try:
                y = load(s, Loader=Loader)
            except YAMLError as err:
                print(f"Could not parse YAML file '{filename}', error:\n{err}")
                bad = True
            finally:
                s.close()

        if not bad:
            YAMLS.append(y)   # for later dump

            # Check a few things in the yaml:
            for attr in ["name", "help", "exposedBy", "description", "unit",
                         "type", "category", "complexity", "introducedIn"]:
                if not attr in y:
                    print(f"YAML file '{filename}' does not have required attribute '{attr}'")
                    bad = True
            if not bad:
                for attr in ["name", "help", "description", "unit",
                             "type", "category", "complexity", "introducedIn"]:
                    if not isinstance(y[attr], str):
                        print(f"YAML file '{filename}' has an attribute "
                              f"'{attr}' whose value must be a string but isn't.")
                        bad = True
                if y["help"].strip()[-1] != ".":
                    print(f"YAML file '{filename}' has a 'help' attribute that "
                          f"does not end with a period.")
                    bad = True
                if not isinstance(y["exposedBy"], list):
                    print(f"YAML file '{filename}' has an attribute 'exposedBy' "
                          f"whose value must be a list but isn't.")
                    bad = True
                else:
                    for e in y["exposedBy"]:
                        if e not in NODE_TYPES:
                            print(f"YAML file '{filename}' has an attribute 'exposedBy' "
                                  f"that lists an invalid value '{e}'.")
                            bad = True
                if not bad:
                    if not y["category"] in CATEGORYNAMES:
                        print(f"YAML file '{filename}' has an unknown category "
                              f"'{y['category']}', please fix.")
                        bad = True
                    if not bad:
                        if y["name"] != metric:
                            print(f"YAML file '{filename}' has an attribute name '" + y["name"] + "' which does not match the file name.")
                            bad = True

    if bad:
        MISSING = True

TOOMANY = False
for i, yamlfile in enumerate(YAMLFILES):
    name = yamlfile[:-5]
    if not name in METRICSLIST:
        TOOMANY = True
        print(f"YAML file '{name}.yaml'\n"
              f"does not have a corresponding metric declared in the source code!")

DUMPMETRICS = False
if len(sys.argv) > 1 and sys.argv[1] == "-d":
    DUMPMETRICS = True

OUTFILE = "Documentation/Metrics/allMetrics.yaml"
if DUMPMETRICS:
    # Dump what we have:
    with open(OUTFILE, "w", encoding="utf-8") as S:
        for i, yamlfile in enumerate(YAMLFILES):
            with open(os.path.join("Documentation", "Metrics", yamlfile), encoding="utf-8") as I:
                prefix = "- "
                while True:
                    l = I.readline()
                    if l == "":
                        break
                    S.write(prefix)
                    prefix = "  "
                    S.write(l)
                S.write("\n")

if MISSING:
    sys.exit(17)

if TOOMANY:
    sys.exit(18)


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

namespace PublishR.Models
{
    public class Section
    {
        [JsonProperty("template")]
        public string Template { get; set; }

        [JsonProperty("blocks")]
        public IDictionary<string, Block> Blocks { get; set; }

        [JsonProperty("schedules")]
        public IList<Schedule> Schedules { get; set; }

        [JsonProperty("properties")]
        public IDictionary<string, object> Properties { get; set; }
    }
}


text:
Implementation of OSGI User Admin Service.
Provides support for a pluggable persistence provider.


text:
IF OBJECT_ID('config.filter_name_view') IS NOT NULL
DROP VIEW config.filter_name_view;
GO
CREATE VIEW config.filter_name_view
AS
SELECT
    DISTINCT
    object_name,
    filter_name,
    is_default
FROM config.filters
WHERE config.filters.deleted = 0;

GO


text:
package loon.utils;

/**
 * 存储单独value的线性数据集合,内部数据无序排列,不允许重复
 *
 * @param <E>
 */
public class ObjectSet<E> implements Iterable<E>, IArray {

	private ObjectMap<E, Object> _map;

	public ObjectSet() {
		_map = new ObjectMap<E, Object>(false);
	}

	public ObjectSet(ObjectSet<? extends E> c) {
		_map = new ObjectMap<E, Object>(false);
		addAll(c);
	}

	public ObjectSet(int initialCapacity, float loadFactor) {
		_map = new ObjectMap<E, Object>(initialCapacity, loadFactor, false);
	}

	public ObjectSet(int initialCapacity) {
		_map = new ObjectMap<E, Object>(initialCapacity, false);
	}

	ObjectSet(int initialCapacity, float loadFactor, boolean dummy) {
		_map = new OrderedMap<E, Object>(initialCapacity, loadFactor, false, false);
	}

	public void addAll(ObjectSet<? extends E> c){
		for (E key : c) {
			add(key);
		}
	}

	@Override
	public LIterator<E> iterator() {
		return _map.keys();
	}

	@Override
	public int size() {
		return _map.size();
	}

	@Override
	public boolean isEmpty() {
		return _map.isEmpty();
	}

	public boolean contains(Object o) {
		return _map.containsKey(o);
	}

	public boolean add(E e) {
		return _map.put(e, null) == null;
	}

	public boolean remove(Object o) {
		return _map.remove(o) == ObjectMap.FINAL_VALUE;
	}

	@Override
	public int hashCode() {
		if (_map == null) {
			return super.hashCode();
		}
		int hashCode = 1;
		for (LIterator<E> it = _map.keys(); it.hasNext();) {
			E e = it.next();
			hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
		}
		return hashCode;
	}

	@Override
	public void clear() {
		_map.clear();
	}

	@Override
    public String toString() {
		LIterator<E> it = iterator();
        if (! it.hasNext()) {
            return "[]";
        }
        StrBuilder sbr = new StrBuilder();
        sbr.append('[');
        for (it = _map.keys(); it.hasNext();) {
            E e = it.next();
            sbr.append(e == this ? "(this ObjectSet)" : e);
            if (! it.hasNext()) {
                return sbr.append(']').toString();
            }
            sbr.append(',').append(' ');
        }
        return sbr.toString();
    }

}


text:
package asyncpi

import (
	"go.nickng.io/asyncpi/internal/errors"
	"go.nickng.io/asyncpi/internal/name"
)

func errSubst(err error) error {
	return errors.Wrap(err, "substitution failed")
}

// Subst is the substitution of variables xs by names vs in Process p.
//
// The caller must ensure that the size of xs and vs are the same
// such that xs[i] is substituted by vs[i] in 0 <= i < len(xs).
func Subst(p Process, vs, xs []Name) error {
	if len(xs) != len(vs) {
		return errSubst(ErrInvalid)
	}
	procs := []Process{p}
	for len(procs) > 0 {
		p, procs = procs[0], procs[1:]
		switch p := p.(type) {
		case *NilProcess:
		case *Par:
			procs = append(procs, p.Procs...)
		case *Recv:
			for i, x := range xs {
				if IsSameName(p.Chan, x) {
					if ch, canSetName := p.Chan.(name.Setter); canSetName {
						ch.SetName(vs[i].Ident())
					}
				}
				for _, rv := range p.Vars {
					if IsSameName(rv, x) {
						if ch, canSetName := rv.(name.Setter); canSetName {
							ch.SetName(vs[i].Ident())
						}
					}
				}
			}
			procs = append(procs, p.Cont)
		case *Restrict:
			procs = append(procs, p.Proc)
		case *Repeat:
			procs = append(procs, p.Proc)
		case *Send:
			for i, x := range xs {
				if IsSameName(p.Chan, x) {
					if ch, canSetName := p.Chan.(name.Setter); canSetName {
						ch.SetName(vs[i].Ident())
					}
				}
			}
		default:
			return errSubst(UnknownProcessError{Proc: p})
		}
	}
	return nil
}

// Reduce1 performs a single step of reduction for Process p.
func Reduce1(p Process) (changed bool, err error) {
	changed, err = reduceOnce(p)
	return changed, errors.Wrap(err, "cannot reduce process")
}

// reduceOnce performs a single step of reduction.
//
// This reduction combines multiple congruence relations
// and attempts to perform an interaction.
func reduceOnce(p Process) (changed bool, err error) {
	switch p := p.(type) {
	case *NilProcess:
		return false, nil
	case *Par:
		var sends map[string]*Process // pointer because we will mutate them
		var recvs map[string]*Process // pointer because we will mutate them
		for i, proc := range p.Procs {
			switch proc := proc.(type) {
			case *Par:
				// nested Par.
				return reduceOnce(proc)
			case *Recv:
				if recvs == nil {
					recvs = make(map[string]*Process)
				}
				if IsFreeName(proc.Chan) {
					ch := proc.Chan.Ident()
					// Do not overwrite existing subprocess with same channel.
					// Substitution only consider leftmost available names.
					if _, exists := recvs[ch]; !exists {
						recvs[ch] = &p.Procs[i]
					}
				}
			case *Send:
				if sends == nil {
					sends = make(map[string]*Process)
				}
				if IsFreeName(proc.Chan) {
					ch := proc.Chan.Ident()
					// Do not overwrite existing subprocess with same channel.
					// Substitution only consider leftmost available names.
					if _, exists := sends[ch]; !exists {
						sends[ch] = &p.Procs[i]
					}
				}
			}
		}
		for ch, s := range sends {
			if r, hasSharedChan := recvs[ch]; hasSharedChan {
				recv := (*r).(*Recv)
				send := (*s).(*Send)
				if err := Subst(recv.Cont, send.Vals, recv.Vars); err != nil {
					return false, err
				}
				*s, *r = NewNilProcess(), recv.Cont
				return true, nil
			}
		}
		return false, nil
	case *Recv:
		return false, nil
	case *Restrict:
		return reduceOnce(p.Proc)
	case *Repeat:
		return reduceOnce(p.Proc)
	case *Send:
		return false, nil
	default:
		return false, UnknownProcessError{Proc: p}
	}
}

func errSimplify(err error) error {
	return errors.Wrap(err, "cannot simplify process")
}

// SimplifyBySC simplifies a Process p by structural congruence rules.
//
// It applies functions to (1) remove unnecessary Restrict,
// and (2) remove superfluous inact.
//
func SimplifyBySC(p Process) (Process, error) {
	unwanted, err := findUnusedRestrict(p)
	if err != nil {
		return nil, errSimplify(errors.Wrap(err, "cannot find unused restricts"))
	}
	p, err = filterRestrict(p, unwanted)
	if err != nil {
		return nil, errSimplify(errors.Wrap(err, "cannot filter unused restricts"))
	}
	p, err = filterNilProcess(p)
	if err != nil {
		return nil, errSimplify(errors.Wrap(err, "cannot filter nil processes"))
	}
	return p, nil
}

// findUnusedRestrict returns a slice of unused Names
// introduced by a Restrict in Process p.
//
// More accurately, this function returns all x in the form of:
//
//     (νx)P where x ∉ fn(P)
//
// Such that the unused Names and the Restrict that
// introduced them can be removed.
func findUnusedRestrict(p Process) (unused []Name, err error) {
	if err := Bind(&p); err != nil {
		return nil, err
	}
	type rescount struct {
		ResName Name
		Count   int
	}
	resUses := make(map[string]*rescount)
	procs := []Process{p}
	for len(procs) > 0 {
		p, procs = procs[0], procs[1:]
		switch p := p.(type) {
		case *NilProcess:
		case *Par:
			procs = append(procs, p.Procs...)
		case *Recv:
			if rc, exists := resUses[p.Chan.Ident()]; exists {
				rc.Count++
			}
			for _, v := range p.Vars {
				if rc, exists := resUses[v.Ident()]; exists {
					rc.Count++
				}
			}
			procs = append(procs, p.Cont)
		case *Repeat:
			procs = append(procs, p.Proc)
		case *Restrict:
			resUses[p.Name.Ident()] = &rescount{ResName: p.Name, Count: 1}
			procs = append(procs, p.Proc)
		case *Send:
			if rc, exists := resUses[p.Chan.Ident()]; exists {
				rc.Count++
			}
			for _, v := range p.Vals {
				if rc, exists := resUses[v.Ident()]; exists {
					rc.Count++

				}
			}
		default:
			return nil, UnknownProcessError{Proc: p}
		}
	}
	for _, rc := range resUses {
		if rc.Count == 1 {
			unused = append(unused, rc.ResName)
		}
	}
	return unused, nil
}

// filterRestrict returns a Process where all unwanted Names
// introduced by Restrict are removed from the input Process p.
//
// More accurately, this function returns P given a slice of x:
//
//     (νx)P where x ∉ fn(P)
//
// See also findUnusedRestrict(Process) function for creating the
// unwanted Name slice.
func filterRestrict(p Process, unwanted []Name) (Process, error) {
	switch p := p.(type) {
	case *NilProcess:
		return p, nil
	case *Par:
		var procs []Process
		for _, proc := range p.Procs {
			res, err := filterRestrict(proc, unwanted)
			if err != nil {
				return nil, err
			}
			procs = append(procs, res)
		}
		p.Procs = procs
		return p, nil
	case *Recv:
		var err error
		p.Cont, err = filterRestrict(p.Cont, unwanted)
		if err != nil {
			return nil, err
		}
		return p, nil
	case *Repeat:
		var err error
		p.Proc, err = filterRestrict(p.Proc, unwanted)
		if err != nil {
			return nil, err
		}
		return p, nil
	case *Restrict:
		var err error
		p.Proc, err = filterRestrict(p.Proc, unwanted)
		if err != nil {
			return nil, err
		}
		for _, n := range unwanted {
			if n == p.Name { // note: pointer compare
				return p.Proc, nil
			}
		}
		return p, nil
	case *Send:
		return p, nil
	default:
		return nil, UnknownProcessError{Proc: p}
	}
}

// filterNilProcess returns a Process where superfluous NilProcess
// that does not end a Process are removed from the input Process p.
//
// More accurately, this function removes 0 or collapses Process involving 0:
//
//     (P|0) → P
//     !0 → 0
//
// NilProcess at the end of Processes are unchanged.
func filterNilProcess(p Process) (Process, error) {
	switch p := p.(type) {
	case *NilProcess:
		return p, nil
	case *Par:
		var procs []Process
		for _, proc := range p.Procs {
			proc, err := filterNilProcess(proc)
			if err != nil {
				return nil, err
			}
			if _, isEmpty := proc.(*NilProcess); !isEmpty {
				procs = append(procs, proc)
			}
		}
		switch len(procs) {
		case 0:
			return NewNilProcess(), nil
		case 1:
			return procs[0], nil
		default:
			p.Procs = procs
			return p, nil
		}
	case *Recv:
		var err error
		p.Cont, err = filterNilProcess(p.Cont)
		if err != nil {
			return nil, err
		}
		return p, nil
	case *Repeat:
		var err error
		p.Proc, err = filterNilProcess(p.Proc)
		if err != nil {
			return nil, err
		}
		if _, isEmpty := p.Proc.(*NilProcess); isEmpty {
			return p.Proc, nil
		}
		return p, nil
	case *Restrict:
		var err error
		p.Proc, err = filterNilProcess(p.Proc)
		if err != nil {
			return nil, err
		}
		if _, isEmpty := p.Proc.(*NilProcess); isEmpty {
			return p.Proc, nil
		}
		return p, nil
	case *Send:
		return p, nil
	default:
		return nil, UnknownProcessError{Proc: p}
	}
}


text:
package com.amazonaws.services.identitymanagement.model;

import java.io.Serializable;

/**
 *

 * Contains the response to a successful ListGroups request.
 *

 */
public class ListGroupsResult implements Serializable, Cloneable {

    /**
     * A list of groups.
     */
    private com.amazonaws.internal.ListWithAutoConstructFlag<Group> groups;

    /**
     * A flag that indicates whether there are more items to return. If your
     * results were truncated, you can make a subsequent pagination request
     * using the Marker request parameter to retrieve more
     * items.
     */
    private Boolean isTruncated;

    /**
     * When IsTruncated is true, this element is
     * present and contains the value to use for the Marker
     * parameter in a subsequent pagination request.
     *

     * Constraints:

     * Length: 1 - 320

     * Pattern: [\u0020-\u00FF]+

     */
    private String marker;

    /**
     * A list of groups.
     *
     * @return A list of groups.
     */
    public java.util.List<Group> getGroups() {
        if (groups == null) {
              groups = new com.amazonaws.internal.ListWithAutoConstructFlag<Group>();
              groups.setAutoConstruct(true);
        }
        return groups;
    }

    /**
     * A list of groups.
     *
     * @param groups A list of groups.
     */
    public void setGroups(java.util.Collection<Group> groups) {
        if (groups == null) {
            this.groups = null;
            return;
        }
        com.amazonaws.internal.ListWithAutoConstructFlag<Group> groupsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<Group>(groups.size());
        groupsCopy.addAll(groups);
        this.groups = groupsCopy;
    }

    /**
     * A list of groups.
     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setGroups(java.util.Collection)} or {@link
     * #withGroups(java.util.Collection)} if you want to override the
     * existing values.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param groups A list of groups.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ListGroupsResult withGroups(Group... groups) {
        if (getGroups() == null) setGroups(new java.util.ArrayList<Group>(groups.length));
        for (Group value : groups) {
            getGroups().add(value);
        }
        return this;
    }

    /**
     * A list of groups.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param groups A list of groups.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ListGroupsResult withGroups(java.util.Collection<Group> groups) {
        if (groups == null) {
            this.groups = null;
        } else {
            com.amazonaws.internal.ListWithAutoConstructFlag<Group> groupsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<Group>(groups.size());
            groupsCopy.addAll(groups);
            this.groups = groupsCopy;
        }

        return this;
    }

    /**
     * A flag that indicates whether there are more items to return. If your
     * results were truncated, you can make a subsequent pagination request
     * using the Marker request parameter to retrieve more
     * items.
     *
     * @return A flag that indicates whether there are more items to return. If your
     *         results were truncated, you can make a subsequent pagination request
     *         using the Marker request parameter to retrieve more
     *         items.
     */
    public Boolean isTruncated() {
        return isTruncated;
    }

    /**
     * A flag that indicates whether there are more items to return. If your
     * results were truncated, you can make a subsequent pagination request
     * using the Marker request parameter to retrieve more
     * items.
     *
     * @param isTruncated A flag that indicates whether there are more items to return. If your
     *         results were truncated, you can make a subsequent pagination request
     *         using the Marker request parameter to retrieve more
     *         items.
     */
    public void setIsTruncated(Boolean isTruncated) {
        this.isTruncated = isTruncated;
    }

    /**
     * A flag that indicates whether there are more items to return. If your
     * results were truncated, you can make a subsequent pagination request
     * using the Marker request parameter to retrieve more
     * items.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param isTruncated A flag that indicates whether there are more items to return. If your
     *         results were truncated, you can make a subsequent pagination request
     *         using the Marker request parameter to retrieve more
     *         items.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ListGroupsResult withIsTruncated(Boolean isTruncated) {
        this.isTruncated = isTruncated;
        return this;
    }

    /**
     * A flag that indicates whether there are more items to return. If your
     * results were truncated, you can make a subsequent pagination request
     * using the Marker request parameter to retrieve more
     * items.
     *
     * @return A flag that indicates whether there are more items to return. If your
     *         results were truncated, you can make a subsequent pagination request
     *         using the Marker request parameter to retrieve more
     *         items.
     */
    public Boolean getIsTruncated() {
        return isTruncated;
    }

    /**
     * When IsTruncated is true, this element is
     * present and contains the value to use for the Marker
     * parameter in a subsequent pagination request.
     *

     * Constraints:

     * Length: 1 - 320

     * Pattern: [\u0020-\u00FF]+

     *
     * @return When IsTruncated is true, this element is
     *         present and contains the value to use for the Marker
     *         parameter in a subsequent pagination request.
     */
    public String getMarker() {
        return marker;
    }

    /**
     * When IsTruncated is true, this element is
     * present and contains the value to use for the Marker
     * parameter in a subsequent pagination request.
     *

     * Constraints:

     * Length: 1 - 320

     * Pattern: [\u0020-\u00FF]+

     *
     * @param marker When IsTruncated is true, this element is
     *         present and contains the value to use for the Marker
     *         parameter in a subsequent pagination request.
     */
    public void setMarker(String marker) {
        this.marker = marker;
    }

    /**
     * When IsTruncated is true, this element is
     * present and contains the value to use for the Marker
     * parameter in a subsequent pagination request.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 1 - 320

     * Pattern: [\u0020-\u00FF]+

     *
     * @param marker When IsTruncated is true, this element is
     *         present and contains the value to use for the Marker
     *         parameter in a subsequent pagination request.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ListGroupsResult withMarker(String marker) {
        this.marker = marker;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getGroups() != null) sb.append("Groups: " + getGroups() + ",");
        if (isTruncated() != null) sb.append("IsTruncated: " + isTruncated() + ",");
        if (getMarker() != null) sb.append("Marker: " + getMarker() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getGroups() == null) ? 0 : getGroups().hashCode());
        hashCode = prime * hashCode + ((isTruncated() == null) ? 0 : isTruncated().hashCode());
        hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof ListGroupsResult == false) return false;
        ListGroupsResult other = (ListGroupsResult)obj;

        if (other.getGroups() == null ^ this.getGroups() == null) return false;
        if (other.getGroups() != null && other.getGroups().equals(this.getGroups()) == false) return false;
        if (other.isTruncated() == null ^ this.isTruncated() == null) return false;
        if (other.isTruncated() != null && other.isTruncated().equals(this.isTruncated()) == false) return false;
        if (other.getMarker() == null ^ this.getMarker() == null) return false;
        if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false) return false;
        return true;
    }

    @Override
    public ListGroupsResult clone() {
        try {
            return (ListGroupsResult) super.clone();

        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                    + "even though we're Cloneable!",
                    e);
        }

    }

}


text:
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { Search } from 'semantic-ui-react'

class AttackSearch extends Component {
  constructor(props){
    super(props)
    this.state = {}
  }

  static getDerivedStateFromProps(nextProps, prevState){
    return {
      results: nextProps.attacks.map((attack)=>{
        let { description, id, name } = attack
        return {
          title: name,
          description,
          key: id,
          attack
        }
      }),
      value: ''
    }
  }

  _searchChange = (e, {value}) => {
    let { attacks } = this.props
    let results = []
    if (value === ''){
      results = attacks.map((attack)=>{
        let { description, id, name } = attack
        return {
          title: name,
          description,
          key: id,
          attack
        }
      })
    }else{
      results = attacks.reduce((_results, attack) => {
        if(attack.name.includes(value)){
          let { description, id, name } = attack
          _results.push({
            title: name,
            description,
            key: id,
            attack
          })
        }
        return _results
      }, [])
    }
    this.setState({
      results,
      value
    })
  }

  _resultSelect = (e, { result }) => {
    this.props.showAttack(result.key)
    this.props.toggleActive(result.attack)
  }

  render(){
    let { results, value } = this.state
    return(
      <Search
        id="attack-search-bar"
        fluid
        minCharacters={0}
        onResultSelect={this._resultSelect}
        onSearchChange={this._searchChange}
        results={results}
        value={value}
        style={{display: 'inline-block'}}
      />
    )
  }
}

AttackSearch.propTypes = {
  attacks: PropTypes.array.isRequired,
  showAttack: PropTypes.func.isRequired,
  toggleActive: PropTypes.func.isRequired
}

export default AttackSearch


text:
namespace extensions {

// Writes |password| into Keychain with |service_name| and |account_name|.
OSStatus WriteKeychainItem(const std::string& service_name,
                           const std::string& account_name,
                           const std::string& password);

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_ENTERPRISE_REPORTING_PRIVATE_KEYCHAIN_DATA_HELPER_MAC_H_


text:
<?php

namespace jamesvweston\EasyPost\Exceptions;

class EasyPostInvalidStreet1Exception extends EasyPostApiException
{

    public function __construct($message = 'Invalid Recipient Street1', $code = 400, \Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
using Utils;

namespace VulnServer1.Controllers
{
	public struct TransactionResult
	{
		public string Status;
		public long ConfirmationNumber;
	}

	public class TransactionController : ApiController
	{
		public TransactionResult Get( string ticket )
		{
			if ( String.IsNullOrEmpty( ticket ) ) return new TransactionResult();
			var encryptionKeyString = "4f256766a4075027695bd48b444e1ac5c7c17385a1b4f1779e6385da24d97997";
			byte[] encryptionKey = QuickCrypto.StringToByteArray( encryptionKeyString );

			byte[] ticketBytes = QuickCrypto.StringToByteArray( ticket.Substring( 32 ) );
			byte[] ivBytes = QuickCrypto.StringToByteArray( ticket.Substring( 0, 32 ) );
			string decrypted;
			try
			{
				decrypted = QuickCrypto.DecryptStringFromBytes_Aes(
					ticketBytes, encryptionKey, ivBytes );
			}
			catch
			{
				return new TransactionResult() { Status = "Bad Token" };
			}

			long accountNumber = 0;
			string[] ticketParts = decrypted.Split( '|' );
			// some fake validation
			bool validAccount = Int64.TryParse( ticketParts[ 0 ], out accountNumber );
			if ( ticketParts.Length == 4 && validAccount )
			{
				return new TransactionResult() { Status = "OK", ConfirmationNumber = 123 };
			}
			return new TransactionResult() { Status = "Invalid Request" };
		}
	}
}


text:
set -o errexit
set -o nounset

function check_label() {
  local LABEL_LINE="$1"
  # Expected: dstat's YAML output in ${DSTAT_OUTPUT}, with a section like:
  #
  # labels:
  #  label1: value1
  #  label2: value2
  #
  # and $LABEL_LINE would be e.g. "label2: value2"
  if ! echo "${DSTAT_OUTPUT}" | grep 'labels:' -A2 | grep -q "${LABEL_LINE}"; then
    echo "Label ${LABEL_LINE} not found in the dstat output!"
    echo "${DSTAT_OUTPUT}"
    exit 1
  fi
}

# Test labels.
#
# This test launches a single job and then verifies that dstat
# reflects the labels that were specified in dsub.
readonly SCRIPT_DIR="$(dirname "${0}")"

# This test is not sensitive to the output of the dsub job.
# Set the ALLOW_DIRTY_TESTS environment variable to 1 in your shell to
# run this test without first emptying the output and logging directories.
source "${SCRIPT_DIR}/test_setup_e2e.sh"

# Set up for running the tests
mkdir -p "${TEST_TMP}"

# Create a simple TSV file
readonly TASKS_FILE="${TEST_TMP}/${TEST_NAME}.tsv"
util::write_tsv_file "${TASKS_FILE}" \
' --label song
  cheryl
  milestones
'

if [[ "${CHECK_RESULTS_ONLY:-0}" -eq 0 ]]; then

  echo "Launching pipeline..."

  JOBID="$(run_dsub \
    --label genre=jazz \
    --label subgenre=bebop \
    --command "echo 'hello world'; sleep 4m;")"

  echo "Checking dstat (full)..."

  if ! DSTAT_OUTPUT=$(run_dstat --status '*' --full --jobs "${JOBID}" 2>&1); then
    echo "dstat exited with a non-zero exit code!"
    echo "Output:"
    echo "${DSTAT_OUTPUT}"
    exit 1
  fi

  check_label 'genre: jazz'
  check_label 'subgenre: bebop'

  echo
  echo "Running ddel against a non-matching label - should not kill pipeline."
  run_ddel --jobs "${JOBID}" --label "genre=rock" --label "subgenre=bebop"

  echo
  echo "Check that the job is not canceled."
  if util::wait_for_canceled_status "${JOBID}"; then
    echo "ERROR: Operation is canceled, but ddel should not have canceled it."
    util::get_job_status "${JOBID}"
    exit 1
  fi

  echo
  echo "Killing the pipeline"
  run_ddel --jobs "${JOBID}" --label "genre=jazz" --label "subgenre=bebop"

  if ! util::wait_for_canceled_status "${JOBID}"; then
    echo "dstat does not show the operation as canceled after wait."
    util::get_job_status "${JOBID}"
    exit 1
  fi

  # As of this writing we cannot combine --labels from the command line
  # and task file, that's why we run two tests.

  echo "Launching pipeline..."

  JOBID="$(run_dsub \
    --tasks "${TASKS_FILE}" \
    --command "echo 'hello world'")"

  echo "Checking dstat (full)..."

  if ! DSTAT_OUTPUT=$(run_dstat --status '*' --full --jobs "${JOBID}" 2>&1); then
    echo "dstat exited with a non-zero exit code!"
    echo "Output:"
    echo "${DSTAT_OUTPUT}"
    exit 1
  fi

  check_label 'song: cheryl'
  check_label 'song: milestones'

  echo "SUCCESS"

fi


text:
using System.Linq;
using NUnit.Framework;

namespace Tests.LINQMethods
{
    [TestFixture]
    public class DefaultIfEmpty_Value : LINQQueryableInventoryMethodTestBase<IntegratedTestsBase.InventorySelect>
    {
        protected override IQueryable<InventorySelect> GetQuery(IQueryable<InventorySelect> source)
        {
            return source.DefaultIfEmpty(new InventorySelect());
        }
    }
}


text:
class QSpinBox;
class QCheckBox;

class StaffSettings : public QWidget
{
    Q_OBJECT
public:
    explicit StaffSettings(QWidget *parent = 0);

    int queueLength() const;
    bool showNoteNames() const;

signals:

public slots:

protected slots:
    void onQueueLengthChanged(int value);
    void onShowNoteNamesClicked(bool checked);

protected:
    QSpinBox *queueLengthSpinBox_ = nullptr;
    QCheckBox *showNoteNamesCheckBox_ = nullptr;
    int queueLength_ = 0;
    bool showNoteNames_ = false;
};

#endif // STAFFSETTINGS_H


text:
package edu.cmu.hcii.citrus.views;

import edu.cmu.hcii.citrus.*;

public class Image extends BootElement<Image> {

	public final java.awt.Image value;

	public Image(java.awt.Image image) {

		value = image;

	}

	public Namespace<?> getType() { return Reflection.getJavaType(Image.class); }

	public Real width() { return new Real(value.getWidth(null)); }
	public Real height() { return new Real(value.getHeight(null)); }

	public Image evaluate(Element<?> env) { return this; }

	public Element duplicate() { return new Image(value); }
	public Text toCitrus() { return new Text(value.toString()); }
	public String toString() { return value.toString(); }

	public Bool isEquivalentTo(Element<?> o) { return new Bool(this.equals(o)); }

}


text:
'use strict';
const fs = require('fs');
const lang = require('zero-lang');
const path = require('path');
const shelljs = require('shelljs');
const SVGO = require('svgo');
const svgo = new SVGO();

function getPadding(size, addPadding, PIXEL) {
  let padding = 0;

  if (addPadding && size) {
    const pad = parseInt(size / 14) * 14;
    padding = ((size - pad) / 2) * (PIXEL / 2);
  }

  return padding;
}

function getSvgStr(params, size, PIXEL, callback) {
  const padding = getPadding(size, params.addPadding);

  params = lang.extend({}, params, {
    shiftX: -(-(14 * PIXEL - params.advWidth) / 2 - padding),
    shiftY: -(-2 * PIXEL - padding),
    width: Math.round(14 * PIXEL + 2 * padding),
    height: Math.round(14 * PIXEL + 2 * padding)
  });

  const svgStr = `<svg viewBox="0 0 ${params.width} ${params.height}" xmlns="http://www.w3.org/2000/svg">
    <g transform="translate(${params.shiftX} ${params.shiftY})">
    <g transform="scale(1 -1) translate(0 -${10 * PIXEL})">
    <path d="${params.d}"/>
    </g></g>
    </svg>`
    .replace(/\n/g, '')
    .replace(/\s+/g, ' ')
    .replace(/>\s+</g, '><');
  svgo.optimize(svgStr, function (result) {
    callback(result.data);
  });
}

module.exports = (fonts, target, WIDTH) => {
  // generate separated svg icons
  shelljs.mkdir('-p', target);
  // cannot yield inside a callback function, so use for... instead of forEach
  lang.each(fonts, (icon) => {
    const svgFilePath = path.resolve(target, `./${icon.id}.svg`);
    const advWidth = icon['horiz-adv-x'] || WIDTH;
    const pixelWidth = advWidth > WIDTH ? advWidth / 12 : WIDTH / 12;
    console.log(`[writing...] ${svgFilePath}`);
    getSvgStr(lang.extend({
      advWidth
    }, icon), null, pixelWidth, (result) => {
      fs.writeFile(svgFilePath, result, 'utf8', (err) => {
        if (err) {
          console.log(`[ERROR]: ${err}`);
        }
      });
    });
  });
};