text:
/* @flow */
/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

import { GraphQLError, locatedError } from '../error';
import find from '../jsutils/find';
import invariant from '../jsutils/invariant';
import isNullish from '../jsutils/isNullish';
import { typeFromAST } from '../utilities/typeFromAST';
import { Kind } from '../language';
import { getVariableValues, getArgumentValues } from './values';
import {
  GraphQLScalarType,
  GraphQLObjectType,
  GraphQLEnumType,
  GraphQLList,
  GraphQLNonNull,
  GraphQLInterfaceType,
  GraphQLUnionType,
  isAbstractType
} from '../type/definition';
import type {
  GraphQLType,
  GraphQLLeafType,
  GraphQLAbstractType,
  GraphQLFieldDefinition,
  GraphQLFieldResolveFn,
  GraphQLResolveInfo,
} from '../type/definition';
import { GraphQLSchema } from '../type/schema';
import {
  SchemaMetaFieldDef,
  TypeMetaFieldDef,
  TypeNameMetaFieldDef
} from '../type/introspection';
import {
  GraphQLIncludeDirective,
  GraphQLSkipDirective
} from '../type/directives';
import type {
  Directive,
  Document,
  OperationDefinition,
  SelectionSet,
  Field,
  InlineFragment,
  FragmentDefinition
} from '../language/ast';

/**
 * Terminology
 *
 * "Definitions" are the generic name for top-level statements in the document.
 * Examples of this include:
 * 1) Operations (such as a query)
 * 2) Fragments
 *
 * "Operations" are a generic name for requests in the document.
 * Examples of this include:
 * 1) query,
 * 2) mutation
 *
 * "Selections" are the definitions that can appear legally and at
 * single level of the query. These include:
 * 1) field references e.g "a"
 * 2) fragment "spreads" e.g. "...c"
 * 3) inline fragment "spreads" e.g. "...on Type { a }"
 */

/**
 * Data that must be available at all points during query execution.
 *
 * Namely, schema of the type system that is currently executing,
 * and the fragments defined in the query document
 */
type ExecutionContext = {
  schema: GraphQLSchema;
  fragments: {[key: string]: FragmentDefinition};
  rootValue: mixed;
  contextValue: mixed;
  operation: OperationDefinition;
  variableValues: {[key: string]: mixed};
  errors: Array<GraphQLError>;
}

/**
 * The result of execution. `data` is the result of executing the
 * query, `errors` is null if no errors occurred, and is a
 * non-empty array if an error occurred.
 */
type ExecutionResult = {
  data: ?Object;
  errors?: Array<GraphQLError>;
}

/**
 * Implements the "Evaluating requests" section of the GraphQL specification.
 *
 * Returns a Promise that will eventually be resolved and never rejected.
 *
 * If the arguments to this function do not result in a legal execution context,
 * a GraphQLError will be thrown immediately explaining the invalid input.
 */
export function execute(
  schema: GraphQLSchema,
  documentAST: Document,
  rootValue?: mixed,
  contextValue?: mixed,
  variableValues?: ?{[key: string]: mixed},
  operationName?: ?string
): Promise<ExecutionResult> {
  invariant(schema, 'Must provide schema');
  invariant(
    schema instanceof GraphQLSchema,
    'Schema must be an instance of GraphQLSchema. Also ensure that there are ' +
    'not multiple versions of GraphQL installed in your node_modules directory.'
  );

  // If a valid context cannot be created due to incorrect arguments,
  // this will throw an error.
  const context = buildExecutionContext(
    schema,
    documentAST,
    rootValue,
    contextValue,
    variableValues,
    operationName
  );

  // Return a Promise that will eventually resolve to the data described by
  // The "Response" section of the GraphQL specification.
  //
  // If errors are encountered while executing a GraphQL field, only that
  // field and its descendants will be omitted, and sibling fields will still
  // be executed. An execution which encounters errors will still result in a
  // resolved Promise.
  return new Promise(resolve => {
    resolve(executeOperation(context, context.operation, rootValue));
  }).catch(error => {
    // Errors from sub-fields of a NonNull type may propagate to the top level,
    // at which point we still log the error and null the parent field, which
    // in this case is the entire response.
    context.errors.push(error);
    return null;
  }).then(data => {
    if (!context.errors.length) {
      return { data };
    }
    return { data, errors: context.errors };
  });
}

/**
 * Constructs a ExecutionContext object from the arguments passed to
 * execute, which we will pass throughout the other execution methods.
 *
 * Throws a GraphQLError if a valid execution context cannot be created.
 */
function buildExecutionContext(
  schema: GraphQLSchema,
  documentAST: Document,
  rootValue: mixed,
  contextValue: mixed,
  rawVariableValues: ?{[key: string]: mixed},
  operationName: ?string
): ExecutionContext {
  const errors: Array<GraphQLError> = [];
  let operation: ?OperationDefinition;
  const fragments: {[name: string]: FragmentDefinition} = Object.create(null);
  documentAST.definitions.forEach(definition => {
    switch (definition.kind) {
      case Kind.OPERATION_DEFINITION:
        if (!operationName && operation) {
          throw new GraphQLError(
            'Must provide operation name if query contains multiple operations.'
          );
        }
        if (!operationName ||
            definition.name && definition.name.value === operationName) {
          operation = definition;
        }
        break;
      case Kind.FRAGMENT_DEFINITION:
        fragments[definition.name.value] = definition;
        break;
      default: throw new GraphQLError(
        `GraphQL cannot execute a request containing a ${definition.kind}.`,
        definition
      );
    }
  });
  if (!operation) {
    if (operationName) {
      throw new GraphQLError(`Unknown operation named "${operationName}".`);
    } else {
      throw new GraphQLError('Must provide an operation.');
    }
  }
  const variableValues = getVariableValues(
    schema,
    operation.variableDefinitions || [],
    rawVariableValues || {}
  );

  return {
    schema,
    fragments,
    rootValue,
    contextValue,
    operation,
    variableValues,
    errors
  };
}

/**
 * Implements the "Evaluating operations" section of the spec.
 */
function executeOperation(
  exeContext: ExecutionContext,
  operation: OperationDefinition,
  rootValue: mixed
): Object {
  const type = getOperationRootType(exeContext.schema, operation);
  const fields = collectFields(
    exeContext,
    type,
    operation.selectionSet,
    Object.create(null),
    Object.create(null)
  );

  if (operation.operation === 'mutation') {
    return executeFieldsSerially(exeContext, type, rootValue, fields);
  }
  return executeFields(exeContext, type, rootValue, fields);
}

/**
 * Extracts the root type of the operation from the schema.
 */
function getOperationRootType(
  schema: GraphQLSchema,
  operation: OperationDefinition
): GraphQLObjectType {
  switch (operation.operation) {
    case 'query':
      return schema.getQueryType();
    case 'mutation':
      const mutationType = schema.getMutationType();
      if (!mutationType) {
        throw new GraphQLError(
          'Schema is not configured for mutations',
          [ operation ]
        );
      }
      return mutationType;
    case 'subscription':
      const subscriptionType = schema.getSubscriptionType();
      if (!subscriptionType) {
        throw new GraphQLError(
          'Schema is not configured for subscriptions',
          [ operation ]
        );
      }
      return subscriptionType;
    default:
      throw new GraphQLError(
        'Can only execute queries, mutations and subscriptions',
        [ operation ]
      );
  }
}

/**
 * Implements the "Evaluating selection sets" section of the spec
 * for "write" mode.
 */
function executeFieldsSerially(
  exeContext: ExecutionContext,
  parentType: GraphQLObjectType,
  sourceValue: mixed,
  fields: {[key: string]: Array<Field>}
): Promise<Object> {
  return Object.keys(fields).reduce(
    (prevPromise, responseName) => prevPromise.then(results => {
      const fieldASTs = fields[responseName];
      const result = resolveField(
        exeContext,
        parentType,
        sourceValue,
        fieldASTs
      );
      if (result === undefined) {
        return results;
      }
      if (isThenable(result)) {
        return ((result: any): Promise).then(resolvedResult => {
          results[responseName] = resolvedResult;
          return results;
        });
      }
      results[responseName] = result;
      return results;
    }),
    Promise.resolve({})
  );
}

/**
 * Implements the "Evaluating selection sets" section of the spec
 * for "read" mode.
 */
function executeFields(
  exeContext: ExecutionContext,
  parentType: GraphQLObjectType,
  sourceValue: mixed,
  fields: {[key: string]: Array<Field>}
): Object {
  let containsPromise = false;

  const finalResults = Object.keys(fields).reduce(
    (results, responseName) => {
      const fieldASTs = fields[responseName];
      const result = resolveField(
        exeContext,
        parentType,
        sourceValue,
        fieldASTs
      );
      if (result === undefined) {
        return results;
      }
      results[responseName] = result;
      if (isThenable(result)) {
        containsPromise = true;
      }
      return results;
    },
    Object.create(null)
  );

  // If there are no promises, we can just return the object
  if (!containsPromise) {
    return finalResults;
  }

  // Otherwise, results is a map from field name to the result
  // of resolving that field, which is possibly a promise. Return
  // a promise that will return this same map, but with any
  // promises replaced with the values they resolved to.
  return promiseForObject(finalResults);
}

/**
 * Given a selectionSet, adds all of the fields in that selection to
 * the passed in map of fields, and returns it at the end.
 *
 * CollectFields requires the "runtime type" of an object. For a field which
 * returns and Interface or Union type, the "runtime type" will be the actual
 * Object type returned by that field.
 */
function collectFields(
  exeContext: ExecutionContext,
  runtimeType: GraphQLObjectType,
  selectionSet: SelectionSet,
  fields: {[key: string]: Array<Field>},
  visitedFragmentNames: {[key: string]: boolean}
): {[key: string]: Array<Field>} {
  for (let i = 0; i < selectionSet.selections.length; i++) {
    const selection = selectionSet.selections[i];
    switch (selection.kind) {
      case Kind.FIELD:
        if (!shouldIncludeNode(exeContext, selection.directives)) {
          continue;
        }
        const name = getFieldEntryKey(selection);
        if (!fields[name]) {
          fields[name] = [];
        }
        fields[name].push(selection);
        break;
      case Kind.INLINE_FRAGMENT:
        if (!shouldIncludeNode(exeContext, selection.directives) ||
            !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {
          continue;
        }
        collectFields(
          exeContext,
          runtimeType,
          selection.selectionSet,
          fields,
          visitedFragmentNames
        );
        break;
      case Kind.FRAGMENT_SPREAD:
        const fragName = selection.name.value;
        if (visitedFragmentNames[fragName] ||
            !shouldIncludeNode(exeContext, selection.directives)) {
          continue;
        }
        visitedFragmentNames[fragName] = true;
        const fragment = exeContext.fragments[fragName];
        if (!fragment ||
            !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {
          continue;
        }
        collectFields(
          exeContext,
          runtimeType,
          fragment.selectionSet,
          fields,
          visitedFragmentNames
        );
        break;
    }
  }
  return fields;
}

/**
 * Determines if a field should be included based on the @include and @skip
 * directives, where @skip has higher precidence than @include.
 */
function shouldIncludeNode(
  exeContext: ExecutionContext,
  directives: ?Array<Directive>
): boolean {
  const skipAST = directives && find(
    directives,
    directive => directive.name.value === GraphQLSkipDirective.name
  );
  if (skipAST) {
    const { if: skipIf } = getArgumentValues(
      GraphQLSkipDirective.args,
      skipAST.arguments,
      exeContext.variableValues
    );
    if (skipIf === true) {
      return false;
    }
  }

  const includeAST = directives && find(
    directives,
    directive => directive.name.value === GraphQLIncludeDirective.name
  );
  if (includeAST) {
    const { if: includeIf } = getArgumentValues(
      GraphQLIncludeDirective.args,
      includeAST.arguments,
      exeContext.variableValues
    );
    if (includeIf === false) {
      return false;
    }
  }

  return true;
}

/**
 * Determines if a fragment is applicable to the given type.
 */
function doesFragmentConditionMatch(
  exeContext: ExecutionContext,
  fragment: FragmentDefinition | InlineFragment,
  type: GraphQLObjectType
): boolean {
  const typeConditionAST = fragment.typeCondition;
  if (!typeConditionAST) {
    return true;
  }
  const conditionalType = typeFromAST(exeContext.schema, typeConditionAST);
  if (conditionalType === type) {
    return true;
  }
  if (isAbstractType(conditionalType)) {
    const abstractType = ((conditionalType: any): GraphQLAbstractType);
    return exeContext.schema.isPossibleType(abstractType, type);
  }
  return false;
}

/**
 * This function transforms a JS object `{[key: string]: Promise<T>}` into
 * a `Promise<{[key: string]: T}>`
 *
 * This is akin to bluebird's `Promise.props`, but implemented only using
 * `Promise.all` so it will work with any implementation of ES6 promises.
 */
function promiseForObject<T>(
  object: {[key: string]: Promise<T>}
): Promise<{[key: string]: T}> {
  const keys = Object.keys(object);
  const valuesAndPromises = keys.map(name => object[name]);
  return Promise.all(valuesAndPromises).then(
    values => values.reduce((resolvedObject, value, i) => {
      resolvedObject[keys[i]] = value;
      return resolvedObject;
    }, Object.create(null))
  );
}

/**
 * Implements the logic to compute the key of a given field's entry
 */
function getFieldEntryKey(node: Field): string {
  return node.alias ? node.alias.value : node.name.value;
}

/**
 * Resolves the field on the given source object. In particular, this
 * figures out the value that the field returns by calling its resolve function,
 * then calls completeValue to complete promises, serialize scalars, or execute
 * the sub-selection-set for objects.
 */
function resolveField(
  exeContext: ExecutionContext,
  parentType: GraphQLObjectType,
  source: mixed,
  fieldASTs: Array<Field>
): mixed {
  const fieldAST = fieldASTs[0];
  const fieldName = fieldAST.name.value;

  const fieldDef = getFieldDef(exeContext.schema, parentType, fieldName);
  if (!fieldDef) {
    return;
  }

  const returnType = fieldDef.type;
  const resolveFn = fieldDef.resolve || defaultResolveFn;

  // Build a JS object of arguments from the field.arguments AST, using the
  // variables scope to fulfill any variable references.
  // TODO: find a way to memoize, in case this field is within a List type.
  const args = getArgumentValues(
    fieldDef.args,
    fieldAST.arguments,
    exeContext.variableValues
  );

  // The resolve function's optional third argument is a context value that
  // is provided to every resolve function within an execution. It is commonly
  // used to represent an authenticated user, or request-specific caches.
  const context = exeContext.contextValue;

  // The resolve function's optional fourth argument is a collection of
  // information about the current execution state.
  const info: GraphQLResolveInfo = {
    fieldName,
    fieldASTs,
    returnType,
    parentType,
    schema: exeContext.schema,
    fragments: exeContext.fragments,
    rootValue: exeContext.rootValue,
    operation: exeContext.operation,
    variableValues: exeContext.variableValues,
  };

  // Get the resolve function, regardless of if its result is normal
  // or abrupt (error).
  const result = resolveOrError(resolveFn, source, args, context, info);

  return completeValueCatchingError(
    exeContext,
    returnType,
    fieldASTs,
    info,
    result
  );
}

// Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`
// function. Returns the result of resolveFn or the abrupt-return Error object.
function resolveOrError(
  resolveFn: GraphQLFieldResolveFn,
  source: mixed,
  args: { [key: string]: mixed },
  context: mixed,
  info: GraphQLResolveInfo
): Error | mixed {
  try {
    return resolveFn(source, args, context, info);
  } catch (error) {
    // Sometimes a non-error is thrown, wrap it as an Error for a
    // consistent interface.
    return error instanceof Error ? error : new Error(error);
  }
}

// This is a small wrapper around completeValue which detects and logs errors
// in the execution context.
function completeValueCatchingError(
  exeContext: ExecutionContext,
  returnType: GraphQLType,
  fieldASTs: Array<Field>,
  info: GraphQLResolveInfo,
  result: mixed
): mixed {
  // If the field type is non-nullable, then it is resolved without any
  // protection from errors.
  if (returnType instanceof GraphQLNonNull) {
    return completeValue(exeContext, returnType, fieldASTs, info, result);
  }

  // Otherwise, error protection is applied, logging the error and resolving
  // a null value for this field if one is encountered.
  try {
    const completed = completeValue(
      exeContext,
      returnType,
      fieldASTs,
      info,
      result
    );
    if (isThenable(completed)) {
      // If `completeValue` returned a rejected promise, log the rejection
      // error and resolve to null.
      // Note: we don't rely on a `catch` method, but we do expect "thenable"
      // to take a second callback for the error case.
      return ((completed: any): Promise).then(undefined, error => {
        exeContext.errors.push(error);
        return Promise.resolve(null);
      });
    }
    return completed;
  } catch (error) {
    // If `completeValue` returned abruptly (threw an error), log the error
    // and return null.
    exeContext.errors.push(error);
    return null;
  }
}

/**
 * Implements the instructions for completeValue as defined in the
 * "Field entries" section of the spec.
 *
 * If the field type is Non-Null, then this recursively completes the value
 * for the inner type. It throws a field error if that completion returns null,
 * as per the "Nullability" section of the spec.
 *
 * If the field type is a List, then this recursively completes the value
 * for the inner type on each item in the list.
 *
 * If the field type is a Scalar or Enum, ensures the completed value is a legal
 * value of the type by calling the `serialize` method of GraphQL type
 * definition.
 *
 * If the field is an abstract type, determine the runtime type of the value
 * and then complete based on that type
 *
 * Otherwise, the field type expects a sub-selection set, and will complete the
 * value by evaluating all sub-selections.
 */
function completeValue(
  exeContext: ExecutionContext,
  returnType: GraphQLType,
  fieldASTs: Array<Field>,
  info: GraphQLResolveInfo,
  result: mixed
): mixed {
  // If result is a Promise, apply-lift over completeValue.
  if (isThenable(result)) {
    return ((result: any): Promise).then(
      // Once resolved to a value, complete that value.
      resolved => completeValue(
        exeContext,
        returnType,
        fieldASTs,
        info,
        resolved
      ),
      // If rejected, create a located error, and continue to reject.
      error => Promise.reject(locatedError(error, fieldASTs))
    );
  }

  // If result is an Error, throw a located error.
  if (result instanceof Error) {
    throw locatedError(result, fieldASTs);
  }

  // If field type is NonNull, complete for inner type, and throw field error
  // if result is null.
  if (returnType instanceof GraphQLNonNull) {
    const completed = completeValue(
      exeContext,
      returnType.ofType,
      fieldASTs,
      info,
      result
    );
    if (completed === null) {
      throw new GraphQLError(
        `Cannot return null for non-nullable field ${
          info.parentType}.${info.fieldName}.`,
        fieldASTs
      );
    }
    return completed;
  }

  // If result value is null-ish (null, undefined, or NaN) then return null.
  if (isNullish(result)) {
    return null;
  }

  // If field type is List, complete each item in the list with the inner type
  if (returnType instanceof GraphQLList) {
    return completeListValue(exeContext, returnType, fieldASTs, info, result);
  }

  // If field type is a leaf type, Scalar or Enum, serialize to a valid value,
  // returning null if serialization is not possible.
  if (returnType instanceof GraphQLScalarType ||
      returnType instanceof GraphQLEnumType) {
    return completeLeafValue(returnType, result);
  }

  // If field type is an abstract type, Interface or Union, determine the
  // runtime Object type and complete for that type.
  if (returnType instanceof GraphQLInterfaceType ||
      returnType instanceof GraphQLUnionType) {
    return completeAbstractValue(
      exeContext,
      returnType,
      fieldASTs,
      info,
      result
    );
  }

  // If field type is Object, execute and complete all sub-selections.
  if (returnType instanceof GraphQLObjectType) {
    return completeObjectValue(
      exeContext,
      returnType,
      fieldASTs,
      info,
      result
    );
  }

  // Not reachable. All possible output types have been considered.
  invariant(
    false,
    `Cannot complete value of unexpected type "${returnType}".`
  );
}

/**
 * Complete a list value by completing each item in the list with the
 * inner type
 */
function completeListValue(
  exeContext: ExecutionContext,
  returnType: GraphQLList,
  fieldASTs: Array<Field>,
  info: GraphQLResolveInfo,
  result: mixed
): mixed {
  invariant(
    Array.isArray(result),
    `User Error: expected iterable, but did not find one for field ${
      info.parentType}.${info.fieldName}.`
  );

  // This is specified as a simple map, however we're optimizing the path
  // where the list contains no Promises by avoiding creating another Promise.
  const itemType = returnType.ofType;
  let containsPromise = false;
  const completedResults = result.map(item => {
    const completedItem =
      completeValueCatchingError(exeContext, itemType, fieldASTs, info, item);
    if (!containsPromise && isThenable(completedItem)) {
      containsPromise = true;
    }
    return completedItem;
  });

  return containsPromise ? Promise.all(completedResults) : completedResults;
}

/**
 * Complete a Scalar or Enum by serializing to a valid value, returning
 * null if serialization is not possible.
 */
function completeLeafValue(
  returnType: GraphQLLeafType,
  result: mixed
): mixed {
  invariant(returnType.serialize, 'Missing serialize method on type');
  const serializedResult = returnType.serialize(result);
  return isNullish(serializedResult) ? null : serializedResult;
}

/**
 * Complete a value of an abstract type by determining the runtime object type
 * of that value, then complete the value for that type.
 */
function completeAbstractValue(
  exeContext: ExecutionContext,
  returnType: GraphQLAbstractType,
  fieldASTs: Array<Field>,
  info: GraphQLResolveInfo,
  result: mixed
): mixed {
  const runtimeType = returnType.resolveType ?
    returnType.resolveType(result, exeContext.contextValue, info) :
    defaultResolveTypeFn(result, exeContext.contextValue, info, returnType);

  if (!(runtimeType instanceof GraphQLObjectType)) {
    throw new GraphQLError(
      `Abstract type ${returnType} must resolve to an Object type at runtime ` +
      `for field ${info.parentType}.${info.fieldName} with value "${result}",` +
      `received "${runtimeType}".`,
      fieldASTs
    );
  }

  if (!exeContext.schema.isPossibleType(returnType, runtimeType)) {
    throw new GraphQLError(
      `Runtime Object type "${runtimeType}" is not a possible type ` +
      `for "${returnType}".`,
      fieldASTs
    );
  }

  return completeObjectValue(
    exeContext,
    runtimeType,
    fieldASTs,
    info,
    result
  );
}

/**
 * Complete an Object value by executing all sub-selections.
 */
function completeObjectValue(
  exeContext: ExecutionContext,
  returnType: GraphQLObjectType,
  fieldASTs: Array<Field>,
  info: GraphQLResolveInfo,
  result: mixed
): mixed {
  // If there is an isTypeOf predicate function, call it with the
  // current result. If isTypeOf returns false, then raise an error rather
  // than continuing execution.
  if (returnType.isTypeOf &&
      !returnType.isTypeOf(result, exeContext.contextValue, info)) {
    throw new GraphQLError(
      `Expected value of type "${returnType}" but got: ${result}.`,
      fieldASTs
    );
  }

  // Collect sub-fields to execute to complete this value.
  let subFieldASTs = Object.create(null);
  const visitedFragmentNames = Object.create(null);
  for (let i = 0; i < fieldASTs.length; i++) {
    const selectionSet = fieldASTs[i].selectionSet;
    if (selectionSet) {
      subFieldASTs = collectFields(
        exeContext,
        returnType,
        selectionSet,
        subFieldASTs,
        visitedFragmentNames
      );
    }
  }

  return executeFields(exeContext, returnType, result, subFieldASTs);
}

/**
 * If a resolveType function is not given, then a default resolve behavior is
 * used which tests each possible type for the abstract type by calling
 * isTypeOf for the object being coerced, returning the first type that matches.
 */
function defaultResolveTypeFn(
  value: mixed,
  context: mixed,
  info: GraphQLResolveInfo,
  abstractType: GraphQLAbstractType
): ?GraphQLObjectType {
  const possibleTypes = info.schema.getPossibleTypes(abstractType);
  for (let i = 0; i < possibleTypes.length; i++) {
    const type = possibleTypes[i];
    if (type.isTypeOf && type.isTypeOf(value, context, info)) {
      return type;
    }
  }
}

/**
 * If a resolve function is not given, then a default resolve behavior is used
 * which takes the property of the source object of the same name as the field
 * and returns it as the result, or if it's a function, returns the result
 * of calling that function.
 */
function defaultResolveFn(source: any, args, context, { fieldName }) {
  // ensure source is a value for which property access is acceptable.
  if (typeof source === 'object' || typeof source === 'function') {
    const property = source[fieldName];
    return typeof property === 'function' ? source[fieldName]() : property;
  }
}

/**
 * Checks to see if this object acts like a Promise, i.e. has a "then"
 * function.
 */
function isThenable(value: mixed): boolean {
  return typeof value === 'object' &&
    value !== null &&
    typeof value.then === 'function';
}

/**
 * This method looks up the field on the given type defintion.
 * It has special casing for the two introspection fields, __schema
 * and __typename. __typename is special because it can always be
 * queried as a field, even in situations where no other fields
 * are allowed, like on a Union. __schema could get automatically
 * added to the query type, but that would require mutating type
 * definitions, which would cause issues.
 */
function getFieldDef(
  schema: GraphQLSchema,
  parentType: GraphQLObjectType,
  fieldName: string
): ?GraphQLFieldDefinition {
  if (fieldName === SchemaMetaFieldDef.name &&
      schema.getQueryType() === parentType) {
    return SchemaMetaFieldDef;
  } else if (fieldName === TypeMetaFieldDef.name &&
             schema.getQueryType() === parentType) {
    return TypeMetaFieldDef;
  } else if (fieldName === TypeNameMetaFieldDef.name) {
    return TypeNameMetaFieldDef;
  }
  return parentType.getFields()[fieldName];
}


text:
// This file was automatically generated by the code gen tool - do not modify.

using System ;
using scg = System.Collections.Generic ;
using sd = System.Data ;
using sds = System.Data.SqlClient ;
using sr = System.Reflection ;
using mst = Microsoft.SqlServer.Types ;
using mss = Microsoft.SqlServer.Server ;
using acr = alby.codegen.runtime ;
using ns = alby.northwind.codegen;

namespace alby.northwind.codegen.table
{
	public partial class TestTable5Factory : acr.FactoryBase< TestTable5, ns.database.NorthwindDatabaseSingletonHelper, ns.database.NorthwindDatabase >
	{
		static TestTable5Factory()
		{
			_assemblyˡ = sr.Assembly.GetExecutingAssembly() ;
			_schemaˡ = "dbo" ;
			_tableˡ = "TestTable5" ;
			_selectˡ = "select * from {0} t " ;
			_insertˡ = "insert {0} ( [f_int], [f_nvarchar], [update_date] ) values ( @f_int, @f_nvarchar, @update_date ) " ;
			_insertIdentityˡ = "insert {0} ( [ID], [f_int], [f_nvarchar], [update_date] ) values ( @ID, @f_int, @f_nvarchar, @update_date ) " ;
			_updateˡ = "update {0} set [f_int] = @f_int, [f_nvarchar] = @f_nvarchar, [update_date] = @update_date " ;
			_deleteˡ = "delete {0} " ;
			_whereLoadPKˡ = "where [ID] = @pk_ID " ;
			_whereSavePKˡ = "where [ID] = @pk_ID and [update_date] = @concurrency_update_date " ;
		}

		public TestTable5 Saveˡ( sds.SqlConnection connˡ, TestTable5 rowˡ, acr.CodeGenSaveStrategy saveStrategyˡ = acr.CodeGenSaveStrategy.Normal, bool identityProvidedˡ = false, sds.SqlTransaction tranˡ = null )
		{
			scg.List<sds.SqlParameter> parametersˡ = new scg.List<sds.SqlParameter>();
			base.AddParameterˡ( parametersˡ, "@pk_ID", rowˡ.PrimaryKeyDictionaryˡ[ TestTable5.column٠ID ] );
			base.AddParameterˡ( parametersˡ, "@concurrency_update_date", rowˡ.ConcurrencyTimestampˡ );
			base.AddParameterˡ( parametersˡ, "@ID", rowˡ.ID, sd.SqlDbType.Int );
			base.AddParameterˡ( parametersˡ, "@f_int", rowˡ.f_int, sd.SqlDbType.Int );
			base.AddParameterˡ( parametersˡ, "@f_nvarchar", rowˡ.f_nvarchar, sd.SqlDbType.NText );
			base.AddParameterˡ( parametersˡ, "@update_date", rowˡ.update_date, sd.SqlDbType.DateTime );

			int? identityIDˡ = null ;
			object objˡ = null ;

			acr.SaveEnum saveResultˡ ;

			if ( saveStrategyˡ != acr.CodeGenSaveStrategy.Normal )
			{
				saveResultˡ = base.ExecuteForceSaveˡ( rowˡ, connˡ, tranˡ, parametersˡ, saveStrategyˡ, _insertˡ, _insertIdentityˡ, _updateˡ, _deleteˡ, _whereLoadPKˡ, true, identityProvidedˡ, out objˡ ) ;
				if ( objˡ != null )
					identityIDˡ = int.Parse( objˡ.ToString() ) ;
			}
			else
			{
				saveResultˡ = base.ExecuteSaveˡ( rowˡ, connˡ, tranˡ, parametersˡ, _insertˡ, _insertIdentityˡ, _updateˡ, _deleteˡ, _whereSavePKˡ, true, identityProvidedˡ, out objˡ ) ;
				if ( objˡ != null )
					identityIDˡ = int.Parse( objˡ.ToString() ) ;
			}

			if ( saveResultˡ == acr.SaveEnum.Update )
				return this.LoadByPrimaryKeyˡ( connˡ, rowˡ.ID, tranˡ ) ;
			else
			if ( saveResultˡ == acr.SaveEnum.Insert )
				return this.LoadByPrimaryKeyˡ( connˡ, identityIDˡ, tranˡ ) ;
			else
			if ( saveResultˡ == acr.SaveEnum.Delete )
				return null ;
			else
				return rowˡ ;
		}

		public scg.List<TestTable5> Saveˡ( sds.SqlConnection connˡ, scg.List<TestTable5> rowListˡ, acr.CodeGenSaveStrategy saveStrategyˡ = acr.CodeGenSaveStrategy.Normal,  bool identityProvidedˡ = false, sds.SqlTransaction tranˡ = null )
		{
			scg.List<TestTable5> rowList2ˡ = new scg.List<TestTable5>();
			foreach( TestTable5 rowˡ in rowListˡ )
			{
				TestTable5 row2ˡ = this.Saveˡ( connˡ, rowˡ, saveStrategyˡ, identityProvidedˡ, tranˡ ) ;
				if ( row2ˡ != null )	rowList2ˡ.Add( row2ˡ ) ;
			}
			return rowList2ˡ ;
		}

		public TestTable5 LoadByPrimaryKeyˡ
		(
			sds.SqlConnection connˡ,
			int? ID,
			sds.SqlTransaction tranˡ = null
		)
		{
			scg.List<sds.SqlParameter> parametersˡ = new scg.List<sds.SqlParameter>();
			base.AddParameterˡ( parametersˡ, "@pk_ID", ID );
			return base.ExecuteQueryReturnOneˡ( connˡ, tranˡ, parametersˡ, _assemblyˡ, _selectˡ, false, _whereLoadPKˡ, false ) ;
		}

		public scg.List<TestTable5> Loadˡ
		(
			sds.SqlConnection connˡ,
			int? topNˡ = null,
			scg.List<acr.CodeGenOrderBy> orderByˡ = null,
			sds.SqlTransaction tranˡ = null
		)
		{
			scg.List<sds.SqlParameter> parametersˡ = new scg.List<sds.SqlParameter>();
			string whereˡ = "";
			string sqlˡ = "" ;
			return base.ExecuteQueryˡ( connˡ, tranˡ, parametersˡ, _assemblyˡ, _selectˡ, false, whereˡ, false, topNˡ, orderByˡ, out sqlˡ ) ;
		}

		public scg.List<TestTable5> LoadByWhereˡ
		(
			sds.SqlConnection connˡ,
			string whereˡ,
			scg.List<sds.SqlParameter> parametersˡ = null,
			int? topNˡ = null,
			scg.List<acr.CodeGenOrderBy> orderByˡ = null,
			sds.SqlTransaction tranˡ = null
		)
		{
			string sqlˡ = "" ;
			return base.ExecuteQueryˡ( connˡ, tranˡ, parametersˡ, _assemblyˡ, _selectˡ, false, whereˡ, false, topNˡ, orderByˡ, out sqlˡ ) ;
		}

	}

}

redpajama_set_name: RedPajamaGithub


text:
module RVM
  class Environment

    PREFIX_OPTIONS = [:trace, :json, :yaml]

    def self.default_rvm_path
      value = `bash '#{File.expand_path('../shell/calculate_rvm_path.sh', File.dirname(__FILE__))}'`.strip
      $?.success? && !value.empty? ? File.expand_path(value) : nil
    end

    # Returns the environment identifier for the current environment,
    # as determined from the GEM_HOME.
    def self.current_environment_id
      @current_environment_id ||= begin
        gem_home = ENV['GEM_HOME'].to_s.strip
        if !gem_home.empty? && gem_home =~ /rvm\/gems\//
          File.basename(gem_home)
        else
          matching_path = $:.select { |item| item =~ /rvm\/rubies/ }.first
          matching_path.to_s.gsub(/^.*rvm\/rubies\//, '').split('/')[0] || "system"
        end
      end
    end

    # Returns the ruby string that represents the current environment.
    def self.current_ruby_string
      identifier_to_ruby_string(current_environment_id)
    end

    # Converts a ruby identifier (string + gemset) to just the ruby string.
    def self.identifier_to_ruby_string(identifier)
      identifier.gsub(/@.*$/, '')
    end

    def self.identifier_to_gemset_name(identifier)
      identifier.gsub(/^.*@/, '')
    end

    # Returns the currentl environment.
    # Note that when the ruby is changed, this is reset - Also,
    # if the gemset is changed it will also be reset.
    def self.current
      @current_environment ||= Environment.new(current_environment_id)
    end

    # Sets the current environment back to the currently running ruby
    # or the system env (if it can't be determined from GEM_HOME).
    def self.reset_current!
      @current_environment = nil
    end

    # Lets you build a command up, without needing to see the output.
    # Examples:
    #
    #  rvm :use, "ree@rails3", :install => true
    #  > rvm use ree@rails3 --install
    #
    #  rvm :install, "ree@rails3", :rvm_by_path => true, :rubygems_version => "1.8.23"
    #  > rvm_rubygems_version=1.8.23 $rvm_path/bin/rvm install ree@rails3
    #
    def rvm(*args)
      options = extract_options!(args)
      silent = options.delete(:silent)
      rvm_by_path = options.delete(:rvm_by_path)
      rubygems_version = options.delete(:rubygems_version)
      rearrange_options!(args, options)
      args += hash_to_options(options)
      args.map! { |a| a.to_s }

      rvm_path = config_value_for(:rvm_path, self.class.default_rvm_path, false)
      program = rvm_by_path ? "#{rvm_path}/bin/rvm" : "rvm"
      program = "rvm_rubygems_version=#{rubygems_version} #{program}" if rubygems_version
      if silent
        run_silently(program, *args)
      else
        run(program, *args)
      end
    end

    # Run commands inside the given directory.
    def chdir(dir)
      run_silently :pushd, dir.to_s
      result = Dir.chdir(dir) { yield }
      run_silently :popd
      result
    end

    protected

    # Moves certain options (e.g. yaml, json etc) to the front
    # of the arguments list, making stuff like sets work.
    def rearrange_options!(args, options)
      prefix_options = {}
      (PREFIX_OPTIONS + PREFIX_OPTIONS.map { |o| o.to_s }).each do |k|
        if options.has_key?(k)
          value = options.delete(k)
          prefix_options[k.to_sym] = value
        end
      end
      hash_to_options(prefix_options).reverse.each { |o| args.unshift(o) }
    end

    def ruby_string(result)
      if result && result[:rvm_env_string]
        Environment.identifier_to_ruby_string result[:rvm_env_string]
      else
        self.class.identifier_to_ruby_string(expanded_name)
      end
    end

    # Checks whether the given environment is compatible with the current
    # ruby interpeter.
    def compatible_with_current?(result)
      ruby_string(result) == self.class.current_ruby_string
    end

    # Given an environment identifier, it will add the the given
    # gemset to the end to form a qualified identifier name.
    def self.environment_with_gemset(environment, gemset)
      environment_name, gemset_name = environment.split("@", 2)
      environment_name = "default"     if environment_name.to_s.empty?
      environment_name << "@#{gemset}" unless gemset.to_s.empty?
      environment_name
    end

    # Returns a value, or nil if it is blank.
    def normalize(value)
      value = value.to_s.strip
      value.empty? ? nil : value
    end

    # Normalizes an array, removing blank lines.
    def normalize_array(value)
      value.split("\n").map { |line| line.strip }.reject { |line| line.empty? }
    end

    # Extract options from a hash.
    def extract_options!(args)
      args.last.is_a?(Hash) ? args.pop : {}
    end

    # Converts a hash of options to an array of command line argumets.
    # If the value is false, it wont be added but if it is true only the
    # key will be added. Lastly, when the value is neither true or false,
    # to_s will becalled on it and it shall be added to the array.
    def hash_to_options(options)
      result = []
      options.each_pair do |key, value|
        real_key = "--#{key.to_s.gsub("_", "-")}"
        if value == true
          result << real_key
        elsif value != false
          result << real_key
          result << value.to_s
        end
      end
      result
    end

    # Recursively normalize options.
    def normalize_option_value(value)
      case value
      when Array
        value.map { |option| normalize_option_value(option) }.join(",")
      else
        value.to_s
      end
    end

    def use_env_from_result!(result)
      if compatible_with_current?(result)
        ENV['GEM_HOME']    = result[:GEM_HOME]
        ENV['GEM_PATH']    = result[:GEM_PATH]
        Gem.clear_paths if defined?(Gem)
      else
        raise IncompatibleRubyError.new(result, "The given ruby environment requires #{ruby_string(result)} (versus #{self.class.current_ruby_string})")
      end
    end

  end
end


text:
package gov.va.escreening.entity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

/**
 * Created by kliu on 2/21/15.
 */

@Entity
@Table(name = "veteran_assessment_survey_score")
public class VeteranAssessmentSurveyScore implements Serializable {

    private static final long serialVersionUID = 18947892345L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "assessment_survey_score_id")
    private Integer assessmentSurveyScoreId;

    @JoinColumn(name = "veteran_assessment_id", referencedColumnName = "veteran_assessment_id")
    @ManyToOne
    private VeteranAssessment veteranAssessment;

    @JoinColumn(name = "survey_id", referencedColumnName = "survey_id")
    @ManyToOne
    private Survey survey;

    @Column(name = "av_name")
    private String avName;

    @Column(name = "survey_score")
    private Integer score;

    @Column(name = "screen_number")
    private Integer screenNumber;

    @Column(name = "date_completed")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCompleted;

    @JoinColumn(name = "veteran_id", referencedColumnName = "veteran_id")
    @ManyToOne(optional = false)
    private Veteran veteran;

    @JoinColumn(name = "clinic_id", referencedColumnName = "clinic_id")
    @ManyToOne(optional = false)
    private Clinic clinic;

    public VeteranAssessment getVeteranAssessment() {
        return veteranAssessment;
    }

    public void setVeteranAssessment(VeteranAssessment veteranAssessment) {
        this.veteranAssessment = veteranAssessment;
    }

    public Survey getSurvey() {
        return survey;
    }

    public void setSurvey(Survey survey) {
        this.survey = survey;
    }

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score = score;
    }

    public Date getDateCompleted() {
        return dateCompleted;
    }

    public void setDateCompleted(Date dateCompleted) {
        this.dateCompleted = dateCompleted;
    }

    public Veteran getVeteran() {
        return veteran;
    }

    public void setVeteran(Veteran veteran) {
        this.veteran = veteran;
    }

    public Integer getAssessmentSurveyScoreId() {
        return assessmentSurveyScoreId;
    }

    public void setAssessmentSurveyScoreId(Integer assessmentSurveyScoreId) {
        this.assessmentSurveyScoreId = assessmentSurveyScoreId;
    }

    public Clinic getClinic() {
        return clinic;
    }

    public void setClinic(Clinic clinic) {
        this.clinic = clinic;
    }

    public Integer getScreenNumber() {
        return screenNumber;
    }

    public void setScreenNumber(Integer screenNumber) {
        this.screenNumber = screenNumber;
    }

    public String getAvName() {
        return avName;
    }

    public void setAvName(String avName) {
        this.avName = avName;
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.spi.predicate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import io.airlift.json.ObjectMapperProvider;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.TestingBlockEncodingSerde;
import io.prestosql.spi.block.TestingBlockJsonSerde;
import io.prestosql.spi.type.TestingTypeDeserializer;
import io.prestosql.spi.type.TestingTypeManager;
import io.prestosql.spi.type.Type;
import org.testng.annotations.Test;

import static io.airlift.slice.Slices.utf8Slice;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.BooleanType.BOOLEAN;
import static io.prestosql.spi.type.DoubleType.DOUBLE;
import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

public class TestSortedRangeSet
{
    @Test
    public void testEmptySet()
    {
        SortedRangeSet rangeSet = SortedRangeSet.none(BIGINT);
        assertEquals(rangeSet.getType(), BIGINT);
        assertTrue(rangeSet.isNone());
        assertFalse(rangeSet.isAll());
        assertFalse(rangeSet.isSingleValue());
        assertTrue(Iterables.isEmpty(rangeSet.getOrderedRanges()));
        assertEquals(rangeSet.getRangeCount(), 0);
        assertEquals(rangeSet.complement(), SortedRangeSet.all(BIGINT));
        assertFalse(rangeSet.includesMarker(Marker.lowerUnbounded(BIGINT)));
        assertFalse(rangeSet.includesMarker(Marker.exactly(BIGINT, 0L)));
        assertFalse(rangeSet.includesMarker(Marker.upperUnbounded(BIGINT)));
    }

    @Test
    public void testEntireSet()
    {
        SortedRangeSet rangeSet = SortedRangeSet.all(BIGINT);
        assertEquals(rangeSet.getType(), BIGINT);
        assertFalse(rangeSet.isNone());
        assertTrue(rangeSet.isAll());
        assertFalse(rangeSet.isSingleValue());
        assertEquals(rangeSet.getRangeCount(), 1);
        assertEquals(rangeSet.complement(), SortedRangeSet.none(BIGINT));
        assertTrue(rangeSet.includesMarker(Marker.lowerUnbounded(BIGINT)));
        assertTrue(rangeSet.includesMarker(Marker.exactly(BIGINT, 0L)));
        assertTrue(rangeSet.includesMarker(Marker.upperUnbounded(BIGINT)));
    }

    @Test
    public void testSingleValue()
    {
        SortedRangeSet rangeSet = SortedRangeSet.of(BIGINT, 10L);

        SortedRangeSet complement = SortedRangeSet.of(Range.greaterThan(BIGINT, 10L), Range.lessThan(BIGINT, 10L));

        assertEquals(rangeSet.getType(), BIGINT);
        assertFalse(rangeSet.isNone());
        assertFalse(rangeSet.isAll());
        assertTrue(rangeSet.isSingleValue());
        assertTrue(Iterables.elementsEqual(rangeSet.getOrderedRanges(), ImmutableList.of(Range.equal(BIGINT, 10L))));
        assertEquals(rangeSet.getRangeCount(), 1);
        assertEquals(rangeSet.complement(), complement);
        assertFalse(rangeSet.includesMarker(Marker.lowerUnbounded(BIGINT)));
        assertTrue(rangeSet.includesMarker(Marker.exactly(BIGINT, 10L)));
        assertFalse(rangeSet.includesMarker(Marker.exactly(BIGINT, 9L)));
        assertFalse(rangeSet.includesMarker(Marker.upperUnbounded(BIGINT)));
    }

    @Test
    public void testBoundedSet()
    {
        SortedRangeSet rangeSet = SortedRangeSet.of(
                Range.equal(BIGINT, 10L),
                Range.equal(BIGINT, 0L),
                Range.range(BIGINT, 9L, true, 11L, false),
                Range.equal(BIGINT, 0L),
                Range.range(BIGINT, 2L, true, 4L, true),
                Range.range(BIGINT, 4L, false, 5L, true));

        ImmutableList<Range> normalizedResult = ImmutableList.of(
                Range.equal(BIGINT, 0L),
                Range.range(BIGINT, 2L, true, 5L, true),
                Range.range(BIGINT, 9L, true, 11L, false));

        SortedRangeSet complement = SortedRangeSet.of(
                Range.lessThan(BIGINT, 0L),
                Range.range(BIGINT, 0L, false, 2L, false),
                Range.range(BIGINT, 5L, false, 9L, false),
                Range.greaterThanOrEqual(BIGINT, 11L));

        assertEquals(rangeSet.getType(), BIGINT);
        assertFalse(rangeSet.isNone());
        assertFalse(rangeSet.isAll());
        assertFalse(rangeSet.isSingleValue());
        assertTrue(Iterables.elementsEqual(rangeSet.getOrderedRanges(), normalizedResult));
        assertEquals(rangeSet, SortedRangeSet.copyOf(BIGINT, normalizedResult));
        assertEquals(rangeSet.getRangeCount(), 3);
        assertEquals(rangeSet.complement(), complement);
        assertFalse(rangeSet.includesMarker(Marker.lowerUnbounded(BIGINT)));
        assertTrue(rangeSet.includesMarker(Marker.exactly(BIGINT, 0L)));
        assertFalse(rangeSet.includesMarker(Marker.exactly(BIGINT, 1L)));
        assertFalse(rangeSet.includesMarker(Marker.exactly(BIGINT, 7L)));
        assertTrue(rangeSet.includesMarker(Marker.exactly(BIGINT, 9L)));
        assertFalse(rangeSet.includesMarker(Marker.upperUnbounded(BIGINT)));
    }

    @Test
    public void testUnboundedSet()
    {
        SortedRangeSet rangeSet = SortedRangeSet.of(
                Range.greaterThan(BIGINT, 10L),
                Range.lessThanOrEqual(BIGINT, 0L),
                Range.range(BIGINT, 2L, true, 4L, false),
                Range.range(BIGINT, 4L, true, 6L, false),
                Range.range(BIGINT, 1L, false, 2L, false),
                Range.range(BIGINT, 9L, false, 11L, false));

        ImmutableList<Range> normalizedResult = ImmutableList.of(
                Range.lessThanOrEqual(BIGINT, 0L),
                Range.range(BIGINT, 1L, false, 6L, false),
                Range.greaterThan(BIGINT, 9L));

        SortedRangeSet complement = SortedRangeSet.of(
                Range.range(BIGINT, 0L, false, 1L, true),
                Range.range(BIGINT, 6L, true, 9L, true));

        assertEquals(rangeSet.getType(), BIGINT);
        assertFalse(rangeSet.isNone());
        assertFalse(rangeSet.isAll());
        assertFalse(rangeSet.isSingleValue());
        assertTrue(Iterables.elementsEqual(rangeSet.getOrderedRanges(), normalizedResult));
        assertEquals(rangeSet, SortedRangeSet.copyOf(BIGINT, normalizedResult));
        assertEquals(rangeSet.getRangeCount(), 3);
        assertEquals(rangeSet.complement(), complement);
        assertTrue(rangeSet.includesMarker(Marker.lowerUnbounded(BIGINT)));
        assertTrue(rangeSet.includesMarker(Marker.exactly(BIGINT, 0L)));
        assertTrue(rangeSet.includesMarker(Marker.exactly(BIGINT, 4L)));
        assertFalse(rangeSet.includesMarker(Marker.exactly(BIGINT, 7L)));
        assertTrue(rangeSet.includesMarker(Marker.upperUnbounded(BIGINT)));
    }

    @Test
    public void testGetSingleValue()
    {
        assertEquals(SortedRangeSet.of(BIGINT, 0L).getSingleValue(), 0L);
        try {
            SortedRangeSet.all(BIGINT).getSingleValue();
            fail();
        }
        catch (IllegalStateException e) {
        }
    }

    @Test
    public void testSpan()
    {
        try {
            SortedRangeSet.none(BIGINT).getSpan();
            fail();
        }
        catch (IllegalStateException e) {
        }

        assertEquals(SortedRangeSet.all(BIGINT).getSpan(), Range.all(BIGINT));
        assertEquals(SortedRangeSet.of(BIGINT, 0L).getSpan(), Range.equal(BIGINT, 0L));
        assertEquals(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).getSpan(), Range.range(BIGINT, 0L, true, 1L, true));
        assertEquals(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.greaterThan(BIGINT, 1L)).getSpan(), Range.greaterThanOrEqual(BIGINT, 0L));
        assertEquals(SortedRangeSet.of(Range.lessThan(BIGINT, 0L), Range.greaterThan(BIGINT, 1L)).getSpan(), Range.all(BIGINT));
    }

    @Test
    public void testOverlaps()
    {
        assertTrue(SortedRangeSet.all(BIGINT).overlaps(SortedRangeSet.all(BIGINT)));
        assertFalse(SortedRangeSet.all(BIGINT).overlaps(SortedRangeSet.none(BIGINT)));
        assertTrue(SortedRangeSet.all(BIGINT).overlaps(SortedRangeSet.of(BIGINT, 0L)));
        assertTrue(SortedRangeSet.all(BIGINT).overlaps(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))));
        assertTrue(SortedRangeSet.all(BIGINT).overlaps(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
        assertTrue(SortedRangeSet.all(BIGINT).overlaps(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L), Range.lessThan(BIGINT, 0L))));

        assertFalse(SortedRangeSet.none(BIGINT).overlaps(SortedRangeSet.all(BIGINT)));
        assertFalse(SortedRangeSet.none(BIGINT).overlaps(SortedRangeSet.none(BIGINT)));
        assertFalse(SortedRangeSet.none(BIGINT).overlaps(SortedRangeSet.of(BIGINT, 0L)));
        assertFalse(SortedRangeSet.none(BIGINT).overlaps(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))));
        assertFalse(SortedRangeSet.none(BIGINT).overlaps(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
        assertFalse(SortedRangeSet.none(BIGINT).overlaps(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L), Range.lessThan(BIGINT, 0L))));

        assertTrue(SortedRangeSet.of(BIGINT, 0L).overlaps(SortedRangeSet.all(BIGINT)));
        assertFalse(SortedRangeSet.of(BIGINT, 0L).overlaps(SortedRangeSet.none(BIGINT)));
        assertTrue(SortedRangeSet.of(BIGINT, 0L).overlaps(SortedRangeSet.of(BIGINT, 0L)));
        assertTrue(SortedRangeSet.of(BIGINT, 0L).overlaps(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))));
        assertFalse(SortedRangeSet.of(BIGINT, 0L).overlaps(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
        assertFalse(SortedRangeSet.of(BIGINT, 0L).overlaps(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L), Range.lessThan(BIGINT, 0L))));

        assertTrue(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).overlaps(SortedRangeSet.of(Range.equal(BIGINT, 1L))));
        assertFalse(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).overlaps(SortedRangeSet.of(Range.equal(BIGINT, 2L))));
        assertTrue(SortedRangeSet.of(Range.greaterThanOrEqual(BIGINT, 0L)).overlaps(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
        assertTrue(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)).overlaps(SortedRangeSet.of(Range.greaterThanOrEqual(BIGINT, 0L))));
        assertFalse(SortedRangeSet.of(Range.lessThan(BIGINT, 0L)).overlaps(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
    }

    @Test
    public void testContains()
    {
        assertTrue(SortedRangeSet.all(BIGINT).contains(SortedRangeSet.all(BIGINT)));
        assertTrue(SortedRangeSet.all(BIGINT).contains(SortedRangeSet.none(BIGINT)));
        assertTrue(SortedRangeSet.all(BIGINT).contains(SortedRangeSet.of(BIGINT, 0L)));
        assertTrue(SortedRangeSet.all(BIGINT).contains(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))));
        assertTrue(SortedRangeSet.all(BIGINT).contains(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
        assertTrue(SortedRangeSet.all(BIGINT).contains(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L), Range.lessThan(BIGINT, 0L))));

        assertFalse(SortedRangeSet.none(BIGINT).contains(SortedRangeSet.all(BIGINT)));
        assertTrue(SortedRangeSet.none(BIGINT).contains(SortedRangeSet.none(BIGINT)));
        assertFalse(SortedRangeSet.none(BIGINT).contains(SortedRangeSet.of(BIGINT, 0L)));
        assertFalse(SortedRangeSet.none(BIGINT).contains(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))));
        assertFalse(SortedRangeSet.none(BIGINT).contains(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
        assertFalse(SortedRangeSet.none(BIGINT).contains(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L), Range.lessThan(BIGINT, 0L))));

        assertFalse(SortedRangeSet.of(BIGINT, 0L).contains(SortedRangeSet.all(BIGINT)));
        assertTrue(SortedRangeSet.of(BIGINT, 0L).contains(SortedRangeSet.none(BIGINT)));
        assertTrue(SortedRangeSet.of(BIGINT, 0L).contains(SortedRangeSet.of(BIGINT, 0L)));
        assertFalse(SortedRangeSet.of(BIGINT, 0L).contains(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))));
        assertFalse(SortedRangeSet.of(BIGINT, 0L).contains(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
        assertFalse(SortedRangeSet.of(BIGINT, 0L).contains(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L), Range.lessThan(BIGINT, 0L))));

        assertTrue(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).contains(SortedRangeSet.of(Range.equal(BIGINT, 1L))));
        assertFalse(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).contains(SortedRangeSet.of(Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L))));
        assertTrue(SortedRangeSet.of(Range.greaterThanOrEqual(BIGINT, 0L)).contains(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
        assertFalse(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)).contains(SortedRangeSet.of(Range.greaterThanOrEqual(BIGINT, 0L))));
        assertFalse(SortedRangeSet.of(Range.lessThan(BIGINT, 0L)).contains(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))));
    }

    @Test
    public void testIntersect()
    {
        assertEquals(
                SortedRangeSet.none(BIGINT).intersect(
                        SortedRangeSet.none(BIGINT)),
                SortedRangeSet.none(BIGINT));

        assertEquals(
                SortedRangeSet.all(BIGINT).intersect(
                        SortedRangeSet.all(BIGINT)),
                SortedRangeSet.all(BIGINT));

        assertEquals(
                SortedRangeSet.none(BIGINT).intersect(
                        SortedRangeSet.all(BIGINT)),
                SortedRangeSet.none(BIGINT));

        assertEquals(
                SortedRangeSet.of(Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L), Range.equal(BIGINT, 3L)).intersect(
                        SortedRangeSet.of(Range.equal(BIGINT, 2L), Range.equal(BIGINT, 4L))),
                SortedRangeSet.of(Range.equal(BIGINT, 2L)));

        assertEquals(
                SortedRangeSet.all(BIGINT).intersect(
                        SortedRangeSet.of(Range.equal(BIGINT, 2L), Range.equal(BIGINT, 4L))),
                SortedRangeSet.of(Range.equal(BIGINT, 2L), Range.equal(BIGINT, 4L)));

        assertEquals(
                SortedRangeSet.of(Range.range(BIGINT, 0L, true, 4L, false)).intersect(
                        SortedRangeSet.of(Range.equal(BIGINT, 2L), Range.greaterThan(BIGINT, 3L))),
                SortedRangeSet.of(Range.equal(BIGINT, 2L), Range.range(BIGINT, 3L, false, 4L, false)));

        assertEquals(
                SortedRangeSet.of(Range.greaterThanOrEqual(BIGINT, 0L)).intersect(
                        SortedRangeSet.of(Range.lessThanOrEqual(BIGINT, 0L))),
                SortedRangeSet.of(Range.equal(BIGINT, 0L)));

        assertEquals(
                SortedRangeSet.of(Range.greaterThanOrEqual(BIGINT, -1L)).intersect(
                        SortedRangeSet.of(Range.lessThanOrEqual(BIGINT, 1L))),
                SortedRangeSet.of(Range.range(BIGINT, -1L, true, 1L, true)));
    }

    @Test
    public void testUnion()
    {
        assertUnion(SortedRangeSet.none(BIGINT), SortedRangeSet.none(BIGINT), SortedRangeSet.none(BIGINT));
        assertUnion(SortedRangeSet.all(BIGINT), SortedRangeSet.all(BIGINT), SortedRangeSet.all(BIGINT));
        assertUnion(SortedRangeSet.none(BIGINT), SortedRangeSet.all(BIGINT), SortedRangeSet.all(BIGINT));

        assertUnion(
                SortedRangeSet.of(Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L)),
                SortedRangeSet.of(Range.equal(BIGINT, 2L), Range.equal(BIGINT, 3L)),
                SortedRangeSet.of(Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L), Range.equal(BIGINT, 3L)));

        assertUnion(SortedRangeSet.all(BIGINT), SortedRangeSet.of(Range.equal(BIGINT, 0L)), SortedRangeSet.all(BIGINT));

        assertUnion(
                SortedRangeSet.of(Range.range(BIGINT, 0L, true, 4L, false)),
                SortedRangeSet.of(Range.greaterThan(BIGINT, 3L)),
                SortedRangeSet.of(Range.greaterThanOrEqual(BIGINT, 0L)));

        assertUnion(
                SortedRangeSet.of(Range.greaterThanOrEqual(BIGINT, 0L)),
                SortedRangeSet.of(Range.lessThanOrEqual(BIGINT, 0L)),
                SortedRangeSet.of(Range.all(BIGINT)));

        assertUnion(
                SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)),
                SortedRangeSet.of(Range.lessThan(BIGINT, 0L)),
                SortedRangeSet.of(BIGINT, 0L).complement());
    }

    @Test
    public void testSubtract()
    {
        assertEquals(
                SortedRangeSet.all(BIGINT).subtract(SortedRangeSet.all(BIGINT)),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.all(BIGINT).subtract(SortedRangeSet.none(BIGINT)),
                SortedRangeSet.all(BIGINT));
        assertEquals(
                SortedRangeSet.all(BIGINT).subtract(SortedRangeSet.of(BIGINT, 0L)),
                SortedRangeSet.of(BIGINT, 0L).complement());
        assertEquals(
                SortedRangeSet.all(BIGINT).subtract(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))),
                SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).complement());
        assertEquals(
                SortedRangeSet.all(BIGINT).subtract(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))),
                SortedRangeSet.of(Range.lessThanOrEqual(BIGINT, 0L)));

        assertEquals(
                SortedRangeSet.none(BIGINT).subtract(SortedRangeSet.all(BIGINT)),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.none(BIGINT).subtract(SortedRangeSet.none(BIGINT)),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.none(BIGINT).subtract(SortedRangeSet.of(BIGINT, 0L)),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.none(BIGINT).subtract(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.none(BIGINT).subtract(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))),
                SortedRangeSet.none(BIGINT));

        assertEquals(
                SortedRangeSet.of(BIGINT, 0L).subtract(SortedRangeSet.all(BIGINT)),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.of(BIGINT, 0L).subtract(SortedRangeSet.none(BIGINT)),
                SortedRangeSet.of(BIGINT, 0L));
        assertEquals(
                SortedRangeSet.of(BIGINT, 0L).subtract(SortedRangeSet.of(BIGINT, 0L)),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.of(BIGINT, 0L).subtract(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.of(BIGINT, 0L).subtract(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))),
                SortedRangeSet.of(BIGINT, 0L));

        assertEquals(
                SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).subtract(SortedRangeSet.all(BIGINT)),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).subtract(SortedRangeSet.none(BIGINT)),
                SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)));
        assertEquals(
                SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).subtract(SortedRangeSet.of(BIGINT, 0L)),
                SortedRangeSet.of(BIGINT, 1L));
        assertEquals(
                SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).subtract(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L)).subtract(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))),
                SortedRangeSet.of(Range.equal(BIGINT, 0L)));

        assertEquals(
                SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)).subtract(SortedRangeSet.all(BIGINT)),
                SortedRangeSet.none(BIGINT));
        assertEquals(
                SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)).subtract(SortedRangeSet.none(BIGINT)),
                SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)));
        assertEquals(
                SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)).subtract(SortedRangeSet.of(BIGINT, 0L)),
                SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)));
        assertEquals(
                SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)).subtract(SortedRangeSet.of(Range.equal(BIGINT, 0L), Range.equal(BIGINT, 1L))),
                SortedRangeSet.of(Range.range(BIGINT, 0L, false, 1L, false), Range.greaterThan(BIGINT, 1L)));
        assertEquals(
                SortedRangeSet.of(Range.greaterThan(BIGINT, 0L)).subtract(SortedRangeSet.of(Range.greaterThan(BIGINT, 0L))),
                SortedRangeSet.none(BIGINT));
    }

    @Test
    public void testJsonSerialization()
            throws Exception
    {
        TestingTypeManager typeManager = new TestingTypeManager();
        TestingBlockEncodingSerde blockEncodingSerde = new TestingBlockEncodingSerde(typeManager);

        ObjectMapper mapper = new ObjectMapperProvider().get()
                .registerModule(new SimpleModule()
                        .addDeserializer(Type.class, new TestingTypeDeserializer(typeManager))
                        .addSerializer(Block.class, new TestingBlockJsonSerde.Serializer(blockEncodingSerde))
                        .addDeserializer(Block.class, new TestingBlockJsonSerde.Deserializer(blockEncodingSerde)));

        SortedRangeSet set = SortedRangeSet.all(BIGINT);
        assertEquals(set, mapper.readValue(mapper.writeValueAsString(set), SortedRangeSet.class));

        set = SortedRangeSet.none(DOUBLE);
        assertEquals(set, mapper.readValue(mapper.writeValueAsString(set), SortedRangeSet.class));

        set = SortedRangeSet.of(VARCHAR, utf8Slice("abc"));
        assertEquals(set, mapper.readValue(mapper.writeValueAsString(set), SortedRangeSet.class));

        set = SortedRangeSet.of(Range.equal(BOOLEAN, true), Range.equal(BOOLEAN, false));
        assertEquals(set, mapper.readValue(mapper.writeValueAsString(set), SortedRangeSet.class));
    }

    private void assertUnion(SortedRangeSet first, SortedRangeSet second, SortedRangeSet expected)
    {
        assertEquals(first.union(second), expected);
        assertEquals(first.union(ImmutableList.of(first, second)), expected);
    }
}


text:
<form class="form-horizontal" id="form-editarCronogramaValorizacion" action="<?php echo base_url();?>index.php/CronogramaValorizacion/editar" method="POST" >

		Descripción*

			<input id="hdIdCronogramaValorizacion" type="hidden" name="hdIdCronogramaValorizacion" value="<?= $CronogramaValoracion->id_valorizacion?>" class="form-control col-md-7 col-xs-12" notValidate >
			<input id="txtCronogramaValorizacion" name="txtCronogramaValorizacion" value="<?= $CronogramaValoracion->desc_cronograma?>" class="form-control col-md-7 col-xs-12"  placeholder="Ingrese Etapa" required="required" autocomplete="off" >

			<button type="submit" id="btnEnviarFormulario" class="btn btn-success">Guardar Cronograma Valorización</button>
			<button  class="btn btn-danger" data-dismiss="modal">Cancelar</button>

</form>


text:
#include "../../inc/MarlinConfigPre.h"

#if ENABLED(GCODE_MOTION_MODES)

#include "../gcode.h"

/**
 * G80: Cancel current motion mode
 */
void GcodeSuite::G80() {

  parser.cancel_motion_mode();

}

#endif // GCODE_MOTION_MODES


text:
#include <bundles/index/IndexSearchService.h>

#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>

#include <memory> // for auto_ptr

namespace bfs = boost::filesystem;

namespace sf1r
{

using namespace izenelib::osgi;

MiningBundleActivator::MiningBundleActivator()
    : tracker_(0)
    , context_(0)
    , searchService_(0)
    , searchServiceReg_(0)
    , taskService_(0)
    , taskServiceReg_(0)
    , config_(0)
{
}

MiningBundleActivator::~MiningBundleActivator()
{
}

void MiningBundleActivator::start( IBundleContext::ConstPtr context )
{
    context_ = context;

    boost::shared_ptr<BundleConfiguration> bundleConfigPtr = context->getBundleConfig();
    config_ = static_cast<MiningBundleConfiguration*>(bundleConfigPtr.get());
    tracker_ = new ServiceTracker( context, "IndexSearchService", this );
    tracker_->startTracking();
}

void MiningBundleActivator::stop( IBundleContext::ConstPtr context )
{
    if(tracker_)
    {
        tracker_->stopTracking();
        delete tracker_;
        tracker_ = 0;
    }
    if(searchServiceReg_)
    {
        searchServiceReg_->unregister();
        delete searchServiceReg_;
        delete searchService_;
        searchServiceReg_ = 0;
        searchService_ = 0;
    }

    if(taskServiceReg_)
    {
        taskServiceReg_->unregister();
        delete taskServiceReg_;
        delete taskService_;
        taskServiceReg_ = 0;
        taskService_ = 0;
    }
}

bool MiningBundleActivator::addingService( const ServiceReference& ref )
{
    if ( ref.getServiceName() == "IndexSearchService" )
    {
        Properties props = ref.getServiceProperties();
        if ( props.get( "collection" ) == config_->collectionName_)
        {
            IndexSearchService* service = reinterpret_cast<IndexSearchService*> ( const_cast<IService*>(ref.getService()) );
            cout << "[MiningBundleActivator#addingService] Calling IndexSearchService..." << endl;
            currentCollectionDataName_ = service->bundleConfig_->collPath_.getCurrCollectionDir();
            miningManager_ = createMiningManager_(service);
            if (!miningManager_)
            {
                cerr << "error: failed in creating MiningManager" << endl;
                return false;
            }
            searchService_ = new MiningSearchService;
            searchService_->bundleConfig_ = config_;
            searchService_->miningManager_ = miningManager_;
            searchService_->searchAggregator_ = service->searchAggregator_;
            searchService_->ro_searchAggregator_ = service->ro_searchAggregator_;
            searchService_->searchWorker_ = service->searchWorker_;

            taskService_ = new MiningTaskService(config_);
            taskService_->miningManager_ = miningManager_;

            Properties props;
            props.put( "collection", config_->collectionName_);
            searchServiceReg_ = context_->registerService( "MiningSearchService", searchService_, props );
            taskServiceReg_ = context_->registerService( "MiningTaskService", taskService_, props );
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }

}

void MiningBundleActivator::removedService( const ServiceReference& ref )
{

}

std::string MiningBundleActivator::getCurrentCollectionDataPath_() const
{
    return config_->collPath_.getCollectionDataPath()+"/"+currentCollectionDataName_;
}

std::string MiningBundleActivator::getCollectionDataPath_() const
{
    return config_->collPath_.getCollectionDataPath();
}

boost::shared_ptr<MiningManager>
MiningBundleActivator::createMiningManager_(IndexSearchService* indexService) const
{
    std::string dir = getCurrentCollectionDataPath_()+"/mining";
    boost::filesystem::create_directories(dir);
    boost::shared_ptr<MiningManager> ret;

    ret.reset(
            new MiningManager(
                dir,
                config_->collPath_,
                indexService->searchWorker_->documentManager_,
                indexService->searchWorker_->laManager_,
                indexService->searchWorker_->invertedIndexManager_,
                indexService->searchWorker_->searchManager_,
                indexService->searchWorker_->searchCache_,
                indexService->searchWorker_->idManager_,
                indexService->adSearchService_,
                config_->collectionName_,
                config_->documentSchema_,
                config_->mining_config_,
                config_->mining_schema_,
                indexService->getBundleConfig()->indexSchema_
                )
            );

    static bool FirstRun = true;
    if (FirstRun)
    {
        FirstRun = false;

        MiningManager::system_resource_path_ = config_->system_resource_path_;
        MiningManager::system_working_path_ = config_->system_working_path_;
    }

    bool succ = ret->open();
    if(!succ)
    {
        ret.reset();
    }
    return ret;
}

}


text:
#define SPI1_NSS_PIN    GPIO_Pin_4
#define SPI1_SCK_PIN    GPIO_Pin_5
#define SPI1_MISO_PIN   GPIO_Pin_6
#define SPI1_MOSI_PIN   GPIO_Pin_7

#define SPI1_PORT       GPIOA

#define SPI1_NSS_PIN_SOURCE    GPIO_PinSource4
#define SPI1_SCK_PIN_SOURCE    GPIO_PinSource5
#define SPI1_MISO_PIN_SOURCE   GPIO_PinSource6
#define SPI1_MOSI_PIN_SOURCE   GPIO_PinSource7

#define GOBUS_GPIO_SPEED  GPIO_Speed_100MHz
#define GO_BUS_IRQ        GPIO_Pin_9
#define GO_BUS_IRQ_PORT   GPIOB

#define spiRxBufferSize 1024 * 4
#define spiTxBufferSize 1024 * 4

static unsigned char spiRxBuffer[spiRxBufferSize];
static unsigned char spiTxBuffer[spiTxBufferSize];

void AssertGoBusIRQ(){
  GPIO_WriteBit(GO_BUS_IRQ_PORT, GO_BUS_IRQ, Bit_RESET);
}
void ReleaseGoBusIRQ(){
  GPIO_WriteBit(GO_BUS_IRQ_PORT, GO_BUS_IRQ, Bit_SET);
}

void spiInit(void)
{
  InitializeModuleUUID(spiTxBuffer, spiTxBufferSize);

  GPIO_InitTypeDef  GPIO_InitStructure;
  SPI_InitTypeDef   SPI_InitStructure;
  DMA_InitTypeDef   DMA_InitStructure;
  NVIC_InitTypeDef  NVIC_InitStructure;

  GPIO_StructInit(&GPIO_InitStructure);
  SPI_StructInit(&SPI_InitStructure);
  DMA_StructInit(&DMA_InitStructure);

  // Enable the peripheral clocks
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);

  // Configure the /GOBUS_IRQ line used to synchronize with the SPI master
  GPIO_InitStructure.GPIO_Pin = GO_BUS_IRQ;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_Speed = GOBUS_GPIO_SPEED;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(GO_BUS_IRQ_PORT, &GPIO_InitStructure);

  // Set the /GOBUS_IRQ line HIGH
  ReleaseGoBusIRQ();

  // Connect SPI pins to AF5
  GPIO_PinAFConfig(GPIOA, SPI1_NSS_PIN_SOURCE, GPIO_AF_SPI1);
  GPIO_PinAFConfig(GPIOA, SPI1_SCK_PIN_SOURCE, GPIO_AF_SPI1);
  GPIO_PinAFConfig(GPIOA, SPI1_MISO_PIN_SOURCE, GPIO_AF_SPI1);
  GPIO_PinAFConfig(GPIOA, SPI1_MOSI_PIN_SOURCE, GPIO_AF_SPI1);

  // SPI SCK / MOSI / MISO pin configuration & initialization
  GPIO_InitStructure.GPIO_Pin = SPI1_SCK_PIN | SPI1_MOSI_PIN | SPI1_MISO_PIN | SPI1_NSS_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GOBUS_GPIO_SPEED;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_DOWN;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  // SPI configuration & initialization
  SPI_I2S_DeInit(SPI1);

  SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
  SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
  SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
  SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
  SPI_InitStructure.SPI_NSS = SPI_NSS_Hard;
  SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
  SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
  SPI_InitStructure.SPI_CRCPolynomial = 7;
  SPI_InitStructure.SPI_Mode = SPI_Mode_Slave;
  SPI_Init(SPI1, &SPI_InitStructure);

  // DMA configuration (SPI1 RX on DMA2 Stream 0, Channel 3, see RM0033 Reference manual section 9.3.3)
  DMA_DeInit(DMA2_Stream0);

  DMA_InitStructure.DMA_Channel = DMA_Channel_3;
  DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&SPI1->DR;
  DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)spiRxBuffer;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;
  DMA_InitStructure.DMA_BufferSize = spiRxBufferSize;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
  DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
  DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
  DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
  DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
  DMA_Init(DMA2_Stream0, &DMA_InitStructure); // configure the stream

  // DMA configuration (SPI1 TX on DMA2 Stream 3, Channel 3, see RM0033 Reference manual section 9.3.3)
  DMA_DeInit(DMA2_Stream3);

  DMA_InitStructure.DMA_Channel = DMA_Channel_3;
  DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&SPI1->DR;
  DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)spiTxBuffer;
  DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
  DMA_InitStructure.DMA_BufferSize = spiTxBufferSize;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
  DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
  DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
  DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
  DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
  DMA_Init(DMA2_Stream3, &DMA_InitStructure); // configure the stream

  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

  // Set and enable DMA Stream 0 IRQ (Rx)
  NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream0_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  // Set and enable DMA Stream 3 IRQ (Tx)
  NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream3_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  DMA_ITConfig(DMA2_Stream0, DMA_IT_TC, ENABLE);
  DMA_ITConfig(DMA2_Stream3, DMA_IT_TC, ENABLE);

  DMA_Cmd(DMA2_Stream0, ENABLE); // Enable the stream associated with SPI1_RX
  DMA_Cmd(DMA2_Stream3, ENABLE); // Enable the stream associated with SPI1_TX

  SPI_I2S_DMACmd(SPI1, SPI_I2S_DMAReq_Rx, ENABLE); // Enable the DMA to receive SPI data
  SPI_I2S_DMACmd(SPI1, SPI_I2S_DMAReq_Tx, ENABLE); // Enable the DMA to send SPI data

  SPI_Cmd(SPI1, ENABLE); // Enable the SPI peripheral
}

extern void ProcessMessage(unsigned char* message, unsigned short messageBufferSize, unsigned char* responseData, unsigned short responseSize);

// DMA2 Stream 0 - SPI1 RX - IRQ handler
void DMA2_Stream0_IRQHandler(){
  DMA_ClearITPendingBit(DMA2_Stream0, DMA_IT_TCIF0);
  ReleaseGoBusIRQ();
  ProcessMessage(spiRxBuffer, spiRxBufferSize, spiTxBuffer, spiTxBufferSize);
  // Re-activate the SPI RX DMA
  DMA_SetCurrDataCounter(DMA2_Stream0, spiRxBufferSize);
  DMA_Cmd(DMA2_Stream0, ENABLE);
}

// DMA2 Stream 3 - SPI1 TX - IRQ handler
void DMA2_Stream3_IRQHandler(){
  DMA_ClearITPendingBit(DMA2_Stream3, DMA_IT_TCIF3);
  // Re-activate the SPI TX DMA
  DMA_SetCurrDataCounter(DMA2_Stream3, spiTxBufferSize);
  DMA_Cmd(DMA2_Stream3, ENABLE);
}


text:
typedef BOOL (^JFFAlertViewComparator)( id alert_view1_, id alert_view2_ );

#endif


text:
# code climent must be loaded and started before RAILS_ENV is declared
# require "codeclimate-test-reporter"
ENV['CODECLIMATE_REPO_TOKEN'] = ENV['MYTODO_CC']
# CodeClimate::TestReporter.start
ENV["RAILS_ENV"] = 'test'
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'database_cleaner'
require 'factory_bot_rails'
require 'shoulda-matchers'
require 'faker'
require 'byebug'
require 'my_todo'
require 'simplecov'

SimpleCov.start

DatabaseCleaner.strategy = :truncation

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :active_model
    with.library :active_record
  end
end

Dir['spec/support/**/*.rb'].each { |f| require f }

FactoryBot.define do
  factory :item do
    body { Faker::Lorem.paragraph }
    detailed_status {'None'}
  end

  factory :note do
    item
    body {Faker::Lorem.paragraph}
  end

  factory :tag do
    name {Faker::Lorem.word}
  end
end

RSpec.configure do |config|
  config.before(:each) do
    DatabaseCleaner.clean
  end
  config.include(Shoulda::Matchers::ActiveModel, type: :model)
  config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end

# If I need to check rubocop
# rubocop   --require rubocop-rspec   --only FactoryBot/AttributeDefinedStatically   --auto-correct


text:
import sys
import gc
import uos as os
import uerrno as errno
import ujson as json
import uzlib
import upip_utarfile as tarfile
gc.collect()

debug = False
install_path = None
cleanup_files = []
gzdict_sz = 16 + 15

file_buf = bytearray(512)

class NotFoundError(Exception):
    pass

def op_split(path):
    if path == "":
        return ("", "")
    r = path.rsplit("/", 1)
    if len(r) == 1:
        return ("", path)
    head = r[0]
    if not head:
        head = "/"
    return (head, r[1])

def op_basename(path):
    return op_split(path)[1]

# Expects *file* name
def _makedirs(name, mode=0o777):
    ret = False
    s = ""
    comps = name.rstrip("/").split("/")[:-1]
    if comps[0] == "":
        s = "/"
    for c in comps:
        if s and s[-1] != "/":
            s += "/"
        s += c
        try:
            os.mkdir(s)
            ret = True
        except OSError as e:
            if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
                raise
            ret = False
    return ret

def save_file(fname, subf):
    global file_buf
    with open(fname, "wb") as outf:
        while True:
            sz = subf.readinto(file_buf)
            if not sz:
                break
            outf.write(file_buf, sz)

def install_tar(f, prefix):
    meta = {}
    for info in f:
        #print(info)
        fname = info.name
        try:
            fname = fname[fname.index("/") + 1:]
        except ValueError:
            fname = ""

        save = True
        for p in ("setup.", "PKG-INFO", "README"):
                #print(fname, p)
                if fname.startswith(p) or ".egg-info" in fname:
                    if fname.endswith("/requires.txt"):
                        meta["deps"] = f.extractfile(info).read()
                    save = False
                    if debug:
                        print("Skipping", fname)
                    break

        if save:
            outfname = prefix + fname
            if info.type != tarfile.DIRTYPE:
                if debug:
                    print("Extracting " + outfname)
                _makedirs(outfname)
                subf = f.extractfile(info)
                save_file(outfname, subf)
    return meta

def expandhome(s):
    if "~/" in s:
        h = os.getenv("HOME")
        s = s.replace("~/", h + "/")
    return s

import ussl
import usocket
warn_ussl = True
def url_open(url):
    global warn_ussl
    proto, _, host, urlpath = url.split('/', 3)
    ai = usocket.getaddrinfo(host, 443)
    #print("Address infos:", ai)
    addr = ai[0][4]

    s = usocket.socket(ai[0][0])
    #print("Connect address:", addr)
    s.connect(addr)

    if proto == "https:":
        s = ussl.wrap_socket(s)
        if warn_ussl:
            print("Warning: %s SSL certificate is not validated" % host)
            warn_ussl = False

    # MicroPython rawsocket module supports file interface directly
    s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
    l = s.readline()
    protover, status, msg = l.split(None, 2)
    if status != b"200":
        if status == b"404":
            print("Package not found")
        raise ValueError(status)
    while 1:
        l = s.readline()
        if not l:
            raise ValueError("Unexpected EOF")
        if l == b'\r\n':
            break

    return s

def get_pkg_metadata(name):
    f = url_open("https://pypi.python.org/pypi/%s/json" % name)
    s = f.read()
    f.close()
    return json.loads(s)

def fatal(msg):
    print(msg)
    sys.exit(1)

def install_pkg(pkg_spec, install_path):
    data = get_pkg_metadata(pkg_spec)

    latest_ver = data["info"]["version"]
    packages = data["releases"][latest_ver]
    del data
    gc.collect()
    assert len(packages) == 1
    package_url = packages[0]["url"]
    print("Installing %s %s from %s" % (pkg_spec, latest_ver, package_url))
    package_fname = op_basename(package_url)
    f1 = url_open(package_url)
    f2 = uzlib.DecompIO(f1, gzdict_sz)
    f3 = tarfile.TarFile(fileobj=f2)
    meta = install_tar(f3, install_path)
    f1.close()
    del f3
    del f2
    gc.collect()
    return meta

def install(to_install, install_path=None):
    # Calculate gzip dictionary size to use
    global gzdict_sz
    sz = gc.mem_free() + gc.mem_alloc()
    if sz <= 65536:
        gzdict_sz = 16 + 12

    if install_path is None:
        install_path = get_install_path()
    if install_path[-1] != "/":
        install_path += "/"
    if not isinstance(to_install, list):
        to_install = [to_install]
    print("Installing to: " + install_path)
    # sets would be perfect here, but don't depend on them
    installed = []
    try:
        while to_install:
            if debug:
                print("Queue:", to_install)
            pkg_spec = to_install.pop(0)
            if pkg_spec in installed:
                continue
            meta = install_pkg(pkg_spec, install_path)
            installed.append(pkg_spec)
            if debug:
                print(meta)
            deps = meta.get("deps", "").rstrip()
            if deps:
                deps = deps.decode("utf-8").split("\n")
                to_install.extend(deps)
    except NotFoundError:
        print("Error: cannot find '%s' package (or server error), packages may be partially installed" \
            % pkg_spec, file=sys.stderr)

def get_install_path():
    global install_path
    if install_path is None:
        # sys.path[0] is current module's path
        install_path = sys.path[1]
    install_path = expandhome(install_path)
    return install_path

def cleanup():
    for fname in cleanup_files:
        try:
            os.unlink(fname)
        except OSError:
            print("Warning: Cannot delete " + fname)

def help():
    print("""\
upip - Simple PyPI package manager for MicroPython
Usage: micropython -m upip install [-p <path>] <package>... | -r <requirements.txt>
import upip; upip.install(package_or_list, [<path>])

If <path> is not given, packages will be installed into sys.path[1]
(can be set from MICROPYPATH environment variable, if current system
supports that).""")
    print("Current value of sys.path[1]:", sys.path[1])
    print("""\

Note: only MicroPython packages (usually, named micropython-*) are supported
for installation, upip does not support arbitrary code in setup.py.
""")

def main():
    global debug
    global install_path
    install_path = None

    if len(sys.argv) < 2 or sys.argv[1] == "-h" or sys.argv[1] == "--help":
        help()
        return

    if sys.argv[1] != "install":
        fatal("Only 'install' command supported")

    to_install = []

    i = 2
    while i < len(sys.argv) and sys.argv[i][0] == "-":
        opt = sys.argv[i]
        i += 1
        if opt == "-h" or opt == "--help":
            help()
            return
        elif opt == "-p":
            install_path = sys.argv[i]
            i += 1
        elif opt == "-r":
            list_file = sys.argv[i]
            i += 1
            with open(list_file) as f:
                while True:
                    l = f.readline()
                    if not l:
                        break
                    to_install.append(l.rstrip())
        elif opt == "--debug":
            debug = True
        else:
            fatal("Unknown/unsupported option: " + opt)

    to_install.extend(sys.argv[i:])
    if not to_install:
        help()
        return

    install(to_install)

    if not debug:
        cleanup()

if __name__ == "__main__":
    main()


text:
package org.ovirt.engine.core.cryptotool;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.ovirt.engine.core.uutils.cli.parser.ArgumentsParser;
import org.ovirt.engine.core.uutils.crypto.EnvelopeEncryptDecrypt;
import org.ovirt.engine.core.uutils.crypto.EnvelopePBE;

public class Main {

    private static final Map<String, String> substitutions = new HashMap<>();

    private static class ExitException extends RuntimeException {
        private int exitCode;

        public ExitException() {
            this(0);
        }

        public ExitException(int exitCode) {
            this(null, exitCode);
        }

        public ExitException(String msg, int exitCode) {
            super(msg);
            this.exitCode = exitCode;
        }

        public int getExitCode() {
            return exitCode;
        }
    }

    private interface Logic {
        void execute(Map<String, Object> argMap) throws IOException, GeneralSecurityException;
    }

    private enum Action {
        PBE_ENCODE(
            new Logic() {
                @Override
                public void execute(Map<String, Object> argMap) throws IOException, GeneralSecurityException {
                    System.out.println(
                        EnvelopePBE.encode(
                            (String)argMap.get("algorithm"),
                            (Integer)argMap.get("key-size"),
                            (Integer)argMap.get("iterations"),
                            null,
                            getPassword("Password: ", (String)argMap.get("password"))
                        )
                    );
                }
            }
        ),
        PBE_CHECK(
            new Logic() {
                @Override
                public void execute(Map<String, Object> argMap) throws IOException, GeneralSecurityException {
                    if (
                        !EnvelopePBE.check(
                            new String(readStream(System.in), Charset.forName("UTF-8")),
                            getPassword("Password: ", (String)argMap.get("password"))
                        )
                    ) {
                        System.err.println("FAILED");
                        throw new ExitException("Check failed", 1);
                    }
                }
            }
        ),
        ENC_ENCODE(
            new Logic() {
                @Override
                public void execute(Map<String, Object> argMap) throws IOException, GeneralSecurityException {
                    try(InputStream in = new FileInputStream((String)argMap.get("certificate"))) {
                        System.out.println(
                            EnvelopeEncryptDecrypt.encrypt(
                                (String)argMap.get("algorithm"),
                                (Integer)argMap.get("key-size"),
                                CertificateFactory.getInstance("X.509").generateCertificate(in),
                                (Integer)argMap.get("block-size"),
                                readStream(System.in)
                            )
                        );
                    }
                }
            }
        ),
        ENC_DECODE(
            new Logic() {
                @Override
                public void execute(Map<String, Object> argMap) throws IOException, GeneralSecurityException {
                    String keystorePassword = getPassword("Key store password: ", (String)argMap.get("keystore-password"));
                    System.out.write(
                        EnvelopeEncryptDecrypt.decrypt(
                            getPrivateKeyEntry(
                                getKeyStore(
                                    (String)argMap.get("keystore-type"),
                                    (String)argMap.get("keystore"),
                                    keystorePassword
                                ),
                                (String)argMap.get("keystore-alias"),
                                (
                                    argMap.get("key-password") != null ?
                                    getPassword("Key password: ", (String)argMap.get("key-password")) :
                                    keystorePassword
                                )
                            ),
                            new String(readStream(System.in), Charset.forName("UTF-8"))
                        )
                    );
                }
            }
        );

        private Logic logic;

        private Action(Logic logic) {
            this.logic = logic;
        }

        void execute(Properties props, List<String> cmdArgs) throws IOException, GeneralSecurityException {
            ArgumentsParser parser = new ArgumentsParser(props, cmdArgs.remove(0));
            parser.getSubstitutions().putAll(substitutions);
            parser.parse(cmdArgs);
            Map<String, Object> argMap = parser.getParsedArgs();

            if((Boolean)argMap.get("help")) {
                System.out.format("Usage: %s", parser.getUsage());
                throw new ExitException("Help", 0);
            }
            if(!parser.getErrors().isEmpty()) {
                for(Throwable t : parser.getErrors()) {
                    System.err.format("FATAL: %s%n", t.getMessage());
                }
                throw new ExitException("Parsing error", 1);
            }
            logic.execute(argMap);
        }
    };

    private static String PROGRAM_NAME = System.getProperty("org.ovirt.engine.cryptotool.core.programName");
    private static String PACKAGE_NAME = System.getProperty("org.ovirt.engine.cryptotool.core.packageName");
    private static String PACKAGE_VERSION = System.getProperty("org.ovirt.engine.cryptotool.core.packageVersion");
    private static String PACKAGE_DISPLAY_NAME = System.getProperty("org.ovirt.engine.cryptotool.core.packageDisplayName");

    private static KeyStore getKeyStore(String storeType, String store, String password) throws IOException, GeneralSecurityException {
        KeyStore ks = KeyStore.getInstance(storeType);
        try (InputStream is = new FileInputStream(store)) {
            ks.load(is, password.toCharArray());
        }
        return ks;
    }

    private static KeyStore.PrivateKeyEntry getPrivateKeyEntry(KeyStore ks, String alias, String password) throws IOException, GeneralSecurityException {
        KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)ks.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));
        if (entry == null) {
            throw new IllegalArgumentException(String.format("Keystore alias '%s' is missing", alias));
        }
        return entry;
    }

    private static byte[] readStream(InputStream in) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int n;
        while ((n = in.read(buf)) != -1) {
            os.write(buf, 0, n);
        }
        return os.toByteArray();
    }

    private static String getPassword(String prompt, String what) throws IOException {
        String keyValue[] = what.split(":", 2);
        String type = keyValue[0];
        String value = keyValue[1];

        String password = null;
        if ("pass".equals(type)) {
            password = value;
        } else if ("file".equals(type)) {
            try(
                InputStream is = new FileInputStream(value);
                Reader reader = new InputStreamReader(is);
                BufferedReader breader = new BufferedReader(reader);
            ) {
                password = breader.readLine();
            }
        } else if ("env".equals(type)) {
            password = System.getenv(value);
        } else if ("interactive".equals(type)) {
            if (System.console() == null) {
                throw new RuntimeException("Console is not available, interactive password prompt is impossible");
            }
            System.console().printf("%s", prompt);
            char passwordChars[] = System.console().readPassword();
            if (passwordChars == null) {
                throw new RuntimeException("Cannot read password");
            }
            password = new String(passwordChars);
        } else {
            throw new IllegalArgumentException(String.format("Invalid type: '%s'", type));
        }

        if (password == null) {
            throw new IllegalArgumentException("No password");
        }

        return password;
    }

    public static void main(String... args) throws IOException {
        int exitStatus = 1;
        List<String> cmdArgs = new ArrayList<>(Arrays.asList(args));
        substitutions.put("@PROGRAM_NAME@", PROGRAM_NAME);

        try {
            Properties props = new Properties();
            try (
                InputStream in = Main.class.getResourceAsStream("arguments.properties");
                Reader reader = new InputStreamReader(in);
            ) {
                props.load(reader);
            }
            ArgumentsParser parser = new ArgumentsParser(props, "core");
            parser.getSubstitutions().putAll(substitutions);
            parser.parse(cmdArgs);
            Map<String, Object> argMap = parser.getParsedArgs();

            if((Boolean)argMap.get("help")) {
                System.out.format("Usage: %s", parser.getUsage());
                throw new ExitException("Help", 0);
            } else if((Boolean)argMap.get("version")) {
                System.out.format("%s-%s (%s)%n", PACKAGE_NAME, PACKAGE_VERSION, PACKAGE_DISPLAY_NAME);
                throw new ExitException("Version", 0);
            }
            if(!parser.getErrors().isEmpty()) {
                for(Throwable t : parser.getErrors()) {
                    System.err.format("FATAL: %s%n", t.getMessage());
                }
                throw new ExitException("Parsing error", 1);
            }

            if (cmdArgs.size() < 1) {
                System.err.println("Action not provided");
                throw new ExitException("Action not provided", 1);
            }

            Action action;
            try {
                action = Action.valueOf(cmdArgs.get(0).toUpperCase().replace("-", "_"));
            } catch(IllegalArgumentException e) {
                System.err.printf("Invalid action '%s'%n", cmdArgs.get(0));
                throw new ExitException("Invalid action", 1);
            }

            action.execute(props, cmdArgs);
            exitStatus = 0;
        } catch (ExitException e) {
            exitStatus = e.getExitCode();
        } catch (Exception e) {
            System.err.format("FATAL: %s%n", e.getMessage());
            e.printStackTrace(System.err);
        }

        System.exit(exitStatus);
    }

}


text:
Attributes:

    <list-builder [item-list]="pattern.attributes"
                  [label-provider]="labelProvider">
      <type-ahead-instiller class="instiller"></type-ahead-instiller>
    </list-builder>

      <button class="ps-btn primary" [disabled]="!isDirty" (click)="save()">
        Save
      </button>
      <button class="ps-btn" [disabled]="!isDirty" (click)="cancel()">
        Cancel
      </button>

Related links:

      <ps-menu [list-provider]="listProvider"
               [selection-model]="selectionModel">
      </ps-menu>


text:
namespace Snippets5
{
    using NServiceBus;

    public class License
    {
        public void Simple()
        {
            #region License

            BusConfiguration busConfiguration = new BusConfiguration();

            busConfiguration.LicensePath("PathToLicense");
            //or
            busConfiguration.License("YourCustomLicenseText");

            #endregion
        }

    }
}