text:
import { Code } from '@blueprintjs/core';
import React from 'react';

import { ExternalLink, Field } from '../components';
import { getLink } from '../links';
import { filterMap, oneOf } from '../utils';
import { HeaderAndRows } from '../utils/sampler';

import { getColumnTypeFromHeaderAndRows } from './ingestion-spec';

export interface MetricSpec {
  type: string;
  name?: string;
  fieldName?: string;
  maxStringBytes?: number;
  filterNullValues?: boolean;
  fieldNames?: string[];
  fnAggregate?: string;
  fnCombine?: string;
  fnReset?: string;
  fields?: string[];
  byRow?: boolean;
  round?: boolean;
  isInputHyperUnique?: boolean;
  filter?: any;
  aggregator?: MetricSpec;
}

export const METRIC_SPEC_FIELDS: Field<MetricSpec>[] = [
  {
    name: 'name',
    type: 'string',
    info: <>The metric name as it will appear in Druid.</>,
  },
  {
    name: 'type',
    type: 'string',
    suggestions: [
      'count',
      {
        group: 'sum',
        suggestions: ['longSum', 'doubleSum', 'floatSum'],
      },
      {
        group: 'min',
        suggestions: ['longMin', 'doubleMin', 'floatMin'],
      },
      {
        group: 'max',
        suggestions: ['longMax', 'doubleMax', 'floatMax'],
      },
      {
        group: 'first',
        suggestions: ['longFirst', 'doubleFirst', 'floatFirst'],
      },
      {
        group: 'last',
        suggestions: ['longLast', 'doubleLast', 'floatLast'],
      },
      'thetaSketch',
      {
        group: 'HLLSketch',
        suggestions: ['HLLSketchBuild', 'HLLSketchMerge'],
      },
      'quantilesDoublesSketch',
      'momentSketch',
      'fixedBucketsHistogram',
      'hyperUnique',
      'filtered',
    ],
    info: <>The aggregation function to apply.</>,
  },
  {
    name: 'fieldName',
    type: 'string',
    defined: m => m.type !== 'filtered',
    info: <>The column name for the aggregator to operate on.</>,
  },
  {
    name: 'maxStringBytes',
    type: 'number',
    defaultValue: 1024,
    defined: m => {
      return oneOf(m.type, 'stringFirst', 'stringLast');
    },
  },
  {
    name: 'filterNullValues',
    type: 'boolean',
    defaultValue: false,
    defined: m => {
      return oneOf(m.type, 'stringFirst', 'stringLast');
    },
  },
  // filtered
  {
    name: 'filter',
    type: 'json',
    defined: m => m.type === 'filtered',
  },
  {
    name: 'aggregator',
    type: 'json',
    defined: m => m.type === 'filtered',
  },
  // thetaSketch
  {
    name: 'size',
    type: 'number',
    defined: m => m.type === 'thetaSketch',
    defaultValue: 16384,
    info: (
      <>

          Must be a power of 2. Internally, size refers to the maximum number of entries sketch
          object will retain. Higher size means higher accuracy but more space to store sketches.
          Note that after you index with a particular size, druid will persist sketch in segments
          and you will use size greater or equal to that at query time.

          See the{' '}
          <ExternalLink href="https://datasketches.apache.org/docs/Theta/ThetaSize.html">
            DataSketches site
          </ExternalLink>{' '}
          for details.

In general, We recommend just sticking to default size.

      </>
    ),
  },
  {
    name: 'isInputThetaSketch',
    type: 'boolean',
    defined: m => m.type === 'thetaSketch',
    defaultValue: false,
    info: (
      <>
        This should only be used at indexing time if your input data contains theta sketch objects.
        This would be the case if you use datasketches library outside of Druid, say with Pig/Hive,
        to produce the data that you are ingesting into Druid
      </>
    ),
  },
  // HLLSketchBuild & HLLSketchMerge
  {
    name: 'lgK',
    type: 'number',
    defined: m => oneOf(m.type, 'HLLSketchBuild', 'HLLSketchMerge'),
    defaultValue: 12,
    info: (
      <>

          log2 of K that is the number of buckets in the sketch, parameter that controls the size
          and the accuracy.

Must be between 4 to 21 inclusively.

      </>
    ),
  },
  {
    name: 'tgtHllType',
    type: 'string',
    defined: m => oneOf(m.type, 'HLLSketchBuild', 'HLLSketchMerge'),
    defaultValue: 'HLL_4',
    suggestions: ['HLL_4', 'HLL_6', 'HLL_8'],
    info: (
      <>
        The type of the target HLL sketch. Must be HLL_4, HLL_6, or{' '}
        HLL_8.
      </>
    ),
  },
  // quantilesDoublesSketch
  {
    name: 'k',
    type: 'number',
    defined: m => m.type === 'quantilesDoublesSketch',
    defaultValue: 128,
    info: (
      <>

          Parameter that determines the accuracy and size of the sketch. Higher k means higher
          accuracy but more space to store sketches.

          Must be a power of 2 from 2 to 32768. See the{' '}
          <ExternalLink href="https://datasketches.apache.org/docs/Quantiles/QuantilesAccuracy.html">
            Quantiles Accuracy
          </ExternalLink>{' '}
          for details.

      </>
    ),
  },
  // momentSketch
  {
    name: 'k',
    type: 'number',
    defined: m => m.type === 'momentSketch',
    required: true,
    info: (
      <>
        Parameter that determines the accuracy and size of the sketch. Higher k means higher
        accuracy but more space to store sketches. Usable range is generally [3,15]
      </>
    ),
  },
  {
    name: 'compress',
    type: 'boolean',
    defined: m => m.type === 'momentSketch',
    defaultValue: true,
    info: (
      <>
        Flag for whether the aggregator compresses numeric values using arcsinh. Can improve
        robustness to skewed and long-tailed distributions, but reduces accuracy slightly on more
        uniform distributions.
      </>
    ),
  },
  // fixedBucketsHistogram
  {
    name: 'lowerLimit',
    type: 'number',
    defined: m => m.type === 'fixedBucketsHistogram',
    required: true,
    info: <>Lower limit of the histogram.</>,
  },
  {
    name: 'upperLimit',
    type: 'number',
    defined: m => m.type === 'fixedBucketsHistogram',
    required: true,
    info: <>Upper limit of the histogram.</>,
  },
  {
    name: 'numBuckets',
    type: 'number',
    defined: m => m.type === 'fixedBucketsHistogram',
    defaultValue: 10,
    required: true,
    info: (
      <>
        Number of buckets for the histogram. The range [lowerLimit, upperLimit] will be
        divided into numBuckets intervals of equal size.
      </>
    ),
  },
  {
    name: 'outlierHandlingMode',
    type: 'string',
    defined: m => m.type === 'fixedBucketsHistogram',
    required: true,
    suggestions: ['ignore', 'overflow', 'clip'],
    info: (
      <>

          Specifies how values outside of [lowerLimit, upperLimit] will be handled.

          Supported modes are ignore, overflow, and clip. See
          <ExternalLink
            href={`${getLink(
              'DOCS',
            )}/development/extensions-core/approximate-histograms.html#outlier-handling-modes`}
          >
            outlier handling modes
          </ExternalLink>{' '}
          for more details.

      </>
    ),
  },
  // hyperUnique
  {
    name: 'isInputHyperUnique',
    type: 'boolean',
    defined: m => m.type === 'hyperUnique',
    defaultValue: false,
    info: (
      <>
        This can be set to true to index precomputed HLL (Base64 encoded output from druid-hll is
        expected).
      </>
    ),
  },
];

export function getMetricSpecName(metricSpec: MetricSpec): string {
  return (
    metricSpec.name || (metricSpec.aggregator ? getMetricSpecName(metricSpec.aggregator) : '?')
  );
}

export function getMetricSpecSingleFieldName(metricSpec: MetricSpec): string | undefined {
  return (
    metricSpec.fieldName ||
    (metricSpec.aggregator ? getMetricSpecSingleFieldName(metricSpec.aggregator) : undefined)
  );
}

export function getMetricSpecOutputType(metricSpec: MetricSpec): string | undefined {
  if (metricSpec.aggregator) return getMetricSpecOutputType(metricSpec.aggregator);
  const m = String(metricSpec.type).match(/^(long|float|double)/);
  if (!m) return;
  return m[1];
}

export function getMetricSpecs(
  headerAndRows: HeaderAndRows,
  typeHints: Record<string, string>,
): MetricSpec[] {
  return [{ name: 'count', type: 'count' }].concat(
    filterMap(headerAndRows.header, h => {
      if (h === '__time') return;
      const type = typeHints[h] || getColumnTypeFromHeaderAndRows(headerAndRows, h);
      switch (type) {
        case 'double':
          return { name: `sum_${h}`, type: 'doubleSum', fieldName: h };
        case 'float':
          return { name: `sum_${h}`, type: 'floatSum', fieldName: h };
        case 'long':
          return { name: `sum_${h}`, type: 'longSum', fieldName: h };
        default:
          return;
      }
    }),
  );
}


text:
using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace ProteinTrackerAndroid
{
	[Activity (Label = "Protein Tracker", MainLauncher = true)]
	public class MainActivity : Activity
	{
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERLevel;

namespace ParentLoadSoftDelete.DataAccess.Sql.ERLevel
{
    /// <summary>
    /// DAL SQL Server implementation of <see cref="IE11_City_ChildDal"/>
    /// </summary>
    public partial class E11_City_ChildDal : IE11_City_ChildDal
    {
        /// <summary>
        /// Inserts a new E11_City_Child object in the database.
        /// </summary>
        /// <param name="e11_City_Child">The E11 City Child DTO.</param>
        /// <returns>The new <see cref="E11_City_ChildDto"/>.</returns>
        public E11_City_ChildDto Insert(E11_City_ChildDto e11_City_Child)
        {
            using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
            {
                using (var cmd = new SqlCommand("AddE11_City_Child", ctx.Connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@City_ID1", e11_City_Child.Parent_City_ID).DbType = DbType.Int32;
                    cmd.Parameters.AddWithValue("@City_Child_Name", e11_City_Child.City_Child_Name).DbType = DbType.String;
                    cmd.ExecuteNonQuery();
                }
            }
            return e11_City_Child;
        }

        /// <summary>
        /// Updates in the database all changes made to the E11_City_Child object.
        /// </summary>
        /// <param name="e11_City_Child">The E11 City Child DTO.</param>
        /// <returns>The updated <see cref="E11_City_ChildDto"/>.</returns>
        public E11_City_ChildDto Update(E11_City_ChildDto e11_City_Child)
        {
            using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
            {
                using (var cmd = new SqlCommand("UpdateE11_City_Child", ctx.Connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@City_ID1", e11_City_Child.Parent_City_ID).DbType = DbType.Int32;
                    cmd.Parameters.AddWithValue("@City_Child_Name", e11_City_Child.City_Child_Name).DbType = DbType.String;
                    var rowsAffected = cmd.ExecuteNonQuery();
                    if (rowsAffected == 0)
                        throw new DataNotFoundException("E11_City_Child");
                }
            }
            return e11_City_Child;
        }

        /// <summary>
        /// Deletes the E11_City_Child object from database.
        /// </summary>
        /// <param name="city_ID1">The parent City ID1.</param>
        public void Delete(int city_ID1)
        {
            using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
            {
                using (var cmd = new SqlCommand("DeleteE11_City_Child", ctx.Connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@City_ID1", city_ID1).DbType = DbType.Int32;
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}


text:
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!

#include "config.h"
#if ENABLE(WEB_AUDIO)
#include "V8AudioParam.h"

#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8Float32Array.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"

namespace blink {

// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8AudioParam::wrapperTypeInfo = { gin::kEmbedderBlink, V8AudioParam::domTemplate, V8AudioParam::refObject, V8AudioParam::derefObject, V8AudioParam::trace, 0, 0, V8AudioParam::preparePrototypeObject, V8AudioParam::installConditionallyEnabledProperties, "AudioParam", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::GarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif

// This static member must be declared by DEFINE_WRAPPERTYPEINFO in AudioParam.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& AudioParam::s_wrapperTypeInfo = V8AudioParam::wrapperTypeInfo;

namespace AudioParamV8Internal {

static void valueAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    v8::Local<v8::Object> holder = info.Holder();
    AudioParam* impl = V8AudioParam::toImpl(holder);
    v8SetReturnValue(info, impl->value());
}

static void valueAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
    AudioParamV8Internal::valueAttributeGetter(info);
    TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}

static void valueAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
    v8::Local<v8::Object> holder = info.Holder();
    ExceptionState exceptionState(ExceptionState::SetterContext, "value", "AudioParam", holder, info.GetIsolate());
    AudioParam* impl = V8AudioParam::toImpl(holder);
    float cppValue = toRestrictedFloat(info.GetIsolate(), v8Value, exceptionState);
    if (exceptionState.throwIfNeeded())
        return;
    impl->setValue(cppValue);
}

static void valueAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    v8::Local<v8::Value> v8Value = info[0];
    TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
    AudioParamV8Internal::valueAttributeSetter(v8Value, info);
    TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}

static void defaultValueAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    v8::Local<v8::Object> holder = info.Holder();
    AudioParam* impl = V8AudioParam::toImpl(holder);
    v8SetReturnValue(info, impl->defaultValue());
}

static void defaultValueAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
    AudioParamV8Internal::defaultValueAttributeGetter(info);
    TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}

static void setValueAtTimeMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ExecutionContext, "setValueAtTime", "AudioParam", info.Holder(), info.GetIsolate());
    if (UNLIKELY(info.Length() < 2)) {
        setMinimumArityTypeError(exceptionState, 2, info.Length());
        exceptionState.throwIfNeeded();
        return;
    }
    AudioParam* impl = V8AudioParam::toImpl(info.Holder());
    float value;
    double time;
    {
        value = toRestrictedFloat(info.GetIsolate(), info[0], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        time = toRestrictedDouble(info.GetIsolate(), info[1], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
    }
    impl->setValueAtTime(value, time, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
}

static void setValueAtTimeMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
    AudioParamV8Internal::setValueAtTimeMethod(info);
    TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}

static void linearRampToValueAtTimeMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ExecutionContext, "linearRampToValueAtTime", "AudioParam", info.Holder(), info.GetIsolate());
    if (UNLIKELY(info.Length() < 2)) {
        setMinimumArityTypeError(exceptionState, 2, info.Length());
        exceptionState.throwIfNeeded();
        return;
    }
    AudioParam* impl = V8AudioParam::toImpl(info.Holder());
    float value;
    double time;
    {
        value = toRestrictedFloat(info.GetIsolate(), info[0], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        time = toRestrictedDouble(info.GetIsolate(), info[1], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
    }
    impl->linearRampToValueAtTime(value, time, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
}

static void linearRampToValueAtTimeMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
    AudioParamV8Internal::linearRampToValueAtTimeMethod(info);
    TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}

static void exponentialRampToValueAtTimeMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ExecutionContext, "exponentialRampToValueAtTime", "AudioParam", info.Holder(), info.GetIsolate());
    if (UNLIKELY(info.Length() < 2)) {
        setMinimumArityTypeError(exceptionState, 2, info.Length());
        exceptionState.throwIfNeeded();
        return;
    }
    AudioParam* impl = V8AudioParam::toImpl(info.Holder());
    float value;
    double time;
    {
        value = toRestrictedFloat(info.GetIsolate(), info[0], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        time = toRestrictedDouble(info.GetIsolate(), info[1], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
    }
    impl->exponentialRampToValueAtTime(value, time, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
}

static void exponentialRampToValueAtTimeMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
    AudioParamV8Internal::exponentialRampToValueAtTimeMethod(info);
    TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}

static void setTargetAtTimeMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ExecutionContext, "setTargetAtTime", "AudioParam", info.Holder(), info.GetIsolate());
    if (UNLIKELY(info.Length() < 3)) {
        setMinimumArityTypeError(exceptionState, 3, info.Length());
        exceptionState.throwIfNeeded();
        return;
    }
    AudioParam* impl = V8AudioParam::toImpl(info.Holder());
    float target;
    double time;
    double timeConstant;
    {
        target = toRestrictedFloat(info.GetIsolate(), info[0], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        time = toRestrictedDouble(info.GetIsolate(), info[1], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        timeConstant = toRestrictedDouble(info.GetIsolate(), info[2], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
    }
    impl->setTargetAtTime(target, time, timeConstant, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
}

static void setTargetAtTimeMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
    AudioParamV8Internal::setTargetAtTimeMethod(info);
    TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}

static void setValueCurveAtTimeMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ExecutionContext, "setValueCurveAtTime", "AudioParam", info.Holder(), info.GetIsolate());
    if (UNLIKELY(info.Length() < 3)) {
        setMinimumArityTypeError(exceptionState, 3, info.Length());
        exceptionState.throwIfNeeded();
        return;
    }
    AudioParam* impl = V8AudioParam::toImpl(info.Holder());
    DOMFloat32Array* values;
    double time;
    double duration;
    {
        values = info[0]->IsFloat32Array() ? V8Float32Array::toImpl(v8::Local<v8::Float32Array>::Cast(info[0])) : 0;
        time = toRestrictedDouble(info.GetIsolate(), info[1], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        duration = toRestrictedDouble(info.GetIsolate(), info[2], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
    }
    impl->setValueCurveAtTime(values, time, duration, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
}

static void setValueCurveAtTimeMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
    AudioParamV8Internal::setValueCurveAtTimeMethod(info);
    TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}

static void cancelScheduledValuesMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ExecutionContext, "cancelScheduledValues", "AudioParam", info.Holder(), info.GetIsolate());
    if (UNLIKELY(info.Length() < 1)) {
        setMinimumArityTypeError(exceptionState, 1, info.Length());
        exceptionState.throwIfNeeded();
        return;
    }
    AudioParam* impl = V8AudioParam::toImpl(info.Holder());
    double startTime;
    {
        startTime = toRestrictedDouble(info.GetIsolate(), info[0], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
    }
    impl->cancelScheduledValues(startTime, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
}

static void cancelScheduledValuesMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
    AudioParamV8Internal::cancelScheduledValuesMethod(info);
    TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}

} // namespace AudioParamV8Internal

static const V8DOMConfiguration::AccessorConfiguration V8AudioParamAccessors[] = {
    {"value", AudioParamV8Internal::valueAttributeGetterCallback, AudioParamV8Internal::valueAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
    {"defaultValue", AudioParamV8Internal::defaultValueAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
};

static const V8DOMConfiguration::MethodConfiguration V8AudioParamMethods[] = {
    {"setValueAtTime", AudioParamV8Internal::setValueAtTimeMethodCallback, 0, 2, V8DOMConfiguration::ExposedToAllScripts},
    {"linearRampToValueAtTime", AudioParamV8Internal::linearRampToValueAtTimeMethodCallback, 0, 2, V8DOMConfiguration::ExposedToAllScripts},
    {"exponentialRampToValueAtTime", AudioParamV8Internal::exponentialRampToValueAtTimeMethodCallback, 0, 2, V8DOMConfiguration::ExposedToAllScripts},
    {"setTargetAtTime", AudioParamV8Internal::setTargetAtTimeMethodCallback, 0, 3, V8DOMConfiguration::ExposedToAllScripts},
    {"setValueCurveAtTime", AudioParamV8Internal::setValueCurveAtTimeMethodCallback, 0, 3, V8DOMConfiguration::ExposedToAllScripts},
    {"cancelScheduledValues", AudioParamV8Internal::cancelScheduledValuesMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
};

static void installV8AudioParamTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
    functionTemplate->ReadOnlyPrototype();

    v8::Local<v8::Signature> defaultSignature;
    defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "AudioParam", v8::Local<v8::FunctionTemplate>(), V8AudioParam::internalFieldCount,
        0, 0,
        V8AudioParamAccessors, WTF_ARRAY_LENGTH(V8AudioParamAccessors),
        V8AudioParamMethods, WTF_ARRAY_LENGTH(V8AudioParamMethods));
    v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
    ALLOW_UNUSED_LOCAL(instanceTemplate);
    v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
    ALLOW_UNUSED_LOCAL(prototypeTemplate);

    // Custom toString template
    functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}

v8::Local<v8::FunctionTemplate> V8AudioParam::domTemplate(v8::Isolate* isolate)
{
    return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8AudioParamTemplate);
}

bool V8AudioParam::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
    return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}

v8::Local<v8::Object> V8AudioParam::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
    return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}

AudioParam* V8AudioParam::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
    return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}

void V8AudioParam::refObject(ScriptWrappable* scriptWrappable)
{
}

void V8AudioParam::derefObject(ScriptWrappable* scriptWrappable)
{
}

} // namespace blink
#endif // ENABLE(WEB_AUDIO)


text:
<?php
header('content-type: application/json; charset=utf-8');

ini_set( 'display_errors', true );
error_reporting(E_ALL & ~ E_NOTICE & ~ E_DEPRECATED);

include('../../class/mysql_crud.php');

$guid_produto = $_POST["produto"];
$guid_pedido  = $_POST["pedido"];

$db = new Database();
$db->connect();
$db->sql("SELECT a.guid as guidproduto,
                 a.preco as valorproduto,
                 b.guid as guidlan,
                 b.guid_produto,
                 b.guid_pedido
                 FROM cad_produtos AS a
                 INNER JOIN lanc_listprodpedido AS b
                 ON a.guid = b.guid_produto WHERE guid_pedido = '$guid_pedido' AND guid_produto = '$guid_produto'");
$res = $db->numRows();

echo ($res);


text:
package com.atteo.jello.space;

import com.atteo.jello.Record;
import com.atteo.jello.store.ListPage;
import com.atteo.jello.store.PagedFile;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;

@Singleton
public class Hybrid implements SpaceManagerPolicy {
	static {
		System.loadLibrary("Hybrid");
	}

	@Inject
	public Hybrid(
			final PagedFile pagedFile,
			final ListPage listPage,
			@Named("pageSize") final short pageSize,
			@Named("blockSize") final short blockSize,
			@Named("maxRecordSize") final int maxRecordSize,
			@Named("freeSpaceInfosPerPage") final short freeSpaceInfosPerPage,
			@Named("freeSpaceInfoSize") final short freeSpaceInfoSize,
			@Named("freeSpaceInfoPageCapacity") final short freeSpaceInfoPageCapacity,
			@Named("freeSpaceInfoPageId") final int pageFreeSpaceInfo,
			@Named("nextFitHistogramClasses") final int histogramClasses) {
		init(pagedFile, listPage, pageSize, blockSize, maxRecordSize,
				freeSpaceInfosPerPage, freeSpaceInfoSize,
				freeSpaceInfoPageCapacity, pageFreeSpaceInfo, histogramClasses);
	}

	public native int acquirePage();

	public native boolean acquireRecord(Record record, int length);

	public native void commit();

	public native void create();

	public native boolean isPageUsed(int id);

	public native boolean load();

	public native boolean reacquireRecord(Record record, int length);

	public native void releasePage(int id);

	public native void releaseRecord(Record record);

	public native void setPageUsed(int id, boolean used);

	private native void init(PagedFile pagedFile, ListPage listPage,
			short pageSize, short blockSize, int maxRecordSize,
			short freeSpaceInfosPerPage, short freeSpaceInfoSize,
			short freeSpaceInfoPageCapacity, int pageFreeSpaceInfo,
			int histogramClasses);
}


text:
DROP TABLE IF EXISTS test.Schema;
CREATE TABLE test.Schema (
  `id` int(12) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `toBoolean` float NOT NULL,
  `toFloat` int(11) UNSIGNED NOT NULL,
  `toInt` tinyint(1) UNSIGNED NOT NULL,
  `toLongText` tinyint(1) NOT NULL,
  `toText` text NOT NULL,
  `toDate` tinyint(1) NOT NULL
);


text:
@import UIKit;
@import CoreGraphics;

NS_ASSUME_NONNULL_BEGIN

@interface UIImage (IGRInstaFilters)

- (UIImage *)igr_imageWithDefaultOrientation;
- (UIImage *)igr_aspectFillImageWithSize:(CGSize)size;

@end

NS_ASSUME_NONNULL_END


text:
package com.ogaclejapan.arclayout;

import android.annotation.TargetApi;
import android.os.Build;
import android.view.Gravity;

public final class ArcOrigin {

    public static final int TOP = Gravity.TOP;

    public static final int BOTTOM = Gravity.BOTTOM;

    public static final int LEFT = Gravity.LEFT;

    public static final int RIGHT = Gravity.RIGHT;

    public static final int CENTER = Gravity.CENTER;

    public static final int CENTER_HORIZONTAL = Gravity.CENTER_HORIZONTAL;

    public static final int CENTER_VERTICAL = Gravity.CENTER_VERTICAL;

    public static final int START = Gravity.START;

    public static final int END = Gravity.END;

    public static final int VERTICAL_MASK = Gravity.VERTICAL_GRAVITY_MASK;

    public static final int HORIZONTAL_MASK = Gravity.HORIZONTAL_GRAVITY_MASK;

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static int getAbsoluteOrigin(int origin, int layoutDirection) {
        return Gravity.getAbsoluteGravity(origin, layoutDirection);
    }

    private ArcOrigin() {
        //No instances.
    }

}


text:
/*
*  FILE          ConsoleComponent.h
*  AUTHOR        Brendon Clifford
*  DESCRIPTION
*    Declaration for console interface features.
*/
#pragma once
#include "WindowComponent.h"

namespace GUI
{
  class ConsoleComponent : public WindowComponent
  {
    public:
      ConsoleComponent();

      virtual void Initialize(void);
      virtual void Display(void);
      virtual void Destroy(void);
  };
}


text:
class ExtendableError extends Error {
    constructor(message) {
        super(message);
        this.name    = this.constructor.name;
        this.message = message;
        if ( typeof Error.captureStackTrace === 'function' ) {
            Error.captureStackTrace(this, this.constructor);
        }
        else {
            this.stack = (new Error(message)).stack;
        }
    }
}
class TideError extends ExtendableError {
    constructor(message) {
        super(message);
    }
}

export class RouterError extends TideError {}
export class MatchNotFound extends RouterError {}
export class DispatchError extends RouterError {}


text:
aethernauts.service('context', ['renderer', function(renderer)                  {
    var service             = {};

    service.area = "";

    return service;
}]);


text:
<?php

namespace spec\LdapTools\Ldif;

use LdapTools\Ldif\Entry\LdifEntryAdd;
use LdapTools\Ldif\Entry\LdifEntryDelete;
use LdapTools\Ldif\Entry\LdifEntryModify;
use LdapTools\Ldif\Ldif;
use PhpSpec\ObjectBehavior;

class LdifSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('LdapTools\Ldif\Ldif');
    }

    function it_should_set_the_ldif_version()
    {
        $this->setVersion(1)->shouldReturnAnInstanceOf('LdapTools\Ldif\Ldif');
    }

    function it_should_get_a_ldif_entry_builder()
    {
        $this->entry()->shouldReturnAnInstanceOf('LdapTools\Ldif\LdifEntryBuilder');
    }

    function it_should_add_a_comment()
    {
        $this->addComment('test')->shouldReturnAnInstanceOf('LdapTools\Ldif\Ldif');
        $this->getComments()->shouldHaveCount(1);

        $this->addComment('foo', 'bar');
        $this->getComments()->shouldHaveCount(3);

        $this->getComments()->shouldBeEqualTo(['test', 'foo', 'bar']);
    }

    function it_should_add_an_entry()
    {
        $delete = new LdifEntryDelete('dc=foo,dc=bar');
        $add = new LdifEntryAdd('dc=foo,dc=bar', ['foo' => 'bar']);
        $modify = new LdifEntryModify('dc=foo,dc=bar');

        $this->addEntry($delete)->shouldReturnAnInstanceOf('LdapTools\Ldif\Ldif');
        $this->getEntries()->shouldHaveCount(1);

        $this->addEntry($add, $modify)->getEntries()->shouldHaveCount(3);
        $this->getEntries()->shouldBeEqualTo([$delete, $add, $modify]);
    }

    function it_should_get_the_ldif_string()
    {
        $delete = new LdifEntryDelete('dc=foo,dc=bar');
        $add = new LdifEntryAdd('dc=foo,dc=bar', ['foo' => 'bar']);
        $this->addEntry($delete, $add);
        $this->addComment('foo');

        $ldif =
              "# foo\r\n"
            . "version: 1\r\n"
            . "\r\n"
            . "dn: dc=foo,dc=bar\r\n"
            . "changetype: delete\r\n"
            . "\r\n"
            . "dn: dc=foo,dc=bar\r\n"
            . "changetype: add\r\n"
            . "foo: bar\r\n";

        $this->toString()->shouldBeEqualTo($ldif);
    }

    function it_should_get_the_operations_for_the_ldif_entries()
    {
        $delete = new LdifEntryDelete('dc=foo,dc=bar');
        $add = new LdifEntryAdd('dc=foo,dc=bar', ['foo' => 'bar']);
        $this->addEntry($delete, $add);

        $this->toOperations()->shouldBeLike([$delete->toOperation(), $add->toOperation()]);
    }

    function it_should_set_the_line_endings_for_the_ldif_string()
    {
        $delete = new LdifEntryDelete('dc=foo,dc=bar');
        $add = new LdifEntryAdd('dc=foo,dc=bar', ['foo' => 'bar']);
        $this->addEntry($delete, $add);
        $this->addComment('foo');
        $this->setLineEnding(Ldif::LINE_ENDING['UNIX']);

        $ldif =
            "# foo\n"
            . "version: 1\n"
            . "\n"
            . "dn: dc=foo,dc=bar\n"
            . "changetype: delete\n"
            . "\n"
            . "dn: dc=foo,dc=bar\n"
            . "changetype: add\n"
            . "foo: bar\n";

        $this->toString()->shouldBeEqualTo($ldif);
    }

    function it_should_throw_an_exception_on_an_invalid_line_ending_type()
    {
        $this->shouldThrow('\LdapTools\Exception\InvalidArgumentException')->duringSetLineEnding('foo');
    }

    function it_should_have_a_line_folding_set_to_false_by_default_with_a_length_of_76()
    {
        $this->getLineFolding()->shouldBeEqualTo(false);
        $this->getMaxLineLength(76);
    }

    function it_should_fold_long_lines_when_specified()
    {
        $dn = 'cn=foo,dc=example,dc=local';
        $description = 'This is a long line that will go over the 76 char limit and then be continued on the next line. We dont need no stinking wordwrap.';
        $givenName = 'foo';
        $comment = 'This is an LDIF file with some really long lines just to test some folded lines so they show up on the next.';
        $comment1 = 'An example comment.';
        $comment2 = 'This comment will go past the line length and should also be split onto the next line.';

        $add = new LdifEntryAdd($dn, [
            'description' => $description,
            'givenName' => $givenName,
        ]);
        $add->addComment($comment1, $comment2);
        $this->addEntry($add);
        $this->addComment($comment);

        $ldif =
            "# This is an LDIF file with some really long lines just to test some folded li\r\n"
            . " nes so they show up on the next.\r\n"
            . "version: 1\r\n"
            . "\r\n"
            . "# $comment1\r\n"
            . "# This comment will go past the line length and should also be split onto the \r\n"
            . " next line.\r\n"
            . "dn: cn=foo,dc=example,dc=local\r\n"
            . "changetype: add\r\n"
            . "description: This is a long line that will go over the 76 char limit and then be continue\r\n"
            . " d on the next line. We dont need no stinking wordwrap.\r\n"
            . "givenName: $givenName\r\n";

        $this->setLineFolding(true);
        $this->toString()->shouldBeEqualTo($ldif);
    }
}


text:
namespace com.keyman.dom.targets {
  export class TextArea extends OutputTarget {
    root: HTMLTextAreaElement;

    /**
     * Tracks the most recently-cached selection start index.
     */
    private _cachedSelectionStart: number

    /**
     * Tracks the most recently processed, extended-string-based selection start index.
     * When the element's selectionStart value changes, this should be invalidated.
     */
    private processedSelectionStart: number;

    /**
     * Tracks the most recently processed, extended-string-based selection end index.
     * When the element's selectionEnd value changes, this should be invalidated.
     */
    private processedSelectionEnd: number;

    /**
     * Used to temporarily store the y-axis scroll coordinate.
     */
    private scrollTop?: number;

    /**
     * Used to temporarily store the x-axis scroll coordinate.
     */
    private scrollLeft?: number;

    constructor(ele: HTMLTextAreaElement) {
      super();

      this.root = ele;
      this._cachedSelectionStart = -1;
    }

    get isSynthetic(): boolean {
      return false;
    }

    getElement(): HTMLTextAreaElement {
      return this.root;
    }

    clearSelection(): void {
      // Processes our codepoint-based variants of selectionStart and selectionEnd.
      this.getCaret(); // updates processedSelectionStart if required
      this.root.value = this.root.value._kmwSubstring(0, this.processedSelectionStart) + this.root.value._kmwSubstring(this.processedSelectionEnd); //I3319

      this.setCaret(this.processedSelectionStart);
    }

    isSelectionEmpty(): boolean {
      return this.root.selectionStart == this.root.selectionEnd;
    }

    hasSelection(): boolean {
      return true;
    }

    invalidateSelection() {
      // Since .selectionStart will never return this value, we use it to indicate
      // the need to refresh our processed indices.
      this._cachedSelectionStart = -1;
    }

    getCaret(): number {
      if(this.root.selectionStart != this._cachedSelectionStart) {
        this._cachedSelectionStart = this.root.selectionStart; // KMW-1
        this.processedSelectionStart = this.root.value._kmwCodeUnitToCodePoint(this.root.selectionStart); // I3319
        this.processedSelectionEnd = this.root.value._kmwCodeUnitToCodePoint(this.root.selectionEnd);     // I3319
      }
      return this.root.selectionDirection == 'forward' ? this.processedSelectionEnd : this.processedSelectionStart;
    }

    getDeadkeyCaret(): number {
      return this.getCaret();
    }

    setCaret(caret: number) {
      this.setSelection(caret, caret, "none");
    }

    setSelection(start: number, end: number, direction: "forward" | "backward" | "none") {
      let domStart = this.root.value._kmwCodePointToCodeUnit(start);
      let domEnd = this.root.value._kmwCodePointToCodeUnit(end);
      this.root.setSelectionRange(domStart, domEnd, direction);

      this.processedSelectionStart = start;
      this.processedSelectionEnd = end;

      Utils.forceScroll(this.root);
    }

    getSelectionDirection(): "forward" | "backward" | "none" {
      return this.root.selectionDirection;
    }

    getTextBeforeCaret(): string {
      this.getCaret();
      return this.getText()._kmwSubstring(0, this.processedSelectionStart);
    }

    setTextBeforeCaret(text: string) {
      this.getCaret();
      let selectionLength = this.processedSelectionEnd - this.processedSelectionStart;
      let direction = this.getSelectionDirection();
      let newCaret = text._kmwLength();
      this.root.value = text + this.getText()._kmwSubstring(this.processedSelectionStart);

      this.setSelection(newCaret, newCaret + selectionLength, direction);
    }

    protected setTextAfterCaret(s: string) {
      let c = this.getCaret();
      let direction = this.getSelectionDirection();

      this.root.value = this.getTextBeforeCaret() + s;
      this.setSelection(this.processedSelectionStart, this.processedSelectionEnd, direction);
    }

    getTextAfterCaret(): string {
      this.getCaret();
      return this.getText()._kmwSubstring(this.processedSelectionEnd);
    }

    getText(): string {
      return this.root.value;
    }

    deleteCharsBeforeCaret(dn: number) {
      if(dn > 0) {
        let curText = this.getTextBeforeCaret();
        let caret = this.processedSelectionStart;

        if(dn > caret) {
          dn = caret;
        }

        this.adjustDeadkeys(-dn);
        this.setTextBeforeCaret(curText.kmwSubstring(0, caret - dn));
        this.setCaret(caret - dn);
      }
    }

    insertTextBeforeCaret(s: string) {
      if(!s) {
        return;
      }

      let caret = this.getCaret();
      let front = this.getTextBeforeCaret();
      let back = this.getText()._kmwSubstring(this.processedSelectionStart);

      this.adjustDeadkeys(s._kmwLength());
      this.root.value = front + s + back;
      this.setCaret(caret + s._kmwLength());
    }

    handleNewlineAtCaret(): void {
      this.insertTextBeforeCaret('\n');
    }

    doInputEvent() {
      this.dispatchInputEventOn(this.root);
    }
  }
}


text:
package egger.software.an_collections;

import java.util.*;

public class Maps {

    enum Color {red, green}

    ;

    public static void main(String[] args) {

        // default map
        Map<Integer, String> hashMap = new HashMap();
        hashMap.put(1, "test1");
        hashMap.put(2, "test2");
        hashMap.put(3, "test3");
        hashMap.put(3, "test4");

        hashMap.entrySet().forEach(System.out::println);

        hashMap.putIfAbsent(4, "test4");
        hashMap.putIfAbsent(4, "test5");

        hashMap.entrySet().forEach(System.out::println);

        hashMap.compute(5, (key, oldValue) -> "test5 " + oldValue);

        hashMap.entrySet().forEach(System.out::println);

        System.out.println(hashMap.get(1));
        System.out.println(hashMap.getOrDefault(10, "default"));
        System.out.println(hashMap.keySet());
        System.out.println(hashMap.values());
        System.out.println(hashMap.containsKey(1));
        System.out.println(hashMap.containsValue("test"));

        hashMap.replace(1, "test1 1");
        hashMap.remove(2);
        hashMap.entrySet().forEach(System.out::println);

        Map<Integer, String> targetMap = new HashMap<>();
        hashMap.forEach((key, value) -> targetMap.put(key * 10, value + " - " + value));
        targetMap.entrySet().forEach(System.out::println);

        WeakHashMap<String, String> weekHashMap = new WeakHashMap<>(); // Useful for caches. Key are garbage collected.
        EnumMap<Color, String> enumHashMap = new EnumMap<>(Color.class);

        // implement hashCode and equals
        System.out.println("-- hashCode and equals");
        System.out.println();

        Map<WrongHashClass, Integer> wrongHashCodeTest = new HashMap<>();
        wrongHashCodeTest.put(new WrongHashClass(1,"a"), 1);
        wrongHashCodeTest.put(new WrongHashClass(1,"a"), 2);
        wrongHashCodeTest.entrySet().forEach(System.out::println);

        System.out.println("--");

        Map<CorrectHashClass, Integer> correctHashCodeTest = new HashMap<>();
        correctHashCodeTest.put(new CorrectHashClass(1,"a"), 1);
        correctHashCodeTest.put(new CorrectHashClass(1,"a"), 2);
        correctHashCodeTest.entrySet().forEach(System.out::println);

    }

    public static class WrongHashClass {

        private Random rnd = new Random();

        private final int a;
        private final String b;

        public WrongHashClass(int a, String b) {
            this.a = a;
            this.b = b;
        }

        // equals always means same hash code!
        // same hash code does not automatically mean equals!

        @Override
        public int hashCode() {
            return rnd.nextInt();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            WrongHashClass that = (WrongHashClass) o;

            if (a != that.a) return false;
            return b != null ? b.equals(that.b) : that.b == null;
        }

        @Override
        public String toString() {
            return "RandomHashClass{" +
                    "a=" + a +
                    ", b='" + b + '\'' +
                    '}';
        }
    }

    public static class CorrectHashClass {

        private final int a;
        private final String b;

        public CorrectHashClass(int a, String b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public int hashCode() {
            int result = a;
            result = 31 * result + (b != null ? b.hashCode() : 0);
            return result;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            CorrectHashClass that = (CorrectHashClass) o;

            if (a != that.a) return false;
            return b != null ? b.equals(that.b) : that.b == null;
        }

        @Override
        public String toString() {
            return "CorrectHashClass{" +
                    "a=" + a +
                    ", b='" + b + '\'' +
                    '}';
        }
    }

}


text:
#ifndef GOAL_H_
#define GOAL_H_

#include"ast.h"
#include"ast_translation.h"
#include"ast_printer.h"
#include"for_each_expr.h"
#include"ref.h"
#include"ref_vector.h"
#include"ref_buffer.h"

class goal {
public:
    enum precision {
        PRECISE,
        UNDER,   // goal is the product of an under-approximation
        OVER,    // goal is the product of an over-approximation
        UNDER_OVER // goal is garbage: the produce of combined under and over approximation steps.
    };

    static precision mk_union(precision p1, precision p2);

protected:
    ast_manager &         m_manager;
    unsigned              m_ref_count;
    expr_array            m_forms;
    expr_array            m_proofs;
    expr_dependency_array m_dependencies;
    // attributes
    unsigned              m_depth:26;          // depth of the goal in the goal tree.
    unsigned              m_models_enabled:1;  // model generation is enabled.
    unsigned              m_proofs_enabled:1;  // proof production is enabled. m_manager.proofs_enabled() must be true if m_proofs_enabled == true
    unsigned              m_core_enabled:1;    // unsat core extraction is enabled.
    unsigned              m_inconsistent:1;    // true if the goal is known to be inconsistent.
    unsigned              m_precision:2;       // PRECISE, UNDER, OVER.

    void push_back(expr * f, proof * pr, expr_dependency * d);
    void quick_process(bool save_first, expr_ref & f, expr_dependency * d);
    void process_and(bool save_first, app * f, proof * pr, expr_dependency * d, expr_ref & out_f, proof_ref & out_pr);
    void process_not_or(bool save_first, app * f, proof * pr, expr_dependency * d, expr_ref & out_f, proof_ref & out_pr);
    void slow_process(bool save_first, expr * f, proof * pr, expr_dependency * d, expr_ref & out_f, proof_ref & out_pr);
    void slow_process(expr * f, proof * pr, expr_dependency * d);
    unsigned get_idx(expr * f) const;
    unsigned get_not_idx(expr * f) const;
    void shrink(unsigned j);
    void reset_core();

public:
    goal(ast_manager & m, bool models_enabled = true, bool core_enabled = false);
    goal(ast_manager & m, bool proofs_enabled, bool models_enabled, bool core_enabled);
    goal(goal const & src);
    // Copy configuration: depth, models/proofs/cores flags, and precision from src.
    // The assertions are not copied
    goal(goal const & src, bool);
    ~goal();

    void inc_ref() { ++m_ref_count; }
    void dec_ref() { --m_ref_count; if (m_ref_count == 0) dealloc(this); }

    ast_manager & m() const { return m_manager; }

    unsigned depth() const { return m_depth; }
    bool models_enabled() const { return m_models_enabled; }
    bool proofs_enabled() const { return m_proofs_enabled; }
    bool unsat_core_enabled() const { return m_core_enabled; }
    bool inconsistent() const { return m_inconsistent; }
    precision prec() const { return static_cast<precision>(m_precision); }

    void set_depth(unsigned d) { m_depth = d; }
    void inc_depth() { m_depth++; }
    void set_prec(precision d) { m_precision = d; }
    void updt_prec(precision d) { m_precision = mk_union(prec(), d); }

    void reset_all(); // reset goal and precision and depth attributes.
    void reset(); // reset goal but preserve precision and depth attributes.

    void copy_to(goal & target) const;
    void copy_from(goal const & src) { src.copy_to(*this); }

    void assert_expr(expr * f, proof * pr, expr_dependency * d);
    void assert_expr(expr * f, expr_dependency * d);
    void assert_expr(expr * f, expr * d) { assert_expr(f, m().mk_leaf(d)); }
    void assert_expr(expr * f) { assert_expr(f, static_cast<expr_dependency*>(0)); }

    unsigned size() const { return m().size(m_forms); }

    unsigned num_exprs() const;

    expr * form(unsigned i) const { return m().get(m_forms, i); }
    proof * pr(unsigned i) const { return proofs_enabled() ? static_cast<proof*>(m().get(m_proofs, i)) : 0; }
    expr_dependency * dep(unsigned i) const { return unsat_core_enabled() ? m().get(m_dependencies, i) : 0; }

    void update(unsigned i, expr * f, proof * pr = 0, expr_dependency * dep = 0);

    void get_formulas(ptr_vector<expr> & result);

    void elim_true();
    void elim_redundancies();

    void display(ast_printer & prn, std::ostream & out) const;
    void display(ast_printer_context & ctx) const;
    void display(std::ostream & out) const;
    void display_ll(std::ostream & out) const;
    void display_as_and(std::ostream & out) const;
    void display_dimacs(std::ostream & out) const;
    void display_with_dependencies(ast_printer & prn, std::ostream & out) const;
    void display_with_dependencies(ast_printer_context & ctx) const;
    void display_with_dependencies(std::ostream & out) const;

    bool sat_preserved() const;
    bool unsat_preserved() const;
    bool is_decided_sat() const;
    bool is_decided_unsat() const;
    bool is_decided() const;
    bool is_well_sorted() const;

    goal * translate(ast_translation & translator) const;
};

std::ostream & operator<<(std::ostream & out, goal::precision p);

typedef ref<goal> goal_ref;
typedef sref_vector<goal> goal_ref_vector;
typedef sref_buffer<goal> goal_ref_buffer;

template<typename GoalCollection>
inline bool is_decided(GoalCollection const & c) { return c.size() == 1 && c[0]->is_decided(); }
template<typename GoalCollection>
inline bool is_decided_sat(GoalCollection const & c) { return c.size() == 1 && c[0]->is_decided_sat(); }
template<typename GoalCollection>
inline bool is_decided_unsat(GoalCollection const & c) { return c.size() == 1 && c[0]->is_decided_unsat(); }

template<typename ForEachProc>
void for_each_expr_at(ForEachProc& proc, goal const & s) {
    expr_mark visited;
    for (unsigned i = 0; i < s.size(); ++i) {
        for_each_expr(proc, visited, s.form(i));
    }
}

bool is_equal(goal const & g1, goal const & g2);

template<typename Predicate>
bool test(goal const & g, Predicate & proc) {
    expr_fast_mark1 visited;
    try {
        unsigned sz = g.size();
        for (unsigned i = 0; i < sz; i++)
            quick_for_each_expr(proc, visited, g.form(i));
    }
    catch (typename Predicate::found) {
        return true;
    }
    return false;
}

template<typename Predicate>
bool test(goal const & g) {
    Predicate proc(g.m());
    return test(g, proc);
}

#endif


text:
namespace Simplexcel
{
    /// <summary>
    /// Worksheet view selection.
    /// </summary>
    public sealed class Selection
    {
		/// <summary>
		/// The pane to which this selection belongs.
		/// </summary>
		public Panes ActivePane { get; set; }

		/// <summary>
		/// Location of the active cell. E.g., "A1"
		/// </summary>
		public string ActiveCell { get; set; }

        // activeCellId
        // sqref

        /// <summary>
        /// Create a new selection
        /// </summary>
        public Selection()
        {
            ActivePane = Panes.TopLeft;
        }
    }
}


text:
class AlterProjectIdAndOrderFromProjectQuestions < ActiveRecord::Migration
  def change
    remove_column :project_questions, :project_id
    add_column :project_questions, :load_order, :integer
  end
end


text:
'use strict';

var callable = require('../../object/valid-callable'),
    apply = Function.prototype.apply;

module.exports = function () /*…args*/{
	var fn = callable(this),
	    args = arguments;

	return function () {
		return apply.call(fn, this, args);
	};
};

//# sourceMappingURL=lock-compiled.js.map


text:
package io.sitoolkit.wt.domain.operation.selenium;

import org.junit.Test;
import io.sitoolkit.wt.domain.tester.TestBase;

/**
 *
 * @author yuichi.kuwahara
 */
public class DrawLineOperationTest extends TestBase {

  @Test
  public void test001() {
    test();
  }

  @Override
  protected String getTestScriptPath() {
    return "src/test/resources/DrawTestScript.csv";
  }

  @Override
  protected String getSheetName() {
    return "TestScript";
  }
}


text:
package com.ECS.client.jax;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{http://webservices.amazon.com/AWSECommerceService/2011-08-01}Item" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "item"
})
@XmlRootElement(name = "RelatedItem")
public class RelatedItem {

    @XmlElement(name = "Item")
    protected Item item;

    /**
     * Gets the value of the item property.
     *
     * @return
     *     possible object is
     *     {@link Item }
     *
     */
    public Item getItem() {
        return item;
    }

    /**
     * Sets the value of the item property.
     *
     * @param value
     *     allowed object is
     *     {@link Item }
     *
     */
    public void setItem(Item value) {
        this.item = value;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Nova Hedwigia 65: 225 (1980)

#### Original name
Clitopilus prostratus Cleland

### Remarks
null


text:
import {ParamRegistry} from "../registries/ParamRegistry";
/**
 * @module common/filters
 */
/** */
import {HeaderParamsFilter} from "../components/HeaderParamsFilter";

/**
 * HeaderParams return the value from [request.params](http://expressjs.com/en/4x/api.html#req.params) object.
 *
 * #### Example
 *
 * ```typescript
 * @Controller('/')
 * class MyCtrl {
 *    @Get('/')
 *    get(@Header() body: any) {
 *       console.log('Entire body', body);
 *    }
 *
 *    @Get('/')
 *    get(@Header('x-token') token: string) {
 *       console.log('token', id);
 *    }
 * }
 * ```
 * > For more information on deserialization see [converters](docs/converters.md) page.
 *
 * @param expression The path of the property to get.
 * @decorator
 * @returns {Function}
 */
export function HeaderParams(expression: string): Function {
    return ParamRegistry.decorate(HeaderParamsFilter, {expression});
}


text:
package com.haogrgr.test.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * from http://blog.csdn.net/ruixue0117/article/details/22829557
 *
 * @author desheng.tu
 * @since 2015年11月6日 下午3:55:03
 *
 */
public class VerifyCodes {

	//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
	public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
	private static Random random = new Random();

	/**
	 * 使用系统默认字符源生成验证码
	 * @param verifySize 验证码长度
	 * @return
	 */
	public static String generateVerifyCode(int verifySize) {
		return generateVerifyCode(verifySize, VERIFY_CODES);
	}

	/**
	 * 使用指定源生成验证码
	 * @param verifySize 验证码长度
	 * @param sources 验证码字符源
	 * @return
	 */
	public static String generateVerifyCode(int verifySize, String sources) {
		if (sources == null || sources.length() == 0) {
			sources = VERIFY_CODES;
		}
		int codesLen = sources.length();
		Random rand = new Random(System.currentTimeMillis());
		StringBuilder verifyCode = new StringBuilder(verifySize);
		for (int i = 0; i < verifySize; i++) {
			verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
		}
		return verifyCode.toString();
	}

	/**
	 * 生成随机验证码文件,并返回验证码值
	 * @param w
	 * @param h
	 * @param outputFile
	 * @param verifySize
	 * @return
	 * @throws IOException
	 */
	public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
		String verifyCode = generateVerifyCode(verifySize);
		outputImage(w, h, outputFile, verifyCode);
		return verifyCode;
	}

	/**
	 * 输出随机验证码图片流,并返回验证码值
	 * @param w
	 * @param h
	 * @param os
	 * @param verifySize
	 * @return
	 * @throws IOException
	 */
	public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
		String verifyCode = generateVerifyCode(verifySize);
		outputImage(w, h, os, verifyCode);
		return verifyCode;
	}

	/**
	 * 生成指定验证码图像文件
	 * @param w
	 * @param h
	 * @param outputFile
	 * @param code
	 * @throws IOException
	 */
	public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
		if (outputFile == null) {
			return;
		}
		File dir = outputFile.getParentFile();
		if (!dir.exists()) {
			dir.mkdirs();
		}
		try {
			outputFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(outputFile);
			outputImage(w, h, fos, code);
			fos.close();
		} catch (IOException e) {
			throw e;
		}
	}

	/**
	 * 输出指定验证码图片流
	 * @param w
	 * @param h
	 * @param os
	 * @param code
	 * @throws IOException
	 */
	public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
		int verifySize = code.length();
		BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Random rand = new Random();
		Graphics2D g2 = image.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		Color[] colors = new Color[5];
		Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
				Color.ORANGE, Color.PINK, Color.YELLOW };
		float[] fractions = new float[colors.length];
		for (int i = 0; i < colors.length; i++) {
			colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
			fractions[i] = rand.nextFloat();
		}
		Arrays.sort(fractions);

		g2.setColor(Color.GRAY);// 设置边框色
		g2.fillRect(0, 0, w, h);

		Color c = getRandColor(200, 250);
		g2.setColor(c);// 设置背景色
		g2.fillRect(0, 2, w, h - 4);

		//绘制干扰线
		Random random = new Random();
		g2.setColor(getRandColor(160, 200));// 设置线条的颜色
		for (int i = 0; i < 20; i++) {
			int x = random.nextInt(w - 1);
			int y = random.nextInt(h - 1);
			int xl = random.nextInt(6) + 1;
			int yl = random.nextInt(12) + 1;
			g2.drawLine(x, y, x + xl + 40, y + yl + 20);
		}

		// 添加噪点
		float yawpRate = 0.05f;// 噪声率
		int area = (int) (yawpRate * w * h);
		for (int i = 0; i < area; i++) {
			int x = random.nextInt(w);
			int y = random.nextInt(h);
			int rgb = getRandomIntColor();
			image.setRGB(x, y, rgb);
		}

		shear(g2, w, h, c);// 使图片扭曲

		g2.setColor(getRandColor(100, 160));
		int fontSize = h - 4;
		Font font = new Font("Algerian", Font.ITALIC, fontSize);
		g2.setFont(font);
		char[] chars = code.toCharArray();
		for (int i = 0; i < verifySize; i++) {
			AffineTransform affine = new AffineTransform();
			affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i
					+ fontSize / 2, h / 2);
			g2.setTransform(affine);
			g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
		}

		g2.dispose();
		ImageIO.write(image, "jpg", os);
	}

	private static Color getRandColor(int fc, int bc) {
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	private static int getRandomIntColor() {
		int[] rgb = getRandomRgb();
		int color = 0;
		for (int c : rgb) {
			color = color << 8;
			color = color | c;
		}
		return color;
	}

	private static int[] getRandomRgb() {
		int[] rgb = new int[3];
		for (int i = 0; i < 3; i++) {
			rgb[i] = random.nextInt(255);
		}
		return rgb;
	}

	private static void shear(Graphics g, int w1, int h1, Color color) {
		shearX(g, w1, h1, color);
		shearY(g, w1, h1, color);
	}

	private static void shearX(Graphics g, int w1, int h1, Color color) {

		int period = random.nextInt(2);

		boolean borderGap = true;
		int frames = 1;
		int phase = random.nextInt(2);

		for (int i = 0; i < h1; i++) {
			double d = (double) (period >> 1)
					* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
			g.copyArea(0, i, w1, 1, (int) d, 0);
			if (borderGap) {
				g.setColor(color);
				g.drawLine((int) d, i, 0, i);
				g.drawLine((int) d + w1, i, w1, i);
			}
		}

	}

	private static void shearY(Graphics g, int w1, int h1, Color color) {

		int period = random.nextInt(40) + 10; // 50;

		boolean borderGap = true;
		int frames = 20;
		int phase = 7;
		for (int i = 0; i < w1; i++) {
			double d = (double) (period >> 1)
					* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
			g.copyArea(i, 0, 1, h1, 0, (int) d);
			if (borderGap) {
				g.setColor(color);
				g.drawLine(i, (int) d, i, 0);
				g.drawLine(i, (int) d + h1, i, h1);
			}

		}

	}

	public static void main(String[] args) throws IOException {
		File dir = new File("F:/verifies");
		int w = 200, h = 80;
		for (int i = 0; i < 50; i++) {
			String verifyCode = generateVerifyCode(4);
			File file = new File(dir, verifyCode + ".jpg");
			outputImage(w, h, file, verifyCode);
		}
	}
}


text:
For this challenge, I evaluated two ORM modules [Sequelize](http://sequelizejs.com) and [jugglingdb](https://github.com/1602/jugglingdb). The jugglingdb API is similar to moongoose API, and it supports ***Redis** and ***MongoDB***, but there seems no way to add `json` or `jsonb` type. For the relational database support, the Sequelize is far superior than jugglingdb. The Sequelize maps correctly `json`, `jsonb` or `array` data type and also creates correctly the constraints like `NOT NULL` or `UNIQUE`. So the solution is implemented with the Sequelize module.

## App Demo Screencast

[App Demo Screencast](https://www.youtube.com/watch?v=mI4Oj4m1ceE)

[Code Overview Screencast](https://www.youtube.com/watch?v=kfFy2ltywGI)

## Heroku Demo App

[Heroku demo app](http://mean-postgresql.herokuapp.com/) is deployed in the heroku.

The heroku app has one regular use ***topcoder3@gmail.com*** for your test, the password is `password1`.

Since local deploy is simple, I recommend not to use the heroku deploy for reviewing. If multiple reviewers access at the same time, there can be undesirable results.

## REST API Documentation

The [REST API Documentation](http://docs.meanpostgres.apiary.io/) is created in the apiary.io.

## Prerequisites
Please go over [MEAN.IO documentation](http://mean.io/#!/docs) to have a basic understanding about the MEAN.IO.

The MEAN.IO is built with `Node.js` and various npm modules. I recommend to install the latest `Node.js`.

The MEAN.IO application requires the `MongoDB`, please install MongoDB locally. It's possible to use a remote MongoDB from [mongolab.com](https://mongolab.com) or any other provider, but recommend to install local one.

This application requires `PostgreSQL 9.4` which supports ***jsonb*** data type, currently `Beta 2` is available. I installed the `PostgreSQL 9.4 Beta 2` with HomeBrew in Mac OS Mavericks.

	$ brew update
	$ brew uninstall postgresql		// if already installed
	$ brew install --devel postgresql

If you uses PgAdmin3, please upgrade the PgAdmin3 to `1.20.0 Beta 1` version to work with PostgreSQL 9.4.

## Configuration

The configuration for local deploy is in the `config/env/development.js`. Please configure MongoDB URL and PostgreSQL URL.

The default MongoDB URL:

	db: 'mongodb://localhost/mean-dev',

Please create `mean_test` database through PgAdmin tool.

The PostgreSQL database URL:

	pg: {
	    database: 'mean_test',
	    username: 'your-user',
	    password: 'xxx',
	    host: 'localhost',
	    port: 5432
	}

## Local Deploy

Please make sure PostgreSQL is running. It can be started by by `pg_ctl` or Mac OS `launchctl` or any other platform specific way.

Start MongoDB:

	$ mongod

This is a command from the MongoDB installed in Mac by [HomeBrew](http://brew.sh). In windows, follow [Install MongoDB on Windows](http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/).

Unzip the project zip file:  *[kbowerma] this step is not necessary since this code base is the core repo*

    $ unzip mean-postgresql.zip
    $ cd mean-postgresql

Install modules:

    $ npm install

Run the app. The app starts with `development` environment by default.

    $ npm start

Then, open a browser and go to:

    http://localhost:3000

Click `Register` link in the top right corner, register one regular user and sign with the registered user.

After sign in, click `Challenges` or `Create New Challenge` link on the top navigation menu.

## REST API Test

The API can be tested easily with Chrome plugin [Postman](https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en). The `portman.json` for testing the app REST API is included in the submission. Please import `postman.json` to the Chrome plugin Postman.

When testing API, please change values or ids based for your objects.

When API has an error, it returns the following JSON object.

	{
		error: "error message ...."
	}

## Heroku Deploy

Before you start make sure you have the [Heroku toolbelt](<https://toolbelt.heroku.com/")
installed. Create a MongoDB instance from [mongolab](https://mongolab.com)  or use one of heroku MongoDB addons (with `heroku addons:add mongolab`), then configure MongoDB database URL/user/password to the `config/env/production.js`.
If you use the heroku addon for mongolab you will be able to navigate to mongolab from the heroku app view and will see that mongo created a user for you, but you wont be able to see the password.   In order to see the app password you can type `heroku config`
from the console which will display the full monglab uri.

Note that the PostgreSQL is configured from DATABASE_URL, no need to configure it.
If you need to connect to the Heroku PostgreSQL database you can do it from your console.  ` heroku pg:psql` assuming you have psql installed.

	$ rm -rf .git
	$ git init
	$ git add .
	$ git commit -m "initial commit"
	$ heroku apps:create
	$ heroku config:set NODE_ENV=production
	$ heroku addons:add heroku-postgresql:dev
	$ heroku config:add BUILDPACK_URL=https://github.com/mbuchetics/heroku-buildpack-nodejs-grunt.git
	$ git push heroku master

The Heroku postgres is still in 9.3 version, which means `jsonb` type is not supported. To deploy the application to Heroku, please change `jsonb` to `json` in Challenge model ***technicalRequirements*** field, comment out the set method.

	technicalRequirements: {
		type: Sequelize.JSON, 	// JSONB is not supported in Heroku postgres.
		set: function(value) {
			return this.setDataValue('technicalRequirements', JSON.stringify(value));
		}
	},

## Challenges Table Schema

This is a Challenges table schema from PgAdmin3 created by Sequelize module.

```
	CREATE TABLE "Challenges"
	(
	  id serial NOT NULL,
	  "startDate" timestamp with time zone,
	  "endDate" timestamp with time zone,
	  title text NOT NULL,
	  overview text,
	  description character varying(140),
	  "functionalRequirements" json,
	  "technicalRequirements" jsonb,
	  tags text[],
	  "createdAt" timestamp with time zone NOT NULL,
	  "updatedAt" timestamp with time zone NOT NULL,
	  CONSTRAINT "Challenges_pkey" PRIMARY KEY (id),
	  CONSTRAINT "Challenges_title_key" UNIQUE (title)
	)
```

For the relational database, the Sequelize module works best, it maps everything correctly.

* The `json` data type in the ***functionalRequirements*** column is created correctly.
* The `jsonb` data type in the ***technicalRequirements*** column is created correctly.
* The `array` data type in the ***tags*** column is created correctly.
* The `length 140` is mapped correctly in the ***description*** column.
* The `NOT NULL` and `UNIQUE` constraints in the ***title*** column are also correctly populated.

## Implementation Details

The solution is implemented with Sequelize module, first installed sequelize module and pg module.

	npm install --save sequelize
	npm install --save pg

Each ORM has a API to open a connection to database, typically this is done through schema object. For example in the Sequealize module:

	var Sequelize = require('sequelize');
	var sequelize = new Sequelize(database, user, pass, {options});

The `sequelize` object has a connection to database and model definitions, this sequelize object must be shared for this challenge. If this object is not shared, then each package creates its own connection and models. So the connection resources are wasted and also one model created in a package can't be accessed from another packages.

There are a few ways to share this sequelize object:

	1. use global
	2. create the schema object inside mean.io core, which requires to modify the mean.io core.
	3. use npm module

The modifying mean.io core will break the future upgrade, using global is not a good practise. So I decide to use npm module.

For this challenge, I created `postgresql-sequelize` module to share sequelize object across the mean.io application. The sequelize object is created inside the `postgresql-sequelize` module.

Install `postgresql-sequelize` module.

	npm install --save postgresql-sequelize

When the application code defines models or accesss database, needs to requrie `postgresql-sequelize` to get the shared `sequelize` object.

	var postgresql = require('postgresql-sequelize');
	var sequelize = postgresql.sequelize;

The `sequelize` object returned from postgresql is shared across the mean.io application.

Thank very much


text:
package org.apache.flink.runtime.rpc.akka;

import org.apache.flink.runtime.rpc.RpcEndpoint;
import org.apache.flink.runtime.rpc.RpcGateway;
import org.apache.flink.runtime.rpc.RpcService;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThatThrownBy;

/**
 * Tests that the {@link AkkaRpcService} runs all RPCs in the {@link AkkaRpcActor}'s main thread.
 */
class MainThreadValidationTest {

    @Test
    void failIfNotInMainThread() throws Exception {
        // test if assertions are activated. The test only works if assertions are loaded.
        try {
            assert false;
            // apparently they are not activated
            return;
        } catch (AssertionError ignored) {
        }

        // actual test
        AkkaRpcService akkaRpcService =
                new AkkaRpcService(
                        AkkaUtils.createDefaultActorSystem(),
                        AkkaRpcServiceConfiguration.defaultConfiguration());

        try {
            TestEndpoint testEndpoint = new TestEndpoint(akkaRpcService);
            testEndpoint.start();

            // this works, because it is executed as an RPC call
            testEndpoint.getSelfGateway(TestGateway.class).someConcurrencyCriticalFunction();

            // this fails, because it is executed directly
            assertThatThrownBy(() -> testEndpoint.someConcurrencyCriticalFunction())
                    .isInstanceOf(AssertionError.class);

            testEndpoint.closeAsync();
        } finally {
            akkaRpcService.closeAsync().get();
        }
    }

    // ------------------------------------------------------------------------
    //  test RPC endpoint
    // ------------------------------------------------------------------------

    interface TestGateway extends RpcGateway {

        void someConcurrencyCriticalFunction();
    }

    private static class TestEndpoint extends RpcEndpoint implements TestGateway {

        private TestEndpoint(RpcService rpcService) {
            super(rpcService);
        }

        @Override
        public void someConcurrencyCriticalFunction() {
            validateRunsInMainThread();
        }
    }
}


text:
package com.abelsky.idea.geekandpoke.ui.impl;

import com.abelsky.idea.geekandpoke.entries.Entry;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * Displays entry title.
 *
 * @author andy
 */
class ComicTitleCellRenderer extends ColoredListCellRenderer {

    @Override
    protected void customizeCellRenderer(final JList list, Object value, int index, boolean selected, boolean hasFocus) {
        @NotNull final Entry entry = (Entry) value;

        SimpleTextAttributes attributes = SimpleTextAttributes.REGULAR_ATTRIBUTES;
        if (entry.isUnread()) {
            attributes = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES;
        }

        append(entry.getEntryInfo().getTitle(), attributes);
    }
}


text:
package edu.howest.breakout.game.info;

/**
 * Created by thomas on 05/11/2014.
 */
public enum GameState {
    Errored,
    EndGame,
    Running
}


text:
#include "prelude.h"                    /*  Universal header file            */
#include "sflmem.h"                     /*  Memory-access functions          */
#include "sflstr.h"                     /*  String manipulation functions    */
#include "sflprint.h"                   /*  snprintf functions               */
#include "sflsyst.h"                    /*  Prototypes for functions         */

/*  ---------------------------------------------------------------------[<]-
    Function: sys_assert

    Synopsis: Displays an 'assertion failed' message and aborts the program.
    This function is required by prelude.h if you compile with the DEBUG
    symbol.
    ---------------------------------------------------------------------[>]-*/

void
sys_assert (const char *File, unsigned Line)
{
#if (defined (__WINDOWS__))
    char
        line_str [10],
        *buffer;                        /*  Formatted error message          */
    MSG
        msg;
    Bool
        quit;
    int
        rc;                             /*  MessageBox return code           */

    snprintf (line_str, sizeof (line_str), "%u", Line);
    buffer = xstrcpy (NULL, "Module ", File, ", line ", line_str, NULL);

    /*  If WM_QUIT is in the queue the message box won't show                */
    quit = PeekMessage (&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE);
    rc   = MessageBox  (NULL, buffer, "Assertion failed!",
                        MB_TASKMODAL | MB_ICONHAND | MB_ABORTRETRYIGNORE);
    mem_free (buffer);
    if (quit)
        PostQuitMessage (msg.wParam);
    if (rc != IDABORT)
        return;
#else
    fflush  (stdout);
    fprintf (stderr, "\nAssertion failed: %s, line %u\n", File, Line);
    fflush  (stderr);
#endif
    abort   ();
}

/*  ---------------------------------------------------------------------[<]-
    Function: sys_name

    Synopsis: Returns a static buffer with the type or name of OS.  If the
    full argument is true, tries to report the OS version information as
    well.
    ---------------------------------------------------------------------[>]-*/

char *
sys_name (Bool full)
{
#if (defined (__WINDOWS__))
#   if (defined (WIN32))
    static char
        name [30];

    OSVERSIONINFO
        version_info;

    if (full)
      {
        version_info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
        if (GetVersionEx (&version_info))
          {
            if (version_info.dwPlatformId == VER_PLATFORM_WIN32_NT)
                snprintf (name, sizeof (name), "Windows NT %ld.%ld",
                                              version_info.dwMajorVersion,
                                              version_info.dwMinorVersion);
            else
            if (version_info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
                snprintf (name, sizeof (name), "Windows 95 %ld.%ld",
                                               version_info.dwMajorVersion,
                                               version_info.dwMinorVersion);
            else
                snprintf (name, sizeof (name), "Windows %ld.%ld with win32s",
                                               version_info.dwMajorVersion,
                                               version_info.dwMinorVersion);
          }
      }
    else
        strcpy (name, "Windows");

    return (name);
#   else
        return (full? "Windows 3.x": "Windows");
#   endif
#elif (defined (__UNIX__))
#   if (defined (__UTYPE_AUX))
        return ("UNIX Type: Apple AUX");
#   elif (defined (__UTYPE_DECALPHA))
        return ("UNIX Type: Digital UNIX (Alpha)");
#   elif (defined (__UTYPE_IBMAIX))
        return ("UNIX Type: IBM RS/6000 AIX");
#   elif (defined (__UTYPE_HPUX))
        return ("UNIX Type: HP/UX");
#   elif (defined (__UTYPE_LINUX))
        return ("UNIX Type: Linux");
#   elif (defined (__UTYPE_MIPS))
        return ("UNIX Type: MIPS");
#   elif (defined (__UTYPE_NETBSD))
        return ("UNIX Type: NetBSD");
#   elif (defined (__UTYPE_NEXT))
        return ("UNIX Type: NeXT");
#   elif (defined (__UTYPE_SCO))
        return ("UNIX Type: SCO UNIX");
#   elif (defined (__UTYPE_IRIX))
        return ("UNIX Type: Silicon Graphics IRIX");
#   elif (defined (__UTYPE_SUNOS))
        return ("UNIX Type: SunOS");
#   elif (defined (__UTYPE_SUNSOLARIS))
        return ("UNIX Type: Sun Solaris");
#   elif (defined (__UTYPE_UNIXWARE))
        return ("UNIX Type: SCO UNIXWare");
#   else
        return ("UNIX Type: Generic");
#   endif
#elif (defined (__VMS__))
    return ("UNIX Type: Digital OpenVMS");
#elif (defined (__OS2__))
    return ("UNIX Type: IBM OS/2");
#elif (defined (__MSDOS__))
    return ("MS-DOS");
#else
    return ("Unknown");
#endif
}


text:
<?php
  // start session
  session_start ();

  // set actual page session variable
  $_SESSION["act_page"] = "borrow";

  // start session, check if the user is already logged in and if he is a superuser or not
  include ("../check_user.inc");
  include ("../library_functions.inc");
?>

<!doctype html public "-//W3C//DTD HTML 4.01//EN">

    <title>STI-Innsbruck Library</title>

    <meta http-equiv="keywords" content="STI-Innsbruck - Library" />
	<meta http-equiv="generator" content="PHP Designer 2005" />
	<meta http-equiv="author" content="Nathalie Steinmetz" />
    <meta http-equiv="Content-Style-Type" content="text/css">

    <link rel="stylesheet" href="../format.css" type="text/css" />

  <?php
    // including vertical menue
    include("menue1.inc");
  ?>

      STI-Innsbruck Library

      <?php
        // check whether the user comes from the expert search or from the normal search
        if ($_SESSION["prev_page"]== "expert_obj_detail.php") {
          echo "> Expert search > Search results ";
        } // end if
        else {
          echo "> Search > Search results ";
        } // end else
      ?>

      > Borrow object

  <?php
    // including vertical menue
    include("menue2.inc");
  ?>

Borrow object

                <?php

                  // the id of the publication to be borrowed had been saved in a session variable
                  $pid = 0;
                  if (isset($_SESSION["obj_pid"]))
                    $pid = $_SESSION["obj_pid"];

                  // start database connection for the normal user, with error handling
                  $db = mysql_connect("localhost", "libraryUser", "user");
                  if (!mysql_select_db ("stilibrary", $db)){
                    die ("Connection to database failed - normal user");
                  } // end if

                  // send query to the database
                  $res = mysql_db_query("stilibrary", "SELECT * FROM publication WHERE pid = $pid");
                  if (mysql_errno() != 0) {
                    // logging function call
                    $string = "Error: " . mysql_errno() . ": " . mysql_error(). "\n";
                    library_log($string);
                    echo ("Database error! - Please see log file for detailed information.

");
                  }

                  // extract results
                  $author = mysql_result($res, 0, "author");
                  $title = mysql_result($res, 0, "title");
                  $subtitle = mysql_result($res, 0, "subtitle");
                  $year = mysql_result($res, 0, "year");
                  $publisher = mysql_result($res, 0, "publisher");
                  $location = mysql_result($res, 0, "location");
                  $isbn = mysql_result($res, 0, "isbn");
                  $keywords = mysql_result($res, 0, "keywords");
                  $comment = mysql_result($res, 0, "comment");
                  $signature = mysql_result($res, 0, "signature");
                  $proc_time = mysql_result($res, 0, "procTime");
                  $conf_loc = mysql_result($res, 0, "confLoc");
                  $supervisor = mysql_result($res, 0, "supervisor");
                  $school = mysql_result($res, 0, "school");
                  $type = mysql_result($res, 0, "type");
                  $classification = mysql_result($res, 0, "classification");
                  $status = mysql_result($res, 0, "status");

                  echo "Do you really want to borrow this book?

";

                  echo "
";
                  echo "<form action = 'borrow_obj_conf.php' method = 'post'>";
                  if(( $author != 'NULL') && ($author != '')) {
                    echo "

 author(s)
 	";
                    echo "", $author, "
"; }
                  echo "

 title
 	";
                  echo "", $title, "
";
                  if(($subtitle != 'NULL') && ($subtitle != '')) {
                    echo "

 subtitle
 	";
                    echo "", $subtitle, "
";}
                  if(($year != 'NULL') && ($year != '') && ($year != '0000')) {
                    echo "

 year
 	";
                    echo "", $year, "
";}
                  if(($publisher != 'NULL') && ($publisher != '')) {
                    echo "

 publisher
 	";
                    echo "", $publisher, "
";}
                  if(($location != 'NULL') && ($location != '')) {
                    echo "

 location
 	";
                    echo "", $location, "
";}
                  if(($isbn != 'NULL') && ($isbn != '')) {
                    echo "

 ISBN / ISSN
 	";
                    echo "", $isbn, "
";}
                  if(($keywords != 'NULL') && ($keywords != '')) {
                    echo "

 keywords
 	";
                    echo "", $keywords, "
";}
                  if(($comment != 'NULL') && ($comment != '')) {
                    echo "

 comment
 	";
                    echo "", $comment, "
";}
                  echo "

 signature
 	";
                  echo "", $signature, "
";
                  if(($proc_time != 'NULL') && ($proc_time != '0000-00-00') && ($proc_time != '')) {
                    echo "

 proceeding time
 	";
                    echo "", $proc_time, "
";}
                  if(($conf_loc != 'NULL') && ($conf_loc != '')) {
                    echo "

 conference location
 	";
                    echo "", $conf_loc, "
";}
                  if(($supervisor != 'NULL') && ($supervisor != '')) {
                    echo "

 supervisor
 	";
                    echo "", $supervisor, "
";}
                  if(($school != 'NULL') && ($school != '')) {
                    echo "

 school
 	";
                    echo "", $school, "
";}
                  echo "

 type
 	";
                  echo "", $type, "
";
                  echo "

 classification
 	";
                  echo "", $classification, "
";
                  echo "

 status
 	";
                  echo "", $status, "
";
                  echo "

";
                  echo "
  <input type='submit' value='  Yes, borrow book  '> 	";
                  echo "</form>";
                  if ($_SESSION["prev_page"]== "expert_obj_detail.php") {
                    echo "<form action = 'expert_result_list.php' method = 'GET'>";
                    echo " <input type='submit' name='get_back' value='  No, back to result list  '> 	";
                    echo "
 </form>";
                  } // end if
                  else {
                    echo "<form action = 'result_list.php' method = 'GET'>";
                    echo " <input type='submit' name='get_back' value='  No, back to result list  '> 	";
                    echo "
 </form>";
                  } // end else
                  echo "
";

                  // close database connection
                  mysql_close($db);
                ?>

    <?php
      // including vertical menue
      include("menue3.inc");
    ?>


text:
"""
日志函数
需要用到日志的地方,需要先初始化cache
每个日志文件以category命名,按日切割
注意category要全局唯一
"""

from . import utility
from . import config
from datetime import datetime
import os

LOG_FILE_POSTFIX = ".log"

class LogFile(object):
    def __init__(self, mdt, f):
        self.mdt = mdt
        self.f = f

_log_files = {}

def _create_file_obj(path, mdt):
    f = open(path, 'a', buffering=1)
    file_obj = LogFile(mdt, f)
    return file_obj

def get_log_file(category):
    log_dir = config.get_log_dir()
    path = os.path.join(log_dir, category)
    path += LOG_FILE_POSTFIX
    now = datetime.now()
    if category not in _log_files:
        try:
            stat_info = os.stat(path)
            mdt = datetime.fromtimestamp(stat_info.st_mtime)
        except FileNotFoundError:
            mdt = now
        _log_files[category] = _create_file_obj(path, mdt)
    file_obj = _log_files[category]
    mdt = file_obj.mdt
    # 跨天
    if mdt.day != now.day:
        src = path
        postfix = mdt.strftime('%Y%m%d')
        dst = '{0}.{1}'.format(path, postfix)
        if not os.path.exists(dst):
            try:
                os.rename(src, dst)
            except Exception as e:
                utility.print_out('rename log error', src, dst, e, category)
        file_obj.f.close()
        file_obj = _create_file_obj(src, now)
        _log_files[category] = file_obj
    return file_obj.f

def log(category, log_type, *args):
    if not args:
        return
    f = get_log_file(category)
    now = datetime.now()
    time_str = now.strftime('%Y-%m-%d %H:%M:%S,%f')[:23]
    sl = [time_str, log_type]
    sl.extend([str(arg) for arg in args])
    sl.append(os.linesep)
    s = ' '.join(sl)
    f.write(s)

def info(category, *args):
    log(category, 'INFO', *args)

def error(category, *args):
    log(category, 'ERROR', *args)

def initialize():
    log_dir = config.get_log_dir()
    utility.ensure_directory(log_dir)

def clear():
    for category, log_file in _log_files.items():
        try:
            log_file.close()
        except Exception as e:
            import traceback
            tb = traceback.format_exc()
            utility.print_out('clear log error', category, e, tb)
    _log_files.clear()


text:
class CreateAddresses< ActiveRecord::Migration
  def self.up
    create_table :addresses do |t|
      t.references :user
      t.string :street
      t.integer :number
    end
  end

  def self.down
    drop_table :addresses
  end
end