text:
<!--
Copyright 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<link rel="import" href="/bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="/bower_components/paper-dropdown/paper-dropdown.html">
<link rel="import" href="/bower_components/core-menu/core-menu.html">
<link rel="import" href="/bower_components/paper-item/paper-item.html">

<polymer-element name="paper-multi-menu" attributes="model value text subMenu">
  <template>
    <style>
      .hidden {
        display: none;
      }
    </style>
    <paper-dropdown-menu>
      <paper-dropdown class="dropdown">
        <core-menu class="menu" selected="0" on-core-select="{{ _select }}">
          <template repeat="{{ item in model.items }}">
            <paper-item menuValue="{{ item.value }}">{{ item.text }}</paper-item>
          </template>
        </core-menu>
      </paper-dropdown>
    </paper-dropdown-menu>
    <span id="subMenus">
      <template repeat="{{ item in model.items }}">
        <template if="{{ item.items }}">
          <paper-multi-menu id="{{ item.value }}" model="{{ item }}" class="hidden"></paper-multi-menu>
        </template>
      </template>
    </span>
  </template>
  <script>
    Polymer({
      _select: function(event) {
        var paperItem = event.detail.item;
        this.value = paperItem.getAttribute('menuValue');
        this.text = paperItem.textContent;
        this._toggleSubMenu();
        this.subMenu = this.$.subMenus.querySelector('#' + this.value);
        this._toggleSubMenu();
      },
      _toggleSubMenu: function() {
        if (this.subMenu) {
          this.subMenu.classList.toggle('hidden');
        }
      }
    });
  </script>
</polymer-element>

redpajama_set_name: RedPajamaGithub


text:
import { getGqlNames } from '../../../types';
import { graphql } from '../../..';
import { InitialisedList } from '../types-for-lists';
import * as createAndUpdate from './create-update';
import * as deletes from './delete';

// This is not a thing that I really agree with but it's to make the behaviour consistent with old keystone.
// Basically, old keystone uses Promise.allSettled and then after that maps that into promises that resolve and reject,
// whereas the new stuff is just like "here are some promises" with no guarantees about the order they will be settled in.
// That doesn't matter when they all resolve successfully because the order they resolve successfully in
// doesn't affect anything, If some reject though, the order that they reject in will be the order in the errors array
// and some of our tests rely on the order of the graphql errors array. They shouldn't, but they do.
function promisesButSettledWhenAllSettledAndInOrder<T extends Promise<unknown>[]>(promises: T): T {
  const resultsPromise = Promise.allSettled(promises);
  return promises.map(async (_, i) => {
    const result: PromiseSettledResult<Awaited<T>> = (await resultsPromise)[i] as any;
    return result.status === 'fulfilled'
      ? Promise.resolve(result.value)
      : Promise.reject(result.reason);
  }) as T;
}

export function getMutationsForList(list: InitialisedList) {
  const names = getGqlNames(list);

  const defaultUniqueWhereInput = list.isSingleton ? { id: '1' } : undefined;

  const createOne = graphql.field({
    type: list.types.output,
    args: {
      data: graphql.arg({ type: graphql.nonNull(list.types.create) }),
    },
    resolve(_rootVal, { data }, context) {
      return createAndUpdate.createOne({ data }, list, context);
    },
  });

  const createMany = graphql.field({
    type: graphql.list(list.types.output),
    args: {
      data: graphql.arg({
        type: graphql.nonNull(graphql.list(graphql.nonNull(list.types.create))),
      }),
    },
    async resolve(_rootVal, args, context) {
      return promisesButSettledWhenAllSettledAndInOrder(
        await createAndUpdate.createMany(args, list, context)
      );
    },
  });

  const updateOne = graphql.field({
    type: list.types.output,
    args: {
      where: graphql.arg({
        type: graphql.nonNull(list.types.uniqueWhere),
        defaultValue: defaultUniqueWhereInput,
      }),
      data: graphql.arg({ type: graphql.nonNull(list.types.update) }),
    },
    resolve(_rootVal, args, context) {
      return createAndUpdate.updateOne(args, list, context);
    },
  });

  const updateManyInput = graphql.inputObject({
    name: names.updateManyInputName,
    fields: {
      where: graphql.arg({
        type: graphql.nonNull(list.types.uniqueWhere),
        defaultValue: defaultUniqueWhereInput,
      }),
      data: graphql.arg({ type: graphql.nonNull(list.types.update) }),
    },
  });
  const updateMany = graphql.field({
    type: graphql.list(list.types.output),
    args: {
      data: graphql.arg({ type: graphql.nonNull(graphql.list(graphql.nonNull(updateManyInput))) }),
    },
    async resolve(_rootVal, args, context) {
      return promisesButSettledWhenAllSettledAndInOrder(
        await createAndUpdate.updateMany(args, list, context)
      );
    },
  });

  const deleteOne = graphql.field({
    type: list.types.output,
    args: {
      where: graphql.arg({
        type: graphql.nonNull(list.types.uniqueWhere),
        defaultValue: defaultUniqueWhereInput,
      }),
    },
    resolve(rootVal, { where }, context) {
      return deletes.deleteOne(where, list, context);
    },
  });

  const deleteMany = graphql.field({
    type: graphql.list(list.types.output),
    args: {
      where: graphql.arg({
        type: graphql.nonNull(graphql.list(graphql.nonNull(list.types.uniqueWhere))),
      }),
    },
    async resolve(rootVal, { where }, context) {
      return promisesButSettledWhenAllSettledAndInOrder(
        await deletes.deleteMany(where, list, context)
      );
    },
  });

  return {
    mutations: {
      ...(list.graphql.isEnabled.create && {
        [names.createMutationName]: createOne,
        [names.createManyMutationName]: createMany,
      }),
      ...(list.graphql.isEnabled.update && {
        [names.updateMutationName]: updateOne,
        [names.updateManyMutationName]: updateMany,
      }),
      ...(list.graphql.isEnabled.delete && {
        [names.deleteMutationName]: deleteOne,
        [names.deleteManyMutationName]: deleteMany,
      }),
    },
    updateManyInput,
  };
}


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Taskrouter\V1\Workspace;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;

class WorkspaceRealTimeStatisticsContext extends InstanceContext {
    /**
     * Initialize the WorkspaceRealTimeStatisticsContext
     *
     * @param \Twilio\Version $version Version that contains the resource
     * @param string $workspaceSid The SID of the Workspace to fetch
     * @return \Twilio\Rest\Taskrouter\V1\Workspace\WorkspaceRealTimeStatisticsContext
     */
    public function __construct(Version $version, $workspaceSid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = array('workspaceSid' => $workspaceSid, );

        $this->uri = '/Workspaces/' . \rawurlencode($workspaceSid) . '/RealTimeStatistics';
    }

    /**
     * Fetch a WorkspaceRealTimeStatisticsInstance
     *
     * @param array|Options $options Optional Arguments
     * @return WorkspaceRealTimeStatisticsInstance Fetched
     *                                             WorkspaceRealTimeStatisticsInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch($options = array()) {
        $options = new Values($options);

        $params = Values::of(array('TaskChannel' => $options['taskChannel'], ));

        $payload = $this->version->fetch(
            'GET',
            $this->uri,
            $params
        );

        return new WorkspaceRealTimeStatisticsInstance(
            $this->version,
            $payload,
            $this->solution['workspaceSid']
        );
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $context = array();
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Taskrouter.V1.WorkspaceRealTimeStatisticsContext ' . \implode(' ', $context) . ']';
    }
}


text:
/*!
  \class SoIndexedShape SoIndexedShape.h Inventor/nodes/SoIndexedShape.h
  \brief The SoIndexedShape class is the superclass for all indexed vertex shapes.
  \ingroup nodes

  This is an abstract class which contains storage for four fields for
  indices to coordinates, normals, materials and texture coordinates
  for it's subclasses.
*/

#include <Inventor/nodes/SoIndexedShape.h>

#include <Inventor/actions/SoAction.h>
#include <Inventor/elements/SoCoordinateElement.h>
#include <Inventor/elements/SoShapeHintsElement.h>
#include <Inventor/elements/SoNormalBindingElement.h>
#include <Inventor/elements/SoTextureCoordinateBindingElement.h>
#include <Inventor/errors/SoDebugError.h>
#include <Inventor/caches/SoNormalCache.h>
#include <Inventor/nodes/SoVertexProperty.h>

#include "nodes/SoSubNodeP.h"
#include "coindefs.h" // COIN_OBSOLETED()

/*!
  \var SoMFInt32 SoIndexedShape::coordIndex
  Coordinate indices.
*/
/*!
  \var SoMFInt32 SoIndexedShape::materialIndex
  Material indices.
*/
/*!
  \var SoMFInt32 SoIndexedShape::normalIndex
  Normal indices.
*/
/*!
  \var SoMFInt32 SoIndexedShape::textureCoordIndex
  Texture coordinate indices.
*/

SO_NODE_ABSTRACT_SOURCE(SoIndexedShape);

/*!
  Constructor.
*/
SoIndexedShape::SoIndexedShape()
{
  SO_NODE_INTERNAL_CONSTRUCTOR(SoIndexedShape);

  SO_NODE_ADD_FIELD(coordIndex,(0));
  SO_NODE_ADD_FIELD(materialIndex,(-1));
  SO_NODE_ADD_FIELD(normalIndex,(-1));
  SO_NODE_ADD_FIELD(textureCoordIndex,(-1));
}

/*!
  Destructor.
*/
SoIndexedShape::~SoIndexedShape()
{
}

// Documented in superclass.
void
SoIndexedShape::initClass(void)
{
  SO_NODE_INTERNAL_INIT_ABSTRACT_CLASS(SoIndexedShape, SO_FROM_INVENTOR_1);
}

// Collects common error msg code for computeBBox() for both
// Coordinate3 and Coordinate4 loops.
static void
error_idx_out_of_bounds(const SoIndexedShape * node, int idxidx, int upper)
{
  SbName n = node->getName();
  SbString ns(" ");
  ns += n;

  SbName t = node->getTypeId().getName();

  SbString bounds;
  if (upper > 0) {
    // (Note: the if-expression above should have been "upper >= 0",
    // if it weren't for the default SoCoordinateElement containing
    // one default coordinate.)
    bounds.sprintf("should be within [0, %d]", upper);
  }
  else {
    bounds = "but no coordinates are available from the state!";
  }

  SoDebugError::post("SoIndexedShape::computeBBox",
                     "coordinate index nr %d for %snode%s of type %s is "
                     "out of bounds: is %d, %s",
                     idxidx,
                     (n == "") ? "<unnamed> " : "",
                     (n != "") ? ns.getString() : "",
                     t.getString(),
                     node->coordIndex[idxidx],
                     bounds.getString());
}

// Documented in superclass. Overridden to calculate bounding box of
// all indexed coordinates, using the coordIndex field.
void
SoIndexedShape::computeBBox(SoAction * action, SbBox3f & box, SbVec3f & center)
{
  assert(box.isEmpty());
  SoState * state = action->getState();

  const SoCoordinateElement * coordelem = NULL;
  SoNode *vpnode = this->vertexProperty.getValue();
  SoVertexProperty *vp =
    (vpnode && vpnode->isOfType(SoVertexProperty::getClassTypeId())) ?
    (SoVertexProperty *)vpnode : NULL;
  SbBool vpvtx = vp && (vp->vertex.getNum() > 0);
  if (!vpvtx) {
    coordelem = SoCoordinateElement::getInstance(state);
  }

  const int numcoords = vpvtx ? vp->vertex.getNum() : coordelem->getNum();
  int numacc = 0; // to calculate weighted center point
  center.setValue(0.0f, 0.0f, 0.0f);

  if (vpvtx || coordelem->is3D()) {
    const SbVec3f * coords = vpvtx ?
      vp->vertex.getValues(0) :
      coordelem->getArrayPtr3();

    const int32_t * ptr = this->coordIndex.getValues(0);
    const int32_t * endptr = ptr + this->coordIndex.getNum();
    while (ptr < endptr) {
      const int idx = *ptr++;
      if (idx < numcoords) {
        if (idx >= 0) {
          box.extendBy(coords[idx]);
          center += coords[idx];
          numacc++;
        }
      }
#if COIN_DEBUG
      else {
        const ptrdiff_t faultyidxpos = (ptr - this->coordIndex.getValues(0)) - 1;
        error_idx_out_of_bounds(this, (int)faultyidxpos, numcoords - 1);
        if (numcoords <= 1) break; // give only one error msg on missing coords
        // (the default state is that there's a default
        // SoCoordinateElement element with a single default
        // coordinate point setup)
      }
#endif // COIN_DEBUG
    }
  }
  else {
    SbVec3f tmp;
    const SbVec4f * coords = coordelem->getArrayPtr4();
    const int32_t * ptr = this->coordIndex.getValues(0);
    const int32_t * endptr = ptr + this->coordIndex.getNum();
    while (ptr < endptr) {
      int idx = *ptr++;
      if (idx < numcoords) {
        if (idx >= 0) {
          SbVec4f h = coords[idx];
          h.getReal(tmp);
          box.extendBy(tmp);
          center += tmp;
          numacc++;
        }
      }
#if COIN_DEBUG
      else {
        const ptrdiff_t faultyidxpos = (ptr - this->coordIndex.getValues(0)) - 1;
        error_idx_out_of_bounds(this, (int)faultyidxpos, numcoords - 1);
        if (numcoords <= 1) break; // give only one error msg on missing coords
        // (the default state is that there's a default
        // SoCoordinateElement element with a single default
        // coordinate point setup)
      }
#endif // COIN_DEBUG
    }
  }
  if (numacc) center /= (float) numacc;
}

/*!
  Returns whether texture coordinates should be indexed or not.

  \sa SoTextureCoordinateBinding
*/
SbBool
SoIndexedShape::areTexCoordsIndexed(SoAction * action)
{
  return SoTextureCoordinateBindingElement::get(action->getState()) ==
    SoTextureCoordinateBindingElement::PER_VERTEX_INDEXED;
}

/*!
  Starting at index position \a startCoord, returns the number of
  indices until either the end of index array or a separator index (-1).
*/
int
SoIndexedShape::getNumVerts(const int startCoord)
{
  const int32_t * ptr = this->coordIndex.getValues(0);
  const int32_t * endptr = ptr + this->coordIndex.getNum();
  ptr += startCoord;
  int cnt = 0;
  while (ptr < endptr && *ptr >= 0) cnt++, ptr++;
  return cnt;
}

/*!
  Not implemented. Probably only used for internal purposes in SGI's
  original Open Inventor, which means it should have been private.

  Let us know if you need this method for any code you are porting and
  we'll look into implement it properly.
*/
void
SoIndexedShape::setupIndices(const int /* numParts */,
                             const int /* numFaces */,
                             const SbBool /* needNormals */,
                             const SbBool /* needTexCoords */)
{
  COIN_OBSOLETED();
}

/*!
  Not implemented. Probably only used for internal purposes in SGI's
  original Open Inventor, which means it should have been private.

  Let us know if you need this method for any code you are porting and
  we'll look into implement it properly.
*/
const int32_t *
SoIndexedShape::getNormalIndices()
{
  COIN_OBSOLETED();
  return NULL;
}

/*!
  Not implemented. Probably only used for internal purposes in SGI's
  original Open Inventor, which means it should have been private.

  Let us know if you need this method for any code you are porting and
  we'll look into implement it properly.
*/
const int32_t *
SoIndexedShape::getColorIndices()
{
  COIN_OBSOLETED();
  return NULL;
}

/*!
  Not implemented. Probably only used for internal purposes in SGI's
  original Open Inventor, which means it should have been private.

  Let us know if you need this method for any code you are porting and
  we'll look into implement it properly.
*/
const int32_t *
SoIndexedShape::getTexCoordIndices()
{
  COIN_OBSOLETED();
  return NULL;
}

/*!
  Convenience method that will fetch data needed for rendering or
  generating primitives. Takes care of normal cache.

  This method was not part of the original SGI Open Inventor API, and
  is an extension specific for Coin.
*/
SbBool
SoIndexedShape::getVertexData(SoState * state,
                              const SoCoordinateElement *& coords,
                              const SbVec3f *& normals,
                              const int32_t *& cindices,
                              const int32_t *& nindices,
                              const int32_t *& tindices,
                              const int32_t *& mindices,
                              int & numcindices,
                              const SbBool needNormals,
                              SbBool & normalCacheUsed)
{
  SoVertexShape::getVertexData(state, coords, normals, needNormals);

  cindices = this->coordIndex.getValues(0);
  numcindices = this->coordIndex.getNum();

  mindices = this->materialIndex.getValues(0);
  if (this->materialIndex.getNum() <= 0 || mindices[0] < 0) mindices = NULL;

  tindices = this->textureCoordIndex.getValues(0);
  if (this->textureCoordIndex.getNum() <= 0 || tindices[0] < 0) tindices = NULL;

  normalCacheUsed = FALSE;
  nindices = NULL;
  if (needNormals) {
    nindices = this->normalIndex.getValues(0);
    if (this->normalIndex.getNum() <= 0 || nindices[0] < 0) nindices = NULL;

    if (normals == NULL) {
      SoNormalCache * nc = this->generateAndReadLockNormalCache(state);
      normals = nc->getNormals();
      nindices = nc->getIndices();
      normalCacheUsed = TRUE;

      // if no normals were generated, unlock normal cache before
      // returning
      if (normals == NULL) {
        this->readUnlockNormalCache();
        normalCacheUsed = FALSE;
      }
    }
  }
  return TRUE;
}


text: Repository used for testing NativeScript plugins


text:
package gdv.xport.util;

/**
 * Der VersionHandler ist fuer die Abfrage der Default-Version eines Satzes
 * zustaendig.
 *
 * @author oliver
 * @since 5.0 (15.01.21)
 */
public interface VersionHandler {

    /**
     * Liefert die (Default-)Version der angefragten Satzart
     *
     * @param satzTyp Satzart, z.B. "0001"
     * @return z.B. "2.4"
     */
    String getVersionOf(SatzTyp satzTyp);

}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import unittest

from pkg_resources import WorkingSet

from pants.base.exceptions import BuildConfigurationError
from pants.init.options_initializer import OptionsInitializer
from pants.option.options_bootstrapper import OptionsBootstrapper

class OptionsInitializerTest(unittest.TestCase):
  def test_invalid_version(self):
    options_bootstrapper = OptionsBootstrapper(args=['--pants-version=99.99.9999'])
    initializer = OptionsInitializer(options_bootstrapper, WorkingSet())

    with self.assertRaises(BuildConfigurationError):
      initializer.setup()


text:
//
// Created by victor on 7/6/20.
//

#ifndef DBCRUDGEN_CPP_SPRINGBOOTPROJECTCREATOR_H
#define DBCRUDGEN_CPP_SPRINGBOOTPROJECTCREATOR_H

#include "JavaProjectCreator.h"
#include "../../projects/SpringBootProjectModel.h"
#include "../../../databases/generic/Database.h"
#include "../../parsers/java/JavaParser.h"
#include "../../codegen/java/JaxbCodeGen.h"
#include "../../parsers/java/HibernateEntitiesParser.h"
#include "../../parsers/java/HibernateConfigurationParser.h"
#include "../../templates/java/crud/hibernate/HibernateClassConfigurationTemplate.h"
#include "../../codegen/java/hibernate/HibernateAbstractableTransactionsCodeGen.h"
#include "../../codegen/java/hibernate/HibernateConfigCodeGen.h"
#include "../../codegen/java/hibernate/HibernateTransactionsCodeGen.h"
#include "../../codegen/java/hibernate/HibernateEntitiyCodeGen.h"
#include "../../codegen/java/spring-boot/SpringBootApplicationCodeGen.h"
#include "../../codegen/java/spring-boot/SpringBootHttpErrorCodeGen.h"
#include "../../codegen/java/spring-boot/SpringBootControllerCodeGen.h"
#include "../../codegen/java/spring-boot/SpringBootHttpCodeGen.h"
#include "../../codegen/java/spring-boot/SpringBootRepoCodeGen.h"

namespace dbcrudgen {
    namespace orm {

        class SpringBootProjectCreator : public JavaProjectCreator {

        private:
            SpringBootProjectModel projectModel;
            dbcrudgen::db::generic::Database database;

        public:

            SpringBootProjectCreator(SpringBootProjectModel &projectModel, dbcrudgen::db::generic::Database &database)
                    : projectModel{projectModel}, database{database}, JavaProjectCreator{projectModel} {}

            std::string getLanguage() override {
                return std::string{Languages::JAVA};
            }

            std::string getDatabase() override {
                return std::string{Databases::GENERIC};
            }

            /**
              * Create project Dirs
              */
            void createProjectDirs() override {
                JavaProjectCreator::createProjectDirs();

                FilesWriter::createDirs(projectModel.getAbsoluteWebDirPath());
                FilesWriter::createDirs(projectModel.getAbsoluteWebErrorDirPath());
                FilesWriter::createDirs(projectModel.getApisAbsolutePath());
                FilesWriter::createDirs(projectModel.getBeansAbsolutePath());
                FilesWriter::createDirs(projectModel.getDatabaseConnectionAbsolutePath());
                FilesWriter::createDirs(projectModel.getEntitiesAbsolutePath());
                FilesWriter::createDirs(projectModel.getHttpRequestsDirPath());
                FilesWriter::createDirs(projectModel.getHttpResponsesDirPath());
                FilesWriter::createDirs(projectModel.getRepositoriesDirPath());
                FilesWriter::createDirs(projectModel.getTransactionsAbsolutePath());
                FilesWriter::createDirs(projectModel.getWebApplicationAbsolutePath());
            }

            /**
             * Create a java jax-ws project
             */
            void createProject() override {
                JavaProjectCreator::createProject();
            }

            /**
             * Create project source files
             */
            void createSourceFiles() override {
                JavaProjectCreator::createSourceFiles();

                std::string error400 = SpringBootHttpErrorCodeGen::createErrorPage(projectModel, "400");
                std::string error404 = SpringBootHttpErrorCodeGen::createErrorPage(projectModel, "404");
                std::string error500 = SpringBootHttpErrorCodeGen::createErrorPage(projectModel, "500");

                std::string applicationClass = SpringBootApplicationCodeGen::createApplicationClass(projectModel);

                std::vector<dbcrudgen::db::generic::Table> tables = database.getTables();

                createHibernateConnectionClass();
                createAbstractableTransactionsExecutorClassFile();

                std::string entityMappings;

                for (const dbcrudgen::db::generic::Table &table : tables) {

                    const std::string &tableName = table.getTableName();
                    dbcrudgen::db::generic::Column *pkColumn = nullptr;

                    std::string apiSuffix = projectModel.getApiClassSuffix();
                    std::string beansSuffix = projectModel.getBeansClassSuffix();
                    std::string entitySuffix = projectModel.getEntityClassSuffix();
                    std::string httpReqSuffix = projectModel.getHttpReqClassSuffix();
                    std::string httpResSuffix = projectModel.getHttpResClassSuffix();
                    std::string reposSuffix = projectModel.getRepoClassSuffix();
                    std::string trxSuffix = projectModel.getTrxClassSuffix();

                    std::string tmpClassName = JavaParser::toJavaClassName(tableName);

                    std::string beansClass = tmpClassName;
                    std::string ctlClass = tmpClassName;
                    std::string entityClass = tmpClassName;
                    std::string httpReqClass = tmpClassName;
                    std::string httpResClass = tmpClassName;
                    std::string repoClass = tmpClassName;
                    std::string trxClass = tmpClassName;

                    beansClass.append(beansSuffix);
                    ctlClass.append(apiSuffix);
                    entityClass.append(entitySuffix);
                    httpReqClass.append(httpReqSuffix);
                    httpResClass.append(httpResSuffix);
                    repoClass.append(reposSuffix);
                    trxClass.append(trxSuffix);

                    std::string ctlSource =
                            SpringBootControllerCodeGen::createControllerSource(projectModel, table, ctlClass,
                                                                                entityClass, trxClass);

                    std::string entitySource =
                            HibernateEntityCodeGen::createHibernateEntitySource(projectModel, tableName, entityClass);

                    std::string trxSource =
                            HibernateTransactionsCodeGen::createHibernateTrxSource(projectModel, table, trxClass,
                                                                                entityClass);

                    std::string httpReqSource = SpringBootHttpCodeGen::createHttpReqSource(projectModel,
                                                                                httpReqClass);
                    std::string httpResSource = SpringBootHttpCodeGen::createHttpResSource(projectModel, httpResClass);
                    std::string repoSource = SpringBootRepoCodeGen::createRepositorySource(projectModel,
                                                                                repoClass, entityClass);

                    std::string beansSource = JaxbCodeGen::createBeansSource(projectModel, beansClass);
                    std::string mappingSource = HibernateConfigCodeGen::createEntityTableMappingSource();

                    entityMappings += HibernateParser::parseEntityClassMapping(mappingSource,
                                                                               projectModel.getPackageName(),
                                                                               projectModel.getEntitiesPkg(),
                                                                               entityClass);

                    std::string entityInstanceVars;
                    std::string entityGetterSetters;

                    std::string beansInstanceVars;
                    std::string beansGetterSetters;
                    std::string beanCtorVariables;
                    std::string beanInstanceVariablesInit;
                    std::string beanDefaultCtorVariablesInit;

                    std::string httpReqInstanceVars;

                    const std::vector<dbcrudgen::db::generic::Column> &columns = table.getTableColumns();

                    int index = 0;
                    for (const dbcrudgen::db::generic::Column &column : columns) {

                        entityInstanceVars += HibernateEntitiesParser::createInstanceVariable(column);
                        entityGetterSetters += HibernateEntitiesParser::createGetterSetter(column);

                        beansInstanceVars += JaxbCodeGen::createInstanceVariable(column);
                        beansGetterSetters += JaxbCodeGen::createGetterSetter(column);
                        beanCtorVariables += JaxbCodeGen::createConstructorVariable(column, index < columns.size() - 1);
                        beanInstanceVariablesInit += JaxbCodeGen::createInstanceVariableConstructorInitialization(
                                column);
                        beanDefaultCtorVariablesInit += JaxbCodeGen::createInstanceVariableDefaultBeanConstructorInitialization(
                                column);

                        if (!column.isNullable()) {
                            httpReqInstanceVars += SpringBootRepoCodeGen::createInstanceVariable(column);
                        }

                        if (column.isPrimary()) {
                            pkColumn = const_cast<dbcrudgen::db::generic::Column *>(&column);
                        }
                        index++;
                    }

                    HibernateEntitiesParser::parseColumnInstanceVariables(entitySource, entityInstanceVars);
                    HibernateEntitiesParser::parseColumnGetterSetters(entitySource, entityGetterSetters);

                    JaxbCodeGen::addInstanceVariables(beansSource, beansInstanceVars);
                    JaxbCodeGen::addGetterSetters(beansSource, beansGetterSetters);
                    JaxbCodeGen::addConstructorVariables(beansSource, beanCtorVariables);
                    JaxbCodeGen::addConstructorVariablesInitialization(beansSource, beanInstanceVariablesInit);
                    JaxbCodeGen::addDefaultInstanceVariablesInitialization(beansSource, beanDefaultCtorVariablesInit);

                    SpringBootHttpCodeGen::addReqModelInstanceVariables(httpReqSource, httpReqInstanceVars);
                    SpringBootHttpCodeGen::addRepositoryPrimaryKey(repoSource, pkColumn);

                    std::string ctlFile =
                            projectModel.getApisAbsolutePath() + "/" + ctlClass + ".java";

                    std::string entityFile =
                            projectModel.getEntitiesAbsolutePath() + "/" + entityClass + ".java";

                    std::string trxFile =
                            projectModel.getTransactionsAbsolutePath() + "/" + trxClass + ".java";

                    std::string beanFile =
                            projectModel.getBeansAbsolutePath() + "/" + beansClass + ".java";

                    std::string httpReqFile =
                            projectModel.getHttpRequestsDirPath() + "/" + httpReqClass + ".java";
                    std::string httpResFile =
                            projectModel.getHttpResponsesDirPath() + "/" + httpResClass + ".java";
                    std::string repoFile =
                            projectModel.getRepositoriesDirPath() + "/" + repoClass + ".java";

                    FilesWriter::writeFile(ctlFile, ctlSource);
                    FilesWriter::writeFile(entityFile, entitySource);
                    FilesWriter::writeFile(trxFile, trxSource);
                    FilesWriter::writeFile(beanFile, beansSource);

                    FilesWriter::writeFile(httpReqFile, httpReqSource);
                    FilesWriter::writeFile(httpResFile, httpResSource);
                    FilesWriter::writeFile(repoFile, repoSource);
                }

                createHtmlErrorPages(error400, error404, error500);
                createApplicationClassFile(applicationClass);
                //createHibernateConnectionScript((std::string &) "THIS IS THE SRC CODE");

            }

            /**
             * Create the hibernate connection class
             */
            void createHibernateConnectionClass() {
                HibernateClassConfigurationTemplate hConnConfigTemplate;
                std::string connPath = projectModel.getDatabaseConnectionAbsolutePath();
                std::string connConfigFile = connPath + "/" + projectModel.getDbConnClassName() + ".java";

                std::string configSource = hConnConfigTemplate.getTemplate();
                HibernateConfigurationParser::parseConfigurationClass(projectModel, configSource);
                FilesWriter::writeFile(connConfigFile, configSource);
            }

            /**
             * Writes the abstractable transactions executor class file
             * @param absTrxSource
             */
            void createAbstractableTransactionsExecutorClassFile() {
                std::string absTrxSource = HibernateAbstractableTransactionsCodeGen::getAbstractableTransactionsSource(
                        projectModel);
                std::string filename = projectModel.getAbstractableTransactionsExecutorFileAbsolutePath();
                FilesWriter::writeFile(filename, absTrxSource);
            }

            /**
             * Create the hibernate connection script
             * @param entityMappings
             */
            void createHibernateConnectionScript(std::string &entityMappings) {

                std::string configSource =
                        HibernateConfigCodeGen::createHibernateConfigSource(projectModel, database, entityMappings);

                std::string javaPath = projectModel.getAbsoluteJavaPath();
                std::string resourcesPath = projectModel.getAbsoluteResourcesPath();

                std::string javaHibernateConfigFile = javaPath + "/hibernate.cfg.xml";
                std::string resourcesHibernateConfigFile = resourcesPath + "/hibernate.cfg.xml";

                HibernateConfigurationParser::parseConfigurationClass(projectModel, configSource);

                FilesWriter::writeFile(javaHibernateConfigFile, configSource);
                FilesWriter::writeFile(resourcesHibernateConfigFile, configSource);
            }

            /**
             * Writes the Web XML Source on disk
             * @param error400Html
             */
            void createHtmlErrorPages(const std::string &error400Html, const std::string &error404Html,
                                      const std::string &error500Html) {
                FilesWriter::writeFile(projectModel.getAbsoluteWebError400FilePath(), error400Html);
                FilesWriter::writeFile(projectModel.getAbsoluteWebError404FilePath(), error404Html);
                FilesWriter::writeFile(projectModel.getAbsoluteWebError500FilePath(), error500Html);
            }

            /**
            * Writes the Web XML Source on disk
            * @param appClassSource
            */
            void createApplicationClassFile(const std::string &appClassSource) {
                std::string filename = projectModel.getWebApplicationFileAbsolutePath();
                FilesWriter::writeFile(filename, appClassSource);
            }
        };
    }
}

#endif //DBCRUDGEN_CPP_SPRINGBOOTPROJECTCREATOR_H


text:
package spanmetricsprocessor

import (
	"bytes"
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/component/componenttest"
	"go.opentelemetry.io/collector/config"
	"go.opentelemetry.io/collector/config/configgrpc"
	"go.opentelemetry.io/collector/consumer/consumertest"
	"go.opentelemetry.io/collector/exporter/otlpexporter"
	"go.opentelemetry.io/collector/pdata/pcommon"
	"go.opentelemetry.io/collector/pdata/pmetric"
	"go.opentelemetry.io/collector/pdata/ptrace"
	conventions "go.opentelemetry.io/collector/semconv/v1.6.1"
	"go.uber.org/zap"
	"go.uber.org/zap/zaptest"
	"google.golang.org/grpc/metadata"

	"github.com/open-telemetry/opentelemetry-collector-contrib/processor/spanmetricsprocessor/internal/cache"
	"github.com/open-telemetry/opentelemetry-collector-contrib/processor/spanmetricsprocessor/mocks"
)

const (
	stringAttrName         = "stringAttrName"
	intAttrName            = "intAttrName"
	doubleAttrName         = "doubleAttrName"
	boolAttrName           = "boolAttrName"
	nullAttrName           = "nullAttrName"
	mapAttrName            = "mapAttrName"
	arrayAttrName          = "arrayAttrName"
	notInSpanAttrName0     = "shouldBeInMetric"
	notInSpanAttrName1     = "shouldNotBeInMetric"
	regionResourceAttrName = "region"
	DimensionsCacheSize    = 2

	sampleRegion          = "us-east-1"
	sampleLatency         = float64(11)
	sampleLatencyDuration = time.Duration(sampleLatency) * time.Millisecond
)

// metricID represents the minimum attributes that uniquely identifies a metric in our tests.
type metricID struct {
	service    string
	operation  string
	kind       string
	statusCode string
}

type metricDataPoint interface {
	Attributes() pcommon.Map
}

type serviceSpans struct {
	serviceName string
	spans       []span
}

type span struct {
	operation  string
	kind       ptrace.SpanKind
	statusCode ptrace.StatusCode
}

func TestProcessorStart(t *testing.T) {
	// Create otlp exporters.
	otlpConfig, mexp, texp := newOTLPExporters(t)

	for _, tc := range []struct {
		name            string
		exporter        component.Component
		metricsExporter string
		wantErrorMsg    string
	}{
		{"export to active otlp metrics exporter", mexp, "otlp", ""},
		{"unable to find configured exporter in active exporter list", mexp, "prometheus", "failed to find metrics exporter: 'prometheus'; please configure metrics_exporter from one of: [otlp]"},
		{"export to active otlp traces exporter should error", texp, "otlp", "the exporter \"otlp\" isn't a metrics exporter"},
	} {
		t.Run(tc.name, func(t *testing.T) {
			// Prepare
			exporters := map[component.DataType]map[component.ID]component.Component{
				component.DataTypeMetrics: {
					otlpConfig.ID(): tc.exporter,
				},
			}
			mhost := &mocks.Host{}
			mhost.On("GetExporters").Return(exporters)

			// Create spanmetrics processor
			factory := NewFactory()
			cfg := factory.CreateDefaultConfig().(*Config)
			cfg.MetricsExporter = tc.metricsExporter

			procCreationParams := componenttest.NewNopProcessorCreateSettings()
			traceProcessor, err := factory.CreateTracesProcessor(context.Background(), procCreationParams, cfg, consumertest.NewNop())
			require.NoError(t, err)

			// Test
			smp := traceProcessor.(*processorImp)
			err = smp.Start(context.Background(), mhost)

			// Verify
			if tc.wantErrorMsg != "" {
				assert.EqualError(t, err, tc.wantErrorMsg)
			} else {
				assert.NoError(t, err)
			}
		})
	}
}

func TestProcessorShutdown(t *testing.T) {
	// Prepare
	factory := NewFactory()
	cfg := factory.CreateDefaultConfig().(*Config)

	// Test
	next := new(consumertest.TracesSink)
	p, err := newProcessor(zaptest.NewLogger(t), cfg, next)
	assert.NoError(t, err)
	err = p.Shutdown(context.Background())

	// Verify
	assert.NoError(t, err)
}

func TestConfigureLatencyBounds(t *testing.T) {
	// Prepare
	factory := NewFactory()
	cfg := factory.CreateDefaultConfig().(*Config)
	cfg.LatencyHistogramBuckets = []time.Duration{
		3 * time.Nanosecond,
		3 * time.Microsecond,
		3 * time.Millisecond,
		3 * time.Second,
	}

	// Test
	next := new(consumertest.TracesSink)
	p, err := newProcessor(zaptest.NewLogger(t), cfg, next)

	// Verify
	assert.NoError(t, err)
	assert.NotNil(t, p)
	assert.Equal(t, []float64{0.000003, 0.003, 3, 3000}, p.latencyBounds)
}

func TestProcessorCapabilities(t *testing.T) {
	// Prepare
	factory := NewFactory()
	cfg := factory.CreateDefaultConfig().(*Config)

	// Test
	next := new(consumertest.TracesSink)
	p, err := newProcessor(zaptest.NewLogger(t), cfg, next)
	assert.NoError(t, err)
	caps := p.Capabilities()

	// Verify
	assert.NotNil(t, p)
	assert.Equal(t, false, caps.MutatesData)
}

func TestProcessorConsumeTracesErrors(t *testing.T) {
	for _, tc := range []struct {
		name              string
		consumeMetricsErr error
		consumeTracesErr  error
	}{
		{
			name:              "ConsumeMetrics error",
			consumeMetricsErr: fmt.Errorf("consume metrics error"),
		},
		{
			name:             "ConsumeTraces error",
			consumeTracesErr: fmt.Errorf("consume traces error"),
		},
		{
			name:              "ConsumeMetrics and ConsumeTraces error",
			consumeMetricsErr: fmt.Errorf("consume metrics error"),
			consumeTracesErr:  fmt.Errorf("consume traces error"),
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			// Prepare
			logger := zap.NewNop()

			mexp := &mocks.MetricsExporter{}
			mexp.On("ConsumeMetrics", mock.Anything, mock.Anything).Return(tc.consumeMetricsErr)

			tcon := &mocks.TracesConsumer{}
			tcon.On("ConsumeTraces", mock.Anything, mock.Anything).Return(tc.consumeTracesErr)

			p := newProcessorImp(mexp, tcon, nil, cumulative, logger)

			traces := buildSampleTrace()

			// Test
			ctx := metadata.NewIncomingContext(context.Background(), nil)
			err := p.ConsumeTraces(ctx, traces)

			// Verify
			require.Error(t, err)
			switch {
			case tc.consumeMetricsErr != nil && tc.consumeTracesErr != nil:
				assert.EqualError(t, err, tc.consumeMetricsErr.Error()+"; "+tc.consumeTracesErr.Error())
			case tc.consumeMetricsErr != nil:
				assert.EqualError(t, err, tc.consumeMetricsErr.Error())
			case tc.consumeTracesErr != nil:
				assert.EqualError(t, err, tc.consumeTracesErr.Error())
			default:
				assert.Fail(t, "expected at least one error")
			}
		})
	}
}

func TestProcessorConsumeTraces(t *testing.T) {
	t.Parallel()

	testcases := []struct {
		name                   string
		aggregationTemporality string
		verifier               func(t testing.TB, input pmetric.Metrics) bool
		traces                 []ptrace.Traces
	}{
		{
			name:                   "Test single consumption, three spans (Cumulative).",
			aggregationTemporality: cumulative,
			verifier:               verifyConsumeMetricsInputCumulative,
			traces:                 []ptrace.Traces{buildSampleTrace()},
		},
		{
			name:                   "Test single consumption, three spans (Delta).",
			aggregationTemporality: delta,
			verifier:               verifyConsumeMetricsInputDelta,
			traces:                 []ptrace.Traces{buildSampleTrace()},
		},
		{
			// More consumptions, should accumulate additively.
			name:                   "Test two consumptions (Cumulative).",
			aggregationTemporality: cumulative,
			verifier:               verifyMultipleCumulativeConsumptions(),
			traces:                 []ptrace.Traces{buildSampleTrace(), buildSampleTrace()},
		},
		{
			// More consumptions, should not accumulate. Therefore, end state should be the same as single consumption case.
			name:                   "Test two consumptions (Delta).",
			aggregationTemporality: delta,
			verifier:               verifyConsumeMetricsInputDelta,
			traces:                 []ptrace.Traces{buildSampleTrace(), buildSampleTrace()},
		},
		{
			// Consumptions with improper timestamps
			name:                   "Test bad consumptions (Delta).",
			aggregationTemporality: cumulative,
			verifier:               verifyBadMetricsOkay,
			traces:                 []ptrace.Traces{buildBadSampleTrace()},
		},
	}

	for _, tc := range testcases {
		// Since parallelism is enabled in these tests, to avoid flaky behavior,
		// instantiate a copy of the test case for t.Run's closure to use.
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			// Prepare
			mexp := &mocks.MetricsExporter{}
			tcon := &mocks.TracesConsumer{}

			// Mocked metric exporter will perform validation on metrics, during p.ConsumeTraces()
			mexp.On("ConsumeMetrics", mock.Anything, mock.MatchedBy(func(input pmetric.Metrics) bool {
				return assert.Eventually(t, func() bool {
					return tc.verifier(t, input)
				}, 10*time.Second, time.Millisecond*100)
			})).Return(nil)
			tcon.On("ConsumeTraces", mock.Anything, mock.Anything).Return(nil)

			defaultNullValue := pcommon.NewValueStr("defaultNullValue")
			p := newProcessorImp(mexp, tcon, &defaultNullValue, tc.aggregationTemporality, zaptest.NewLogger(t))

			for _, traces := range tc.traces {
				// Test
				ctx := metadata.NewIncomingContext(context.Background(), nil)
				err := p.ConsumeTraces(ctx, traces)

				// Verify
				assert.NoError(t, err)
			}
		})
	}
}

func TestMetricKeyCache(t *testing.T) {
	mexp := &mocks.MetricsExporter{}
	tcon := &mocks.TracesConsumer{}

	mexp.On("ConsumeMetrics", mock.Anything, mock.Anything).Return(nil)
	tcon.On("ConsumeTraces", mock.Anything, mock.Anything).Return(nil)

	defaultNullValue := pcommon.NewValueStr("defaultNullValue")
	p := newProcessorImp(mexp, tcon, &defaultNullValue, cumulative, zaptest.NewLogger(t))
	traces := buildSampleTrace()

	// Test
	ctx := metadata.NewIncomingContext(context.Background(), nil)

	// 0 key was cached at beginning
	assert.Zero(t, p.metricKeyToDimensions.Len())

	err := p.ConsumeTraces(ctx, traces)
	// Validate
	require.NoError(t, err)
	// 2 key was cached, 1 key was evicted and cleaned after the processing
	assert.Eventually(t, func() bool {
		return assert.Equal(t, DimensionsCacheSize, p.metricKeyToDimensions.Len())
	}, 10*time.Second, time.Millisecond*100)

	// consume another batch of traces
	err = p.ConsumeTraces(ctx, traces)
	require.NoError(t, err)

	// 2 key was cached, other keys were evicted and cleaned after the processing
	assert.Eventually(t, func() bool {
		return assert.Equal(t, DimensionsCacheSize, p.metricKeyToDimensions.Len())
	}, 10*time.Second, time.Millisecond*100)
}

func BenchmarkProcessorConsumeTraces(b *testing.B) {
	// Prepare
	mexp := &mocks.MetricsExporter{}
	tcon := &mocks.TracesConsumer{}

	mexp.On("ConsumeMetrics", mock.Anything, mock.Anything).Return(nil)
	tcon.On("ConsumeTraces", mock.Anything, mock.Anything).Return(nil)

	defaultNullValue := pcommon.NewValueStr("defaultNullValue")
	p := newProcessorImp(mexp, tcon, &defaultNullValue, cumulative, zaptest.NewLogger(b))

	traces := buildSampleTrace()

	// Test
	ctx := metadata.NewIncomingContext(context.Background(), nil)
	for n := 0; n < b.N; n++ {
		assert.NoError(b, p.ConsumeTraces(ctx, traces))
	}
}

func newProcessorImp(mexp *mocks.MetricsExporter, tcon *mocks.TracesConsumer, defaultNullValue *pcommon.Value, temporality string, logger *zap.Logger) *processorImp {
	defaultNotInSpanAttrVal := pcommon.NewValueStr("defaultNotInSpanAttrVal")
	// use size 2 for LRU cache for testing purpose
	metricKeyToDimensions, err := cache.NewCache[metricKey, pcommon.Map](DimensionsCacheSize)
	if err != nil {
		panic(err)
	}
	return &processorImp{
		logger:          logger,
		config:          Config{AggregationTemporality: temporality},
		metricsExporter: mexp,
		nextConsumer:    tcon,

		startTimestamp: pcommon.NewTimestampFromTime(time.Now()),
		histograms:     make(map[metricKey]*histogramData),
		latencyBounds:  defaultLatencyHistogramBucketsMs,
		dimensions: []dimension{
			// Set nil defaults to force a lookup for the attribute in the span.
			{stringAttrName, nil},
			{intAttrName, nil},
			{doubleAttrName, nil},
			{boolAttrName, nil},
			{mapAttrName, nil},
			{arrayAttrName, nil},
			{nullAttrName, defaultNullValue},
			// Add a default value for an attribute that doesn't exist in a span
			{notInSpanAttrName0, &defaultNotInSpanAttrVal},
			// Leave the default value unset to test that this dimension should not be added to the metric.
			{notInSpanAttrName1, nil},
			// Add a resource attribute to test "process" attributes like IP, host, region, cluster, etc.
			{regionResourceAttrName, nil},
		},
		keyBuf:                new(bytes.Buffer),
		metricKeyToDimensions: metricKeyToDimensions,
	}
}

// verifyConsumeMetricsInputCumulative expects one accumulation of metrics, and marked as cumulative
func verifyConsumeMetricsInputCumulative(t testing.TB, input pmetric.Metrics) bool {
	return verifyConsumeMetricsInput(t, input, pmetric.AggregationTemporalityCumulative, 1)
}

func verifyBadMetricsOkay(t testing.TB, input pmetric.Metrics) bool {
	return true // Validating no exception
}

// verifyConsumeMetricsInputDelta expects one accumulation of metrics, and marked as delta
func verifyConsumeMetricsInputDelta(t testing.TB, input pmetric.Metrics) bool {
	return verifyConsumeMetricsInput(t, input, pmetric.AggregationTemporalityDelta, 1)
}

// verifyMultipleCumulativeConsumptions expects the amount of accumulations as kept track of by numCumulativeConsumptions.
// numCumulativeConsumptions acts as a multiplier for the values, since the cumulative metrics are additive.
func verifyMultipleCumulativeConsumptions() func(t testing.TB, input pmetric.Metrics) bool {
	numCumulativeConsumptions := 0
	return func(t testing.TB, input pmetric.Metrics) bool {
		numCumulativeConsumptions++
		return verifyConsumeMetricsInput(t, input, pmetric.AggregationTemporalityCumulative, numCumulativeConsumptions)
	}
}

// verifyConsumeMetricsInput verifies the input of the ConsumeMetrics call from this processor.
// This is the best point to verify the computed metrics from spans are as expected.
func verifyConsumeMetricsInput(t testing.TB, input pmetric.Metrics, expectedTemporality pmetric.AggregationTemporality, numCumulativeConsumptions int) bool {
	require.Equal(t, 6, input.DataPointCount(),
		"Should be 3 for each of call count and latency. Each group of 3 data points is made of: "+
			"service-a (server kind) -> service-a (client kind) -> service-b (service kind)",
	)

	rm := input.ResourceMetrics()
	require.Equal(t, 1, rm.Len())

	ilm := rm.At(0).ScopeMetrics()
	require.Equal(t, 1, ilm.Len())
	assert.Equal(t, "spanmetricsprocessor", ilm.At(0).Scope().Name())

	m := ilm.At(0).Metrics()
	require.Equal(t, 2, m.Len())

	seenMetricIDs := make(map[metricID]bool)
	// The first 3 data points are for call counts.
	assert.Equal(t, "calls_total", m.At(0).Name())
	assert.Equal(t, expectedTemporality, m.At(0).Sum().AggregationTemporality())
	assert.True(t, m.At(0).Sum().IsMonotonic())
	callsDps := m.At(0).Sum().DataPoints()
	require.Equal(t, 3, callsDps.Len())
	for dpi := 0; dpi < 3; dpi++ {
		dp := callsDps.At(dpi)
		assert.Equal(t, int64(numCumulativeConsumptions), dp.IntValue(), "There should only be one metric per Service/operation/kind combination")
		assert.NotZero(t, dp.StartTimestamp(), "StartTimestamp should be set")
		assert.NotZero(t, dp.Timestamp(), "Timestamp should be set")
		verifyMetricLabels(dp, t, seenMetricIDs)
	}

	seenMetricIDs = make(map[metricID]bool)
	// The remaining 3 data points are for latency.
	assert.Equal(t, "latency", m.At(1).Name())
	assert.Equal(t, "ms", m.At(1).Unit())
	assert.Equal(t, expectedTemporality, m.At(1).Histogram().AggregationTemporality())
	latencyDps := m.At(1).Histogram().DataPoints()
	require.Equal(t, 3, latencyDps.Len())
	for dpi := 0; dpi < 3; dpi++ {
		dp := latencyDps.At(dpi)
		assert.Equal(t, sampleLatency*float64(numCumulativeConsumptions), dp.Sum(), "Should be a 11ms latency measurement, multiplied by the number of stateful accumulations.")
		assert.NotZero(t, dp.Timestamp(), "Timestamp should be set")

		// Verify bucket counts.

		// The bucket counts should be 1 greater than the explicit bounds as documented in:
		// https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto.
		assert.Equal(t, dp.ExplicitBounds().Len()+1, dp.BucketCounts().Len())

		// Find the bucket index where the 11ms latency should belong in.
		var foundLatencyIndex int
		for foundLatencyIndex = 0; foundLatencyIndex < dp.ExplicitBounds().Len(); foundLatencyIndex++ {
			if dp.ExplicitBounds().At(foundLatencyIndex) > sampleLatency {
				break
			}
		}

		// Then verify that all histogram buckets are empty except for the bucket with the 11ms latency.
		var wantBucketCount uint64
		for bi := 0; bi < dp.BucketCounts().Len(); bi++ {
			wantBucketCount = 0
			if bi == foundLatencyIndex {
				wantBucketCount = uint64(numCumulativeConsumptions)
			}
			assert.Equal(t, wantBucketCount, dp.BucketCounts().At(bi))
		}
		verifyMetricLabels(dp, t, seenMetricIDs)
	}
	return true
}

func verifyMetricLabels(dp metricDataPoint, t testing.TB, seenMetricIDs map[metricID]bool) {
	mID := metricID{}
	wantDimensions := map[string]pcommon.Value{
		stringAttrName:         pcommon.NewValueStr("stringAttrValue"),
		intAttrName:            pcommon.NewValueInt(99),
		doubleAttrName:         pcommon.NewValueDouble(99.99),
		boolAttrName:           pcommon.NewValueBool(true),
		nullAttrName:           pcommon.NewValueEmpty(),
		arrayAttrName:          pcommon.NewValueSlice(),
		mapAttrName:            pcommon.NewValueMap(),
		notInSpanAttrName0:     pcommon.NewValueStr("defaultNotInSpanAttrVal"),
		regionResourceAttrName: pcommon.NewValueStr(sampleRegion),
	}
	dp.Attributes().Range(func(k string, v pcommon.Value) bool {
		switch k {
		case serviceNameKey:
			mID.service = v.Str()
		case operationKey:
			mID.operation = v.Str()
		case spanKindKey:
			mID.kind = v.Str()
		case statusCodeKey:
			mID.statusCode = v.Str()
		case notInSpanAttrName1:
			assert.Fail(t, notInSpanAttrName1+" should not be in this metric")
		default:
			assert.Equal(t, wantDimensions[k], v)
			delete(wantDimensions, k)
		}
		return true
	})
	assert.Empty(t, wantDimensions, "Did not see all expected dimensions in metric. Missing: ", wantDimensions)

	// Service/operation/kind should be a unique metric.
	assert.False(t, seenMetricIDs[mID])
	seenMetricIDs[mID] = true
}

func buildBadSampleTrace() ptrace.Traces {
	badTrace := buildSampleTrace()
	span := badTrace.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0)
	now := time.Now()
	// Flipping timestamp for a bad duration
	span.SetEndTimestamp(pcommon.NewTimestampFromTime(now))
	span.SetStartTimestamp(pcommon.NewTimestampFromTime(now.Add(sampleLatencyDuration)))
	return badTrace
}

// buildSampleTrace builds the following trace:
//
//	service-a/ping (server) ->
//	  service-a/ping (client) ->
//	    service-b/ping (server)
func buildSampleTrace() ptrace.Traces {
	traces := ptrace.NewTraces()

	initServiceSpans(
		serviceSpans{
			serviceName: "service-a",
			spans: []span{
				{
					operation:  "/ping",
					kind:       ptrace.SpanKindServer,
					statusCode: ptrace.StatusCodeOk,
				},
				{
					operation:  "/ping",
					kind:       ptrace.SpanKindClient,
					statusCode: ptrace.StatusCodeOk,
				},
			},
		}, traces.ResourceSpans().AppendEmpty())
	initServiceSpans(
		serviceSpans{
			serviceName: "service-b",
			spans: []span{
				{
					operation:  "/ping",
					kind:       ptrace.SpanKindServer,
					statusCode: ptrace.StatusCodeError,
				},
			},
		}, traces.ResourceSpans().AppendEmpty())
	initServiceSpans(serviceSpans{}, traces.ResourceSpans().AppendEmpty())
	return traces
}

func initServiceSpans(serviceSpans serviceSpans, spans ptrace.ResourceSpans) {
	if serviceSpans.serviceName != "" {
		spans.Resource().Attributes().PutStr(conventions.AttributeServiceName, serviceSpans.serviceName)
	}

	spans.Resource().Attributes().PutStr(regionResourceAttrName, sampleRegion)

	ils := spans.ScopeSpans().AppendEmpty()
	for _, span := range serviceSpans.spans {
		initSpan(span, ils.Spans().AppendEmpty())
	}
}

func initSpan(span span, s ptrace.Span) {
	s.SetName(span.operation)
	s.SetKind(span.kind)
	s.Status().SetCode(span.statusCode)
	now := time.Now()
	s.SetStartTimestamp(pcommon.NewTimestampFromTime(now))
	s.SetEndTimestamp(pcommon.NewTimestampFromTime(now.Add(sampleLatencyDuration)))

	s.Attributes().PutStr(stringAttrName, "stringAttrValue")
	s.Attributes().PutInt(intAttrName, 99)
	s.Attributes().PutDouble(doubleAttrName, 99.99)
	s.Attributes().PutBool(boolAttrName, true)
	s.Attributes().PutEmpty(nullAttrName)
	s.Attributes().PutEmptyMap(mapAttrName)
	s.Attributes().PutEmptySlice(arrayAttrName)
	s.SetTraceID(pcommon.TraceID([16]byte{byte(42)}))
	s.SetSpanID(pcommon.SpanID([8]byte{byte(42)}))
}

func newOTLPExporters(t *testing.T) (*otlpexporter.Config, component.MetricsExporter, component.TracesExporter) {
	otlpExpFactory := otlpexporter.NewFactory()
	otlpConfig := &otlpexporter.Config{
		ExporterSettings: config.NewExporterSettings(component.NewID("otlp")),
		GRPCClientSettings: configgrpc.GRPCClientSettings{
			Endpoint: "example.com:1234",
		},
	}
	expCreationParams := componenttest.NewNopExporterCreateSettings()
	mexp, err := otlpExpFactory.CreateMetricsExporter(context.Background(), expCreationParams, otlpConfig)
	require.NoError(t, err)
	texp, err := otlpExpFactory.CreateTracesExporter(context.Background(), expCreationParams, otlpConfig)
	require.NoError(t, err)
	return otlpConfig, mexp, texp
}

func TestBuildKeySameServiceOperationCharSequence(t *testing.T) {
	span0 := ptrace.NewSpan()
	span0.SetName("c")
	buf := &bytes.Buffer{}
	buildKey(buf, "ab", span0, nil, pcommon.NewMap())
	k0 := metricKey(buf.String())
	buf.Reset()
	span1 := ptrace.NewSpan()
	span1.SetName("bc")
	buildKey(buf, "a", span1, nil, pcommon.NewMap())
	k1 := metricKey(buf.String())
	assert.NotEqual(t, k0, k1)
	assert.Equal(t, metricKey("ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET"), k0)
	assert.Equal(t, metricKey("a\u0000bc\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET"), k1)
}

func TestBuildKeyWithDimensions(t *testing.T) {
	defaultFoo := pcommon.NewValueStr("bar")
	for _, tc := range []struct {
		name            string
		optionalDims    []dimension
		resourceAttrMap map[string]interface{}
		spanAttrMap     map[string]interface{}
		wantKey         string
	}{
		{
			name:    "nil optionalDims",
			wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET",
		},
		{
			name: "neither span nor resource contains key, dim provides default",
			optionalDims: []dimension{
				{name: "foo", value: &defaultFoo},
			},
			wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u0000bar",
		},
		{
			name: "neither span nor resource contains key, dim provides no default",
			optionalDims: []dimension{
				{name: "foo"},
			},
			wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET",
		},
		{
			name: "span attribute contains dimension",
			optionalDims: []dimension{
				{name: "foo"},
			},
			spanAttrMap: map[string]interface{}{
				"foo": 99,
			},
			wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u000099",
		},
		{
			name: "resource attribute contains dimension",
			optionalDims: []dimension{
				{name: "foo"},
			},
			resourceAttrMap: map[string]interface{}{
				"foo": 99,
			},
			wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u000099",
		},
		{
			name: "both span and resource attribute contains dimension, should prefer span attribute",
			optionalDims: []dimension{
				{name: "foo"},
			},
			spanAttrMap: map[string]interface{}{
				"foo": 100,
			},
			resourceAttrMap: map[string]interface{}{
				"foo": 99,
			},
			wantKey: "ab\u0000c\u0000SPAN_KIND_UNSPECIFIED\u0000STATUS_CODE_UNSET\u0000100",
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			resAttr := pcommon.NewMap()
			assert.NoError(t, resAttr.FromRaw(tc.resourceAttrMap))
			span0 := ptrace.NewSpan()
			assert.NoError(t, span0.Attributes().FromRaw(tc.spanAttrMap))
			span0.SetName("c")
			buf := &bytes.Buffer{}
			buildKey(buf, "ab", span0, tc.optionalDims, resAttr)
			assert.Equal(t, tc.wantKey, buf.String())
		})
	}
}

func TestProcessorDuplicateDimensions(t *testing.T) {
	// Prepare
	factory := NewFactory()
	cfg := factory.CreateDefaultConfig().(*Config)
	// Duplicate dimension with reserved label after sanitization.
	cfg.Dimensions = []Dimension{
		{Name: "status_code"},
	}

	// Test
	next := new(consumertest.TracesSink)
	p, err := newProcessor(zaptest.NewLogger(t), cfg, next)
	assert.Error(t, err)
	assert.Nil(t, p)
}

func TestValidateDimensions(t *testing.T) {
	for _, tc := range []struct {
		name              string
		dimensions        []Dimension
		expectedErr       string
		skipSanitizeLabel bool
	}{
		{
			name:       "no additional dimensions",
			dimensions: []Dimension{},
		},
		{
			name: "no duplicate dimensions",
			dimensions: []Dimension{
				{Name: "http.service_name"},
				{Name: "http.status_code"},
			},
		},
		{
			name: "duplicate dimension with reserved labels",
			dimensions: []Dimension{
				{Name: "service.name"},
			},
			expectedErr: "duplicate dimension name service.name",
		},
		{
			name: "duplicate dimension with reserved labels after sanitization",
			dimensions: []Dimension{
				{Name: "service_name"},
			},
			expectedErr: "duplicate dimension name service_name",
		},
		{
			name: "duplicate additional dimensions",
			dimensions: []Dimension{
				{Name: "service_name"},
				{Name: "service_name"},
			},
			expectedErr: "duplicate dimension name service_name",
		},
		{
			name: "duplicate additional dimensions after sanitization",
			dimensions: []Dimension{
				{Name: "http.status_code"},
				{Name: "http!status_code"},
			},
			expectedErr: "duplicate dimension name http_status_code after sanitization",
		},
		{
			name: "we skip the case if the dimension name is the same after sanitization",
			dimensions: []Dimension{
				{Name: "http_status_code"},
			},
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			tc.skipSanitizeLabel = false
			err := validateDimensions(tc.dimensions, tc.skipSanitizeLabel)
			if tc.expectedErr != "" {
				assert.EqualError(t, err, tc.expectedErr)
			} else {
				assert.NoError(t, err)
			}
		})
	}
}

func TestSanitize(t *testing.T) {
	cfg := createDefaultConfig().(*Config)
	require.Equal(t, "", sanitize("", cfg.skipSanitizeLabel), "")
	require.Equal(t, "key_test", sanitize("_test", cfg.skipSanitizeLabel))
	require.Equal(t, "key__test", sanitize("__test", cfg.skipSanitizeLabel))
	require.Equal(t, "key_0test", sanitize("0test", cfg.skipSanitizeLabel))
	require.Equal(t, "test", sanitize("test", cfg.skipSanitizeLabel))
	require.Equal(t, "test__", sanitize("test_/", cfg.skipSanitizeLabel))
	// testcases with skipSanitizeLabel flag turned on
	cfg.skipSanitizeLabel = true
	require.Equal(t, "", sanitize("", cfg.skipSanitizeLabel), "")
	require.Equal(t, "_test", sanitize("_test", cfg.skipSanitizeLabel))
	require.Equal(t, "key__test", sanitize("__test", cfg.skipSanitizeLabel))
	require.Equal(t, "key_0test", sanitize("0test", cfg.skipSanitizeLabel))
	require.Equal(t, "test", sanitize("test", cfg.skipSanitizeLabel))
	require.Equal(t, "test__", sanitize("test_/", cfg.skipSanitizeLabel))
}

func TestSetExemplars(t *testing.T) {
	// ----- conditions -------------------------------------------------------
	traces := buildSampleTrace()
	traceID := traces.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).TraceID()
	spanID := traces.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).SpanID()
	exemplarSlice := pmetric.NewExemplarSlice()
	timestamp := pcommon.NewTimestampFromTime(time.Now())
	value := float64(42)

	ed := []exemplarData{{traceID: traceID, spanID: spanID, value: value}}

	// ----- call -------------------------------------------------------------
	setExemplars(ed, timestamp, exemplarSlice)

	// ----- verify -----------------------------------------------------------
	traceIDValue := exemplarSlice.At(0).TraceID()
	spanIDValue := exemplarSlice.At(0).SpanID()

	assert.NotEmpty(t, exemplarSlice)
	assert.Equal(t, traceIDValue, traceID)
	assert.Equal(t, spanIDValue, spanID)
	assert.Equal(t, exemplarSlice.At(0).Timestamp(), timestamp)
	assert.Equal(t, exemplarSlice.At(0).DoubleValue(), value)
}

func TestProcessorUpdateExemplars(t *testing.T) {
	// ----- conditions -------------------------------------------------------
	factory := NewFactory()
	cfg := factory.CreateDefaultConfig().(*Config)
	traces := buildSampleTrace()
	traceID := traces.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).TraceID()
	spanID := traces.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).SpanID()
	key := metricKey("metricKey")
	next := new(consumertest.TracesSink)
	p, err := newProcessor(zaptest.NewLogger(t), cfg, next)
	value := float64(42)

	// ----- call -------------------------------------------------------------
	p.updateHistogram(key, value, traceID, spanID)

	// ----- verify -----------------------------------------------------------
	assert.NoError(t, err)
	assert.NotEmpty(t, p.histograms[key].exemplarsData)
	assert.Equal(t, p.histograms[key].exemplarsData[0], exemplarData{traceID: traceID, spanID: spanID, value: value})

	// ----- call -------------------------------------------------------------
	p.resetExemplarData()

	// ----- verify -----------------------------------------------------------
	assert.NoError(t, err)
	assert.Empty(t, p.histograms[key].exemplarsData)
}


text:
#import <React/RCTBridgeModule.h>

@interface RCTImagePickerManager : NSObject <RCTBridgeModule>

@end


text:
package us.reimus.moaplayer;

import java.io.File;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.Random;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
	private MediaPlayer player; 	// Media player
	private ArrayList<Song> songs; 	// Song list
	private int songPosn;			// Current position
	private final IBinder musicBind = new MusicBinder();
	private String songTitle = "";
	private static final int NOTIFY_ID=1;
	private boolean shuffle = false;
	private Random rand;
	private Song songToBeMoved = null;
	private String sdCard = Environment.getExternalStorageDirectory().toString();
	private String targetDirectory = null;

	public void onCreate() {
		// Create the service.
		super.onCreate();
		songPosn = 0;
		player = new MediaPlayer();
		rand = new Random();

		initMusicPlayer();
	}

	@Override
	public void onDestroy() {
		stopForeground(true);
	}

	public void initMusicPlayer() {
		// Set player properties.
		player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
		player.setAudioStreamType(AudioManager.STREAM_MUSIC);

		// Set class listeners.
		player.setOnPreparedListener(this);
		player.setOnCompletionListener(this);
		player.setOnErrorListener(this);
	}

	public void setList(ArrayList<Song> theSongs) {
		songs=theSongs;
	}

	public class MusicBinder extends Binder {
		MusicService getService() {
		    return MusicService.this;
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
	    return musicBind;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		player.stop();
		player.release();
		return false;
	}

	// TODO: To ensure that your app does not interfere with other
	//		 audio services on the user's device, you should enhance
	//		 it to handle audio focus gracefully. Make the Service
	//		 class implement the AudioManager.OnAudioFocusChangeListener
	//		 interface. In the onCreate method, create an instance of
	//		 the AudioManager class and call requestAudioFocus on it.
	//		 Finally, implement the onAudioFocusChange method in your
	//		 class to control what should happen when the application
	//		 gains or loses audio focus. See the Audio Focus section in
	//		 the Developer Guide for more details.
	@Override
	public void onCompletion(MediaPlayer mp) {
		if (player.getCurrentPosition() > 0) {
			mp.reset();
			playNext();
		}
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		mp.reset();
		return false;
	}

	// Copied from: http://code.tutsplus.com/tutorials/create-a-music-player-on-android-user-controls--mobile-22787
	@Override
	public void onPrepared(MediaPlayer mp) {
		// Start playback.
		mp.start();

		// The PendingIntent class will take the user back to the
		// main Activity class when they select the notification.
		Intent notIntent = new Intent(this, MainActivity.class);
		notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent pendInt = PendingIntent.getActivity(this, 0,
				notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

		Notification.Builder builder = new Notification.Builder(this);

		builder.setContentIntent(pendInt)
			.setSmallIcon(R.drawable.play)
			.setTicker(songTitle)
			.setOngoing(true)
			.setContentTitle("Playing")
			.setContentText(songTitle);
		@SuppressWarnings("deprecation")
		Notification not = builder.getNotification(); // For API min used builder.build();

		startForeground(NOTIFY_ID, not);
	}

	public void setDirectory(String directory) {
		// Move song to new directory
		if (songToBeMoved != null) {
			targetDirectory = directory;
			/*
			File sourceLocation = new File (songToBeMoved.getFileLocation());
			File targetLocation = new File (sdCard + "/Music/" + directory);
			try {
				if(sourceLocation.renameTo(targetLocation)) {
					Log.d("dvp", "Move file sucessful.");
				} else {
					Log.d("dvp", "Move file failed.");
				}
			} catch (NullPointerException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}*/
		}
	}

	private String getFileExtention(String fileLocation) {
		int lastIndexOf = fileLocation.lastIndexOf(".");
		if (lastIndexOf == -1) {
			throw new EmptyStackException();
		}
		return fileLocation.substring(lastIndexOf);
	}

	public void moveSong() {
		if ( (songToBeMoved!=null) && (targetDirectory!=null) ) {
			File sourceLocation = new File (songToBeMoved.getFileLocation());
			File targetLocation = new File (sdCard + "/Music/" + targetDirectory + "/" + songToBeMoved.getTitle() + getFileExtention(songToBeMoved.getFileLocation()));
			Log.d("dvp", "SOURCE: " + sourceLocation);
			Log.d("dvp", "TARGET: " + targetLocation);
			try {
				if(sourceLocation.renameTo(targetLocation)) {
					Log.d("dvp", "Move file sucessful.");
				} else {
					Log.d("dvp", "Move file failed.");
				}
			} catch (NullPointerException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// Remove selected directory. BUG
		targetDirectory = null;
	}

	public void playSong() {
		moveSong();

		// Play a song.
		player.reset();
		Song playSong = songs.get(songPosn); // Get song
		songToBeMoved = playSong;
		songTitle = playSong.getTitle();
		long currSong = playSong.getID();	//Get song Id
		Uri trackUri = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong);	// Set URI

		try {
			player.setDataSource(getApplicationContext(), trackUri);
		}
		catch (Exception e) {
			Log.e("MUSIC SERVICE", "Error setting data source", e);
		}
		player.prepareAsync();
	}

	public void setSong(int songIndex) {
		songPosn = songIndex;
	}

	public int getPosn() {
		return player.getCurrentPosition();
	}

	public int getDur() {
		return player.getDuration();
	}

	public boolean isPng() {
		return player.isPlaying();
	}

	public void pausePlayer() {
		player.pause();
	}

	public void seek(int posn) {
		player.seekTo(posn);
	}

	public void go() {
		player.start();
	}

	public void playPrev() {
		songPosn--;
		if (songPosn < 0) songPosn=songs.size()-1;
		playSong();
	}

	public void playNext() {

		if (shuffle) {
			int newSong = songPosn;
			while (newSong == songPosn) {
				newSong = rand.nextInt(songs.size());
			}
			songPosn = newSong;
		}
		else {
			songPosn++;
			if (songPosn >= songs.size()) songPosn = 0;
		}
		playSong();
	}

	// Toggles shuffle setting.
	public void setShuffle() {
		if (shuffle) shuffle = false;
		else shuffle = true;
	}
}


text:
if(!dojo._hasResource["dijit.form.Textarea"]){
dojo._hasResource["dijit.form.Textarea"]=true;
dojo.provide("dijit.form.Textarea");
dojo.require("dijit.form.SimpleTextarea");
dojo.declare("dijit.form.Textarea",dijit.form.SimpleTextarea,{baseClass:"dijitTextBox dijitTextArea dijitExpandingTextArea",cols:"",_previousNewlines:0,_strictMode:(dojo.doc.compatMode!="BackCompat"),_getHeight:function(_1){
var _2=_1.scrollHeight;
if(dojo.isIE){
_2+=_1.offsetHeight-_1.clientHeight-((dojo.isIE<8&&this._strictMode)?dojo._getPadBorderExtents(_1).h:0);
}else{
if(dojo.isMoz){
_2+=_1.offsetHeight-_1.clientHeight;
}else{
if(dojo.isWebKit){
_2+=dojo._getBorderExtents(_1).h;
}else{
_2+=dojo._getPadBorderExtents(_1).h;
}
}
}
return _2;
},_estimateHeight:function(_3){
_3.style.maxHeight="";
_3.style.height="auto";
_3.rows=(_3.value.match(/\n/g)||[]).length+1;
},_needsHelpShrinking:dojo.isMoz||dojo.isWebKit,_onInput:function(){
this.inherited(arguments);
if(this._busyResizing){
return;
}
this._busyResizing=true;
var _4=this.textbox;
if(_4.scrollHeight&&_4.offsetHeight&&_4.clientHeight){
var _5=this._getHeight(_4)+"px";
if(_4.style.height!=_5){
_4.style.maxHeight=_4.style.height=_5;
}
if(this._needsHelpShrinking){
if(this._setTimeoutHandle){
clearTimeout(this._setTimeoutHandle);
}
this._setTimeoutHandle=setTimeout(dojo.hitch(this,"_shrink"),0);
}
}else{
this._estimateHeight(_4);
}
this._busyResizing=false;
},_busyResizing:false,_shrink:function(){
this._setTimeoutHandle=null;
if(this._needsHelpShrinking&&!this._busyResizing){
this._busyResizing=true;
var _6=this.textbox;
var _7=false;
if(_6.value==""){
_6.value=" ";
_7=true;
}
var _8=_6.scrollHeight;
if(!_8){
this._estimateHeight(_6);
}else{
var _9=_6.style.paddingBottom;
var _a=dojo._getPadExtents(_6);
_a=_a.h-_a.t;
_6.style.paddingBottom=_a+1+"px";
var _b=this._getHeight(_6)-1+"px";
if(_6.style.maxHeight!=_b){
_6.style.paddingBottom=_a+_8+"px";
_6.scrollTop=0;
_6.style.maxHeight=this._getHeight(_6)-_8+"px";
}
_6.style.paddingBottom=_9;
}
if(_7){
_6.value="";
}
this._busyResizing=false;
}
},resize:function(){
this._onInput();
},_setValueAttr:function(){
this.inherited(arguments);
this.resize();
},buildRendering:function(){
this.inherited(arguments);
dojo.style(this.textbox,{overflowY:"hidden",overflowX:"auto",boxSizing:"border-box",MsBoxSizing:"border-box",WebkitBoxSizing:"border-box",MozBoxSizing:"border-box"});
},postCreate:function(){
this.inherited(arguments);
this.connect(this.textbox,"onscroll","_onInput");
this.connect(this.textbox,"onresize","_onInput");
this.connect(this.textbox,"onfocus","_onInput");
this._setTimeoutHandle=setTimeout(dojo.hitch(this,"resize"),0);
},uninitialize:function(){
if(this._setTimeoutHandle){
clearTimeout(this._setTimeoutHandle);
}
this.inherited(arguments);
}});
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using FluentSpotifyApi.Extensions;
using FluentSpotifyApi.Model.Browse;

namespace FluentSpotifyApi.Builder.Browse
{
    internal class BrowseFeaturedPlaylistsBuilder : BuilderBase, IBrowseFeaturedPlaylistsBuilder
    {
        public BrowseFeaturedPlaylistsBuilder(BuilderBase parent)
            : base(parent, "featured-playlists".Yield())
        {
        }

        public Task<FeaturedPlaylists> GetAsync(
            string country,
            string locale,
            DateTime? timestamp,
            int? limit,
            int? offset,
            CancellationToken cancellationToken)
        {
            return this.GetAsync<FeaturedPlaylists>(
                cancellationToken,
                queryParams: new { country, locale, timestamp = timestamp?.ToIsoWithUnspecifiedLocation(), limit, offset });
        }
    }
}


text:
package bleve

import (
	_ "github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/blevesearch/bleve/index/store/forestdb"
)


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class MethodAlreadyDisabledFault extends RuntimeFault {
  public String sourceId;

  public String getSourceId() {
    return this.sourceId;
  }

  public void setSourceId(String sourceId) {
    this.sourceId=sourceId;
  }
}


text:
import axios from 'axios';

import * as AuthRepo from './auth/authRepo';

export const METHODS = {
    GET: 'get',
    POST: 'post',
    PUT: 'put',
    DELETE: 'delete'
};

export function _get(url, options = {}) {
    return request({
        method: METHODS.GET,
        url: url,
        ...options
    });
}

export function _post(url, options = {}) {
    return request({
        method: METHODS.POST,
        url: url,
        ...options
    });
}

export function _put(url, options = {}) {
    return request({
        method: METHODS.PUT,
        url: url,
        ...options
    });
}

export function _remove(url, options = {}) {
    return request({
        method: METHODS.DELETE,
        url: url,
        ...options
    }, useAuth);
}

export function request(options) {
    if(!options.headers){
        options.headers = {};
    }

    _fillDefaultHeaders(options.headers);

    let auth = AuthRepo.getAuth();
    if(auth){
        options.headers['Authorization'] = auth.token;
    }

    // add bearer token if we need
    return axios(options).then((response) => {
        // console.log(response);
        return { data: response.data, status: response.status };
    }).catch ((e) => {
        throw e;
    });
}

export default function RestClient(resourceUrl) {
    return {
        getAll: (options = {}) => {
            let url = `${resourceUrl}`;
            return _get(url, options);
        },

        get: (id, options = {}) => {
            let url = `${resourceUrl}/${id}`;
            return _get(url, options);
        },

        post: (entity = {}, options = {}) => {
            options.data = entity;
            let url = `${resourceUrl}`;
            return _post(url, options);
        },

        put: (id, entity = {}, options = {}) => {
            options.data = entity;
            let url = `${resourceUrl}/${id}`;
            return _put(url, options);
        },

        delete: (id, options = {}) => {
            let url = `${resourceUrl}/${id}`;
            return _remove(url, options);
        }
    }
}

const _fillDefaultHeaders = (headers) => {
    const typeJson = `application/json`;
    if (_isEmptyHeader(headers['Accept'])) {
        headers['Accept'] = typeJson;
    }

    if (_isEmptyHeader(headers['Content-Type'])) {
        headers['Content-Type'] = typeJson;
    }
}

const _isEmptyHeader = (header) => {
    return !header || _isEmptyObject(header);
}

// internal helper function
const _isEmptyObject = (obj) => {
    return Object.keys(obj).length === 0 && obj.constructor === Object
}


text:
"""demo_nogui.py - show how to start the Javabridge without a GUI

python-javabridge is licensed under the BSD license.  See the
accompanying file LICENSE for details.

Copyright (c) 2003-2009 Massachusetts Institute of Technology
Copyright (c) 2009-2013 Broad Institute
All rights reserved.

"""

from __future__ import print_function
import os
import javabridge

javabridge.start_vm(run_headless=True)
try:
    print(javabridge.run_script('java.lang.String.format("Hello, %s!", greetee);',
                                dict(greetee='world')))
finally:
    javabridge.kill_vm()


text:
<?php

namespace Swm\Bundle\MailHookBundle\Hook;

interface HookInterface
{
    public function getEvent();

    public function getEmail();

    public function getService();

    public function getMetaData();

    public function getEventDispatched();
}


text:
namespace Google.Cloud.DataCatalog.V1.Snippets
{
    // [START datacatalog_v1_generated_DataCatalog_SetIamPolicy_async_flattened_resourceNames]
    using Google.Api.Gax;
    using Google.Cloud.DataCatalog.V1;
    using Google.Cloud.Iam.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedDataCatalogClientSnippets
    {
        /// <summary>Snippet for SetIamPolicyAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task SetIamPolicyResourceNamesAsync()
        {
            // Create client
            DataCatalogClient dataCatalogClient = await DataCatalogClient.CreateAsync();
            // Initialize request argument(s)
            IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
            Policy policy = new Policy();
            // Make the request
            Policy response = await dataCatalogClient.SetIamPolicyAsync(resource, policy);
        }
    }
    // [END datacatalog_v1_generated_DataCatalog_SetIamPolicy_async_flattened_resourceNames]
}


text:
package de.dfki.asr.compass.model.components;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import de.dfki.asr.compass.model.SceneNodeComponent;
import de.dfki.asr.compass.model.components.annotations.CompassComponent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@CompassComponent(ui = "/components/annotation.xhtml", icon = "apps-accessories-text-editor")
@JsonSubTypes.Type(value = AnnotationComponent.class)
public class AnnotationComponent extends SceneNodeComponent{

	@XmlElementWrapper(name = "text")
	@XmlElementRef
	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "owner", orphanRemoval = true)
	private final List<Annotation> annotations = new ArrayList<>();

	public AnnotationComponent() {
	}

	public List<Annotation> getAnnotations(){
		return Collections.unmodifiableList(annotations);
	}

	public void addAnnotation(Annotation a) {
		if (!annotations.contains(a)) {
			a.setOwner(this);
			annotations.add(a);
		}
	}

	public void removeAnnotationByIndex(int index){
		annotations.remove(index);
	}

	public void removeAnnotation(Annotation a) {
		annotations.remove(a);
	}

	@Override
	public void clearIdsAfterDeepCopy() {
		setId(0);
		for(Annotation annotation : annotations){
			annotation.clearIdsAfterDeepCopy();
		}
	}
}


text:
package com.codepath.simpletodo;

import com.codepath.simpletodo.data.TodoItem;

import java.util.Comparator;

/**
 * Created by mcvjetinovic on 11/17/15.
 */
public class DueDateComparator implements Comparator<TodoItem> {
    @Override
    public int compare(TodoItem lhs, TodoItem rhs) {
        if (lhs.dueDate.before(rhs.dueDate)) {
            return -1;
        }
        else if (lhs.dueDate.after(rhs.dueDate)) {
            return 1;
        }
        else {
            return 0;
        }
    }
}


text:
package eu.com.cwsfe.cms.dao;

import eu.com.cwsfe.cms.DaoTestsConfiguration;
import eu.com.cwsfe.cms.domains.NewsletterMailGroupStatus;
import eu.com.cwsfe.cms.model.Language;
import eu.com.cwsfe.cms.model.NewsletterMailGroup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.IfProfileValue;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@Rollback
@ContextConfiguration(classes = {DaoTestsConfiguration.class, NewsletterMailGroupDAO.class, CmsLanguagesDAO.class})
@IfProfileValue(name = "test-groups", values = {"integration-tests-local"})
public class NewsletterMailGroupDAOTest extends AbstractTransactionalJUnit4SpringContextTests {

    @Autowired
    private NewsletterMailGroupDAO dao;

    @Autowired
    private CmsLanguagesDAO cmsLanguagesDAO;

    private static final Language LANGUAGE_EN = new Language();

    @Before
    public void setUp() throws Exception {
        LANGUAGE_EN.setId(cmsLanguagesDAO.getByCode("en").getId());
    }

    @Test
    public void testCountForAjax() throws Exception {
        //given
        //when
        int result = dao.countForAjax();

        //then
        assertNotNull("query should return non negative value", result);
        assertTrue("query should return non negative value", result >= 0);
    }

    @Test
    public void testList() throws Exception {
        //given
        //when
        List<NewsletterMailGroup> list = dao.list();

        //then
        assertNotNull("Empty results should not return null", list);
        assertTrue(list.isEmpty());
    }

    @Test
    public void testListNewsletterMailGroupsForDropList() throws Exception {
        //given
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        String name = "name";
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());
        dao.add(newsletterMailGroup);

        //when
        List<NewsletterMailGroup> results = dao.listNewsletterMailGroupsForDropList(name, 1);

        //then
        assertNotNull(results);
        assertEquals("Page limit was set to 1", 1, results.size());
    }

    @Test
    public void testListAjax() throws Exception {
        //given
        String name = "name";
        String name2 = "name2";
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());
        dao.add(newsletterMailGroup);
        NewsletterMailGroup newsletterMailGroup2 = new NewsletterMailGroup();
        newsletterMailGroup2.setName(name2);
        newsletterMailGroup2.setLanguageId(LANGUAGE_EN.getId());
        dao.add(newsletterMailGroup2);

        //when
        List<NewsletterMailGroup> list = dao.listAjax(0, 1);

        //then
        assertNotNull("Empty results should not return null", list);
        assertFalse("List should not be empty", list.isEmpty());
        assertEquals("Page limit was set to 1", 1, list.size());
    }

    @Test
    public void testSearchByAjax() throws Exception {
        //given
        String name = "name";
        String otherName = "otherName";
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());
        dao.add(newsletterMailGroup);
        NewsletterMailGroup newsletterMailGroup2 = new NewsletterMailGroup();
        newsletterMailGroup2.setName(otherName);
        newsletterMailGroup2.setStatus(NewsletterMailGroupStatus.NEW);
        newsletterMailGroup2.setLanguageId(LANGUAGE_EN.getId());
        dao.add(newsletterMailGroup2);

        //when
        List<NewsletterMailGroup> list = dao.searchByAjax(0, 1, newsletterMailGroup.getName(), LANGUAGE_EN.getId());

        //then
        assertNotNull("Empty results should not return null", list);
        assertFalse("List should not be empty", list.isEmpty());
        assertEquals("Page limit was set to 1", 1, list.size());
    }

    @Test
    public void testSearchByAjaxCount() throws Exception {
        //given
        String name = "name";
        String otherName = "otherName";
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());
        dao.add(newsletterMailGroup);
        NewsletterMailGroup newsletterMailGroup2 = new NewsletterMailGroup();
        newsletterMailGroup2.setName(otherName);
        newsletterMailGroup2.setLanguageId(LANGUAGE_EN.getId());
        dao.add(newsletterMailGroup2);

        //when
        int result = dao.searchByAjaxCount(newsletterMailGroup.getName(), newsletterMailGroup.getLanguageId());

        //then
        assertNotNull("Results should not return null", result);
        assertTrue("query should return non negative value", result >= 0);
    }

    @Test
    public void testGet() throws Exception {
        //given
        String name = "name";
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());
        Long addedId = dao.add(newsletterMailGroup);

        //when
        NewsletterMailGroup newsletterMailGroupResult = dao.get(addedId);

        //then
        assertNotNull(newsletterMailGroupResult);
        assertEquals((long) addedId, (long) newsletterMailGroupResult.getId());
        assertEquals(name, newsletterMailGroupResult.getName());
        assertEquals(LANGUAGE_EN.getId(), newsletterMailGroupResult.getLanguageId());
    }

    @Test
    public void testGetByNameAndLanguage() throws Exception {
        //given
        String name = "name";
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());
        Long addedId = dao.add(newsletterMailGroup);

        //when
        NewsletterMailGroup newsletterMailGroupResult = dao.getByNameAndLanguage(name, LANGUAGE_EN.getId());

        //then
        assertNotNull(newsletterMailGroupResult);
        assertEquals((long) addedId, (long) newsletterMailGroupResult.getId());
        assertEquals(name, newsletterMailGroupResult.getName());
        assertEquals(LANGUAGE_EN.getId(), newsletterMailGroupResult.getLanguageId());

    }

    @Test
    public void testAdd() throws Exception {
        //given
        String name = "name";
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());

        //when
        Long addedId = dao.add(newsletterMailGroup);

        //then
        NewsletterMailGroup newsletterMailGroupResult = dao.get(addedId);
        assertNotNull(newsletterMailGroupResult);
        assertEquals((long) addedId, (long) newsletterMailGroupResult.getId());
        assertEquals(name, newsletterMailGroupResult.getName());
        assertEquals(LANGUAGE_EN.getId(), newsletterMailGroupResult.getLanguageId());
    }

    @Test
    public void testUpdate() throws Exception {
        //given
        String name = "name";
        String otherName = "otherName";
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());
        Long addedId = dao.add(newsletterMailGroup);
        newsletterMailGroup.setId(addedId);
        newsletterMailGroup.setName(otherName);

        //when
        dao.update(newsletterMailGroup);

        //then
        NewsletterMailGroup newsletterMailGroupResult = dao.get(addedId);
        assertNotNull(newsletterMailGroupResult);
        assertEquals((long) addedId, (long) newsletterMailGroupResult.getId());
        assertEquals(otherName, newsletterMailGroupResult.getName());
        assertEquals(LANGUAGE_EN.getId(), newsletterMailGroupResult.getLanguageId());

    }

    @Test
    public void testDelete() throws Exception {
        //given
        String name = "name";
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());
        Long addedId = dao.add(newsletterMailGroup);
        newsletterMailGroup.setId(addedId);

        //when
        dao.delete(newsletterMailGroup);

        //then
        NewsletterMailGroup newsletterMailGroupResult = dao.get(addedId);
        assertNotNull(newsletterMailGroupResult);
        assertEquals((long) addedId, (long) newsletterMailGroupResult.getId());
        assertEquals("Unexpected status value for deleted object", NewsletterMailGroupStatus.DELETED, newsletterMailGroupResult.getStatus());
    }

    @Test
    public void testUndelete() throws Exception {
        String name = "name";
        NewsletterMailGroup newsletterMailGroup = new NewsletterMailGroup();
        newsletterMailGroup.setName(name);
        newsletterMailGroup.setLanguageId(LANGUAGE_EN.getId());
        Long addedId = dao.add(newsletterMailGroup);
        newsletterMailGroup.setId(addedId);

        //when
        dao.undelete(newsletterMailGroup);

        //then
        NewsletterMailGroup newsletterMailGroupResult = dao.get(addedId);
        assertNotNull(newsletterMailGroupResult);
        assertEquals((long) addedId, (long) newsletterMailGroupResult.getId());
        assertEquals("Unexpected status for undeleted object", NewsletterMailGroupStatus.NEW, newsletterMailGroupResult.getStatus());
    }
}


text:
<?php
/**
 *
 * Pre-filters source text in the preparation phase.
 *
 * @category Solar
 *
 * @package Markdown
 *
 * @author John Gruber <http://daringfireball.net/projects/markdown/>
 *
 * @author Michel Fortin <http://www.michelf.com/projects/php-markdown/>
 *
 * @author Paul M. Jones <pmjones@solarphp.com>
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 * @version $Id: Prefilter.php 3153 2008-05-05 23:14:16Z pmjones $
 *
 */
namespace PEAR2\Text;

class Markdown_Plugin_Prefilter extends Markdown_Plugin
{
    /**
     *
     * Run this plugin during the "prepare" phase.
     *
     * @var bool
     *
     */
    protected $_is_prepare = true;

    /**
     *
     * Pre-filters source text in the preparation phase.
     *
     * Converts DOS and Mac OS pre-X line endings to Unix line endings,
     * adds 2 newlines to the end of the source, and converts all
     * whitespace-only lines to simple newlines.  Also converts tabs
     * to spaces intelligently, keeping tab columns lined up.
     *
     * @param string $text The source text.
     *
     * @return string $text The text after being filtered.
     *
     */
    public function prepare($text)
    {
        // Standardize DOS and Mac OS 9 line endings
        $text = str_replace(array("\r\n", "\r"), "\n", $text);

        // Make sure $text ends with a couple of newlines:
        $text .= "\n\n";

        // Convert tabs to spaces in a surprisingly nice-looking way.
        $text = $this->_tabsToSpaces($text);

        // Convert lines consisting only of spaces and tabs to simple
        // newlines.
        //
        // This makes subsequent regexen easier to write, because we can
        // match consecutive blank lines with /\n+/ instead of something
        // contorted like /[ \t]*\n+/ .
        $text = preg_replace('/^[ \t]+$/m', '', $text);

        // done
        return $text;
    }

    /**
     *
     * Replaces tabs with the appropriate number of spaces.
     *
     * <http://www.mail-archive.com/macperl-anyperl@perl.org/msg00144.html>
     *
     * > It will take into account the length of the string before the tab
     * > starting from the start of the string, from the previous newline, or
     * > from the last replaced tab; and pad with 1 to 4 spaces so the string
     * > length becomes the next multiple of 4.
     *
     * @param string $text A block of text with tabs.
     *
     * @return string The same block of text, with tabs converted to
     * spaces so that columns still line up.
     *
     */
    protected function _tabsToSpaces($text)
    {
        // For each line we separate the line in blocks delemited by
        // tab characters. Then we reconstruct every line by adding the
        // appropriate number of space between each blocks.
        $lines = explode("\n", $text);
        $text = "";
        $tab_width = $this->_getTabWidth();

        foreach ($lines as $line) {
            // Split in blocks.
            $blocks = explode("\t", $line);
            // Add each blocks to the line.
            $line = $blocks[0];
            unset($blocks[0]); # Do not add first block twice.
            foreach ($blocks as $block) {
                // Calculate width, insert spaces, insert block.
                $amount = $tab_width - strlen($line) % $tab_width;
                $line .= str_repeat(" ", $amount) . $block;
            }
            $text .= "$line\n";
        }
        return $text;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<metamorph xmlns="http://www.culturegraph.org/metamorph"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1">

	<rules>
		<combine name="ok"
			value="" reset="true">
			<data source="refed"/>
			<data source="ok" />
		</combine>
	</rules>
</metamorph>


text:
class AddCreditCardOrderNumber < ActiveRecord::Migration
  def change
    add_column :pay_credit_cards, :order_id, :integer
    add_column :pay_credit_cards, :issue_date, :string
    add_column :pay_credit_cards, :issue_number, :string
  end
end


text:
import unittest
import subprocess
import os

class TestCliRolePaths(unittest.TestCase):
    def setUp(self):
        self.local_test_dir = os.path.dirname(os.path.realpath(__file__))

    def run_ansible_lint(self, cwd, bin, role_path):
        command = '{} {}'.format(bin, role_path)

        result, err = subprocess.Popen(
            [command],
            cwd=cwd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True
        ).communicate()

        self.assertFalse(err, 'Expected no error but was ' + str(err))

        return result

    def test_run_single_role_path_no_trailing_slash(self):
        cwd = self.local_test_dir
        bin = '../bin/ansible-lint'
        role_path = 'test-role'

        result = self.run_ansible_lint(cwd=cwd, bin=bin, role_path=role_path)
        self.assertIn('Use shell only when shell functionality is required',
                      str(result))

    def test_run_single_role_path_with_trailing_slash(self):
        cwd = self.local_test_dir
        bin = '../bin/ansible-lint'
        role_path = 'test-role/'

        result = self.run_ansible_lint(cwd=cwd, bin=bin, role_path=role_path)
        self.assertIn('Use shell only when shell functionality is required',
                      str(result))

    def test_run_multiple_role_path_no_trailing_slash(self):
        cwd = self.local_test_dir
        bin = '../bin/ansible-lint'
        role_path = 'roles/test-role'

        result = self.run_ansible_lint(cwd=cwd, bin=bin, role_path=role_path)
        self.assertIn('Use shell only when shell functionality is required',
                      str(result))

    def test_run_multiple_role_path_with_trailing_slash(self):
        cwd = self.local_test_dir
        bin = '../bin/ansible-lint'
        role_path = 'roles/test-role/'

        result = self.run_ansible_lint(cwd=cwd, bin=bin, role_path=role_path)
        self.assertIn('Use shell only when shell functionality is required',
                      str(result))

    def test_run_inside_role_dir(self):
        cwd = os.path.join(self.local_test_dir, 'test-role/')
        bin = '../../bin/ansible-lint'
        role_path = '.'

        result = self.run_ansible_lint(cwd=cwd, bin=bin, role_path=role_path)
        self.assertIn('Use shell only when shell functionality is required',
                      str(result))

    def test_run_role_three_dir_deep(self):
        cwd = self.local_test_dir
        bin = '../bin/ansible-lint'
        role_path = 'roles/roles/test-role'

        result = self.run_ansible_lint(cwd=cwd, bin=bin, role_path=role_path)
        self.assertIn('Use shell only when shell functionality is required',
                      str(result))


text:
/*
 * Author: Kim Min-Ho (ISKU)
 * Date: 2016.08.26
 * email: minho1a@hanmail.net
 *
 * https://github.com/ISKU/Algorithm
 * https://www.acmicpc.net/problem/10569
 */

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		for (int testCase = input.nextInt(); testCase > 0; testCase--)
			System.out.println(Math.abs(input.nextInt() - input.nextInt() - 2));
	}
}