text:
import { clipPos } from "../line/pos"
import { findMaxLine } from "../line/spans"
import { displayWidth, measureChar, scrollGap } from "../measurement/position_measurement"
import { signal } from "../util/event"
import { activeElt } from "../util/dom"
import { finishOperation, pushOperation } from "../util/operation_group"

import { ensureFocus } from "./focus"
import { measureForScrollbars, updateScrollbars } from "./scrollbars"
import { restartBlink } from "./selection"
import { maybeScrollWindow, scrollPosIntoView, setScrollLeft, setScrollTop } from "./scrolling"
import { DisplayUpdate, maybeClipScrollbars, postUpdateDisplay, setDocumentHeight, updateDisplayIfNeeded } from "./update_display"
import { updateHeightsInViewport } from "./update_lines"

// Operations are used to wrap a series of changes to the editor
// state in such a way that each change won't have to update the
// cursor and display (which would be awkward, slow, and
// error-prone). Instead, display updates are batched and then all
// combined and executed at once.

let nextOpId = 0
// Start a new operation.
export function startOperation(cm) {
  cm.curOp = {
    cm: cm,
    viewChanged: false,      // Flag that indicates that lines might need to be redrawn
    startHeight: cm.doc.height, // Used to detect need to update scrollbar
    forceUpdate: false,      // Used to force a redraw
    updateInput: null,       // Whether to reset the input textarea
    typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
    changeObjs: null,        // Accumulated changes, for firing change events
    cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
    cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
    selectionChanged: false, // Whether the selection needs to be redrawn
    updateMaxLine: false,    // Set when the widest line needs to be determined anew
    scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
    scrollToPos: null,       // Used to scroll to a specific position
    focus: false,
    id: ++nextOpId           // Unique ID
  }
  pushOperation(cm.curOp)
}

// Finish an operation, updating the display and signalling delayed events
export function endOperation(cm) {
  let op = cm.curOp
  finishOperation(op, group => {
    for (let i = 0; i < group.ops.length; i++)
      group.ops[i].cm.curOp = null
    endOperations(group)
  })
}

// The DOM updates done when an operation finishes are batched so
// that the minimum number of relayouts are required.
function endOperations(group) {
  let ops = group.ops
  for (let i = 0; i < ops.length; i++) // Read DOM
    endOperation_R1(ops[i])
  for (let i = 0; i < ops.length; i++) // Write DOM (maybe)
    endOperation_W1(ops[i])
  for (let i = 0; i < ops.length; i++) // Read DOM
    endOperation_R2(ops[i])
  for (let i = 0; i < ops.length; i++) // Write DOM (maybe)
    endOperation_W2(ops[i])
  for (let i = 0; i < ops.length; i++) // Read DOM
    endOperation_finish(ops[i])
}

function endOperation_R1(op) {
  let cm = op.cm, display = cm.display
  maybeClipScrollbars(cm)
  if (op.updateMaxLine) findMaxLine(cm)

  op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
    op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
                       op.scrollToPos.to.line >= display.viewTo) ||
    display.maxLineChanged && cm.options.lineWrapping
  op.update = op.mustUpdate &&
    new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
}

function endOperation_W1(op) {
  op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
}

function endOperation_R2(op) {
  let cm = op.cm, display = cm.display
  if (op.updatedDisplay) updateHeightsInViewport(cm)

  op.barMeasure = measureForScrollbars(cm)

  // If the max line changed since it was last measured, measure it,
  // and ensure the document's width matches it.
  // updateDisplay_W2 will use these properties to do the actual resizing
  if (display.maxLineChanged && !cm.options.lineWrapping) {
    op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
    cm.display.sizerWidth = op.adjustWidthTo
    op.barMeasure.scrollWidth =
      Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
    op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
  }

  if (op.updatedDisplay || op.selectionChanged)
    op.preparedSelection = display.input.prepareSelection()
}

function endOperation_W2(op) {
  let cm = op.cm

  if (op.adjustWidthTo != null) {
    cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
    if (op.maxScrollLeft < cm.doc.scrollLeft)
      setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true)
    cm.display.maxLineChanged = false
  }

  let takeFocus = op.focus && op.focus == activeElt()
  if (op.preparedSelection)
    cm.display.input.showSelection(op.preparedSelection, takeFocus)
  if (op.updatedDisplay || op.startHeight != cm.doc.height)
    updateScrollbars(cm, op.barMeasure)
  if (op.updatedDisplay)
    setDocumentHeight(cm, op.barMeasure)

  if (op.selectionChanged) restartBlink(cm)

  if (cm.state.focused && op.updateInput)
    cm.display.input.reset(op.typing)
  if (takeFocus) ensureFocus(op.cm)
}

function endOperation_finish(op) {
  let cm = op.cm, display = cm.display, doc = cm.doc

  if (op.updatedDisplay) postUpdateDisplay(cm, op.update)

  // Abort mouse wheel delta measurement, when scrolling explicitly
  if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
    display.wheelStartX = display.wheelStartY = null

  // Propagate the scroll position to the actual DOM scroller
  if (op.scrollTop != null) setScrollTop(cm, op.scrollTop, op.forceScroll)

  if (op.scrollLeft != null) setScrollLeft(cm, op.scrollLeft, true, true)
  // If we need to scroll a specific position into view, do so.
  if (op.scrollToPos) {
    let rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
                                 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
    maybeScrollWindow(cm, rect)
  }

  // Fire events for markers that are hidden/unidden by editing or
  // undoing
  let hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
  if (hidden) for (let i = 0; i < hidden.length; ++i)
    if (!hidden[i].lines.length) signal(hidden[i], "hide")
  if (unhidden) for (let i = 0; i < unhidden.length; ++i)
    if (unhidden[i].lines.length) signal(unhidden[i], "unhide")

  if (display.wrapper.offsetHeight)
    doc.scrollTop = cm.display.scroller.scrollTop

  // Fire change events, and delayed event handlers
  if (op.changeObjs)
    signal(cm, "changes", cm, op.changeObjs)
  if (op.update)
    op.update.finish()
}

// Run the given function in an operation
export function runInOp(cm, f) {
  if (cm.curOp) return f()
  startOperation(cm)
  try { return f() }
  finally { endOperation(cm) }
}
// Wraps a function in an operation. Returns the wrapped function.
export function operation(cm, f) {
  return function() {
    if (cm.curOp) return f.apply(cm, arguments)
    startOperation(cm)
    try { return f.apply(cm, arguments) }
    finally { endOperation(cm) }
  }
}
// Used to add methods to editor and doc instances, wrapping them in
// operations.
export function methodOp(f) {
  return function() {
    if (this.curOp) return f.apply(this, arguments)
    startOperation(this)
    try { return f.apply(this, arguments) }
    finally { endOperation(this) }
  }
}
export function docMethodOp(f) {
  return function() {
    let cm = this.cm
    if (!cm || cm.curOp) return f.apply(this, arguments)
    startOperation(cm)
    try { return f.apply(this, arguments) }
    finally { endOperation(cm) }
  }
}


text:
package com.github.mizool.core.st4;

import java.util.Locale;

import org.stringtemplate.v4.StringRenderer;

public class MizoolStringRenderer extends StringRenderer
{
    @Override
    public String toString(Object o, String formatString, Locale locale)
    {
        String s = (String) o;
        String result;

        if (formatString == null)
        {
            result = s;
        }
        else if (formatString.equals("uncap"))
        {
            if (s.length() > 0)
            {
                result = Character.toLowerCase(s.charAt(0)) + s.substring(1);
            }
            else
            {
                result = s;
            }
        }
        else
        {
            result = super.toString(o, formatString, locale);
        }

        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

import { CommonEditorConfiguration, IEnvConfiguration } from 'vs/editor/common/config/commonEditorConfig';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { FontInfo, BareFontInfo } from 'vs/editor/common/config/fontInfo';

export class TestConfiguration extends CommonEditorConfiguration {

	constructor(opts: IEditorOptions) {
		super(opts);
		this._recomputeOptions();
	}

	protected _getEnvConfiguration(): IEnvConfiguration {
		return {
			extraEditorClassName: '',
			outerWidth: 100,
			outerHeight: 100,
			canUseTranslate3d: true,
			pixelRatio: 1,
			zoomLevel: 0
		};
	}

	protected readConfiguration(styling: BareFontInfo): FontInfo {
		return new FontInfo({
			zoomLevel: 0,
			fontFamily: 'mockFont',
			fontWeight: 'normal',
			fontSize: 14,
			lineHeight: 19,
			letterSpacing: 1.5,
			isMonospace: true,
			typicalHalfwidthCharacterWidth: 10,
			typicalFullwidthCharacterWidth: 20,
			spaceWidth: 10,
			maxDigitWidth: 10,
		}, true);
	}
}


text:
package org.apache.nifi.processor.util;

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import org.apache.nifi.components.ValidationContext;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.components.Validator;
import org.apache.nifi.controller.ControllerService;
import org.apache.nifi.expression.AttributeExpression.ResultType;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.util.FormatUtils;

public class StandardValidators {

    //
    //
    // STATICALLY DEFINED VALIDATORS
    //
    //
    public static final Validator ATTRIBUTE_KEY_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
            final ValidationResult.Builder builder = new ValidationResult.Builder();
            builder.subject(subject).input(input);

            try {
                FlowFile.KeyValidator.validateKey(input);
                builder.valid(true);
            } catch (final IllegalArgumentException e) {
                builder.valid(false).explanation(e.getMessage());
            }

            return builder.build();
        }
    };

    public static final Validator ATTRIBUTE_KEY_PROPERTY_NAME_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
            final ValidationResult.Builder builder = new ValidationResult.Builder();
            builder.subject("Property Name").input(subject);

            try {
                FlowFile.KeyValidator.validateKey(subject);
                builder.valid(true);
            } catch (final IllegalArgumentException e) {
                builder.valid(false).explanation(e.getMessage());
            }

            return builder.build();
        }
    };

    public static final Validator POSITIVE_INTEGER_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                final int intVal = Integer.parseInt(value);

                if (intVal <= 0) {
                    reason = "not a positive value";
                }
            } catch (final NumberFormatException e) {
                reason = "not a valid integer";
            }

            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
        }
    };

    public static final Validator POSITIVE_LONG_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                final long longVal = Long.parseLong(value);

                if (longVal <= 0) {
                    reason = "not a positive value";
                }
            } catch (final NumberFormatException e) {
                reason = "not a valid 64-bit integer";
            }

            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
        }
    };

    public static final Validator PORT_VALIDATOR = createLongValidator(1, 65535, true);

    public static final Validator NON_EMPTY_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            return new ValidationResult.Builder().subject(subject).input(value).valid(value != null && !value.isEmpty()).explanation(subject + " cannot be empty").build();
        }
    };

    public static final Validator BOOLEAN_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            final boolean valid = "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value);
            final String explanation = valid ? null : "Value must be 'true' or 'false'";
            return new ValidationResult.Builder().subject(subject).input(value).valid(valid).explanation(explanation).build();
        }
    };

    public static final Validator INTEGER_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                Integer.parseInt(value);
            } catch (final NumberFormatException e) {
                reason = "not a valid integer";
            }

            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
        }
    };

    public static final Validator LONG_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                Long.parseLong(value);
            } catch (final NumberFormatException e) {
                reason = "not a valid Long";
            }

            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
        }
    };

    public static final Validator NON_NEGATIVE_INTEGER_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                final int intVal = Integer.parseInt(value);

                if (intVal < 0) {
                    reason = "value is negative";
                }
            } catch (final NumberFormatException e) {
                reason = "value is not a valid integer";
            }

            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
        }
    };

    public static final Validator CHARACTER_SET_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                if (!Charset.isSupported(value)) {
                    reason = "Character Set is not supported by this JVM.";
                }
            } catch (final UnsupportedCharsetException uce) {
                reason = "Character Set is not supported by this JVM.";
            } catch (final IllegalArgumentException iae) {
                reason = "Character Set value cannot be null.";
            }

            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
        }
    };

    /**
     * URL Validator that does not allow the Expression Language to be used
     */
    public static final Validator URL_VALIDATOR = createURLValidator();

    public static final Validator URI_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
            try {
                new URI(input);
                return new ValidationResult.Builder().subject(subject).input(input).explanation("Valid URI").valid(true).build();
            } catch (final Exception e) {
                return new ValidationResult.Builder().subject(subject).input(input).explanation("Not a valid URI").valid(false).build();
            }
        }
    };

    public static final Validator REGULAR_EXPRESSION_VALIDATOR = createRegexValidator(0, Integer.MAX_VALUE, false);

    public static final Validator ATTRIBUTE_EXPRESSION_LANGUAGE_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
            try {
                context.newExpressionLanguageCompiler().compile(input);
                return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
            } catch (final Exception e) {
                return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation(e.getMessage()).build();
            }
        }

    };

    public static final Validator TIME_PERIOD_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
            if (input == null) {
                return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Time Period cannot be null").build();
            }
            if (Pattern.compile(FormatUtils.TIME_DURATION_REGEX).matcher(input.toLowerCase()).matches()) {
                return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
            } else {
                return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Must be of format <duration> <TimeUnit> where <duration> is a non-negative integer and TimeUnit is a supported Time Unit, such as: nanos, millis, secs, mins, hrs, days").build();
            }
        }
    };

    public static final Validator DATA_SIZE_VALIDATOR = new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
            if (input == null) {
                return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Data Size cannot be null").build();
            }
            if (Pattern.compile(DataUnit.DATA_SIZE_REGEX).matcher(input.toUpperCase()).matches()) {
                return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
            } else {
                return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Must be of format <Data Size> <Data Unit> where <Data Size> is a non-negative integer and <Data Unit> is a supported Data Unit, such as: B, KB, MB, GB, TB").build();
            }
        }
    };

    public static final Validator FILE_EXISTS_VALIDATOR = new FileExistsValidator(true);

    //
    //
    // FACTORY METHODS FOR VALIDATORS
    //
    //
    public static Validator createDirectoryExistsValidator(final boolean allowExpressionLanguage, final boolean createDirectoryIfMissing) {
        return new DirectoryExistsValidator(allowExpressionLanguage, createDirectoryIfMissing);
    }

    private static Validator createURLValidator() {
        return new Validator() {
            @Override
            public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
                try {
                    final String evaluatedInput = context.newPropertyValue(input).evaluateAttributeExpressions().getValue();
                    new URL(evaluatedInput);
                    return new ValidationResult.Builder().subject(subject).input(input).explanation("Valid URL").valid(true).build();
                } catch (final Exception e) {
                    return new ValidationResult.Builder().subject(subject).input(input).explanation("Not a valid URL").valid(false).build();
                }
            }
        };
    }

    public static Validator createTimePeriodValidator(final long minTime, final TimeUnit minTimeUnit, final long maxTime, final TimeUnit maxTimeUnit) {
        return new TimePeriodValidator(minTime, minTimeUnit, maxTime, maxTimeUnit);
    }

    public static Validator createAttributeExpressionLanguageValidator(final ResultType expectedResultType) {
        return createAttributeExpressionLanguageValidator(expectedResultType, true);
    }

    public static Validator createRegexMatchingValidator(final Pattern pattern) {
        return new Validator() {
            @Override
            public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
                final boolean matches = pattern.matcher(input).matches();
                return new ValidationResult.Builder()
                        .input(input)
                        .subject(subject)
                        .valid(matches)
                        .explanation(matches ? null : "Value does not match regular expression: " + pattern.pattern())
                        .build();
            }
        };
    }

    /**
     * Creates a @{link Validator} that ensure that a value is a valid Java
     * Regular Expression with at least minCapturingGroups
     * capturing groups and at most maxCapturingGroups capturing
     * groups. If supportAttributeExpressionLanguage is set to
     * true, the value may also include the Expression Language,
     * but the result of evaluating the Expression Language will be applied
     * before the Regular Expression is performed. In this case, the Expression
     * Language will not support FlowFile Attributes but only System/JVM
     * Properties
     *
     * @param minCapturingGroups
     * @param maxCapturingGroups
     * @param supportAttributeExpressionLanguage
     * @return
     */
    public static Validator createRegexValidator(final int minCapturingGroups, final int maxCapturingGroups, final boolean supportAttributeExpressionLanguage) {
        return new Validator() {
            @Override
            public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
                try {
                    final String substituted;
                    if (supportAttributeExpressionLanguage) {
                        try {
                            substituted = context.newPropertyValue(value).evaluateAttributeExpressions().getValue();
                        } catch (final Exception e) {
                            return new ValidationResult.Builder().subject(subject).input(value).valid(false).explanation("Failed to evaluate the Attribute Expression Language due to " + e.toString()).build();
                        }
                    } else {
                        substituted = value;
                    }

                    final Pattern pattern = Pattern.compile(substituted);
                    final int numGroups = pattern.matcher("").groupCount();
                    if (numGroups < minCapturingGroups || numGroups > maxCapturingGroups) {
                        return new ValidationResult.Builder().subject(subject).input(value).valid(false).explanation("RegEx is required to have between " + minCapturingGroups + " and " + maxCapturingGroups + " Capturing Groups but has " + numGroups).build();
                    }

                    return new ValidationResult.Builder().subject(subject).input(value).valid(true).build();
                } catch (final Exception e) {
                    return new ValidationResult.Builder().subject(subject).input(value).valid(false).explanation("Not a valid Java Regular Expression").build();
                }

            }
        };
    }

    public static Validator createAttributeExpressionLanguageValidator(final ResultType expectedResultType, final boolean allowExtraCharacters) {
        return new Validator() {
            @Override
            public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
                final String syntaxError = context.newExpressionLanguageCompiler().validateExpression(input, allowExtraCharacters);
                if (syntaxError != null) {
                    return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation(syntaxError).build();
                }

                final ResultType resultType = allowExtraCharacters ? ResultType.STRING : context.newExpressionLanguageCompiler().getResultType(input);
                if (!resultType.equals(expectedResultType)) {
                    return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Expected Attribute Query to return type " + expectedResultType + " but query returns type " + resultType).build();
                }

                return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
            }
        };
    }

    public static Validator createLongValidator(final long minimum, final long maximum, final boolean inclusive) {
        return new Validator() {
            @Override
            public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
                String reason = null;
                try {
                    final long longVal = Long.parseLong(input);
                    if (longVal < minimum || (!inclusive && longVal == minimum) | longVal > maximum || (!inclusive && longVal == maximum)) {
                        reason = "Value must be between " + minimum + " and " + maximum + " (" + (inclusive ? "inclusive" : "exclusive") + ")";
                    }
                } catch (final NumberFormatException e) {
                    reason = "not a valid integer";
                }

                return new ValidationResult.Builder().subject(subject).input(input).explanation(reason).valid(reason == null).build();
            }

        };
    }

    //
    //
    // SPECIFIC VALIDATOR IMPLEMENTATIONS THAT CANNOT BE ANONYMOUS CLASSES
    //
    //
    static class TimePeriodValidator implements Validator {

        private final Pattern pattern;

        private final long minNanos;
        private final long maxNanos;

        private final String minValueEnglish;
        private final String maxValueEnglish;

        public TimePeriodValidator(final long minValue, final TimeUnit minTimeUnit, final long maxValue, final TimeUnit maxTimeUnit) {
            pattern = Pattern.compile(FormatUtils.TIME_DURATION_REGEX);

            this.minNanos = TimeUnit.NANOSECONDS.convert(minValue, minTimeUnit);
            this.maxNanos = TimeUnit.NANOSECONDS.convert(maxValue, maxTimeUnit);
            this.minValueEnglish = minValue + " " + minTimeUnit.toString();
            this.maxValueEnglish = maxValue + " " + maxTimeUnit.toString();
        }

        @Override
        public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
            if (input == null) {
                return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Time Period cannot be null").build();
            }
            final String lowerCase = input.toLowerCase();
            final boolean validSyntax = pattern.matcher(lowerCase).matches();
            final ValidationResult.Builder builder = new ValidationResult.Builder();
            if (validSyntax) {
                final long nanos = FormatUtils.getTimeDuration(lowerCase, TimeUnit.NANOSECONDS);

                if (nanos < minNanos || nanos > maxNanos) {
                    builder.subject(subject).input(input).valid(false)
                            .explanation("Must be in the range of " + minValueEnglish + " to " + maxValueEnglish);
                } else {
                    builder.subject(subject).input(input).valid(true);
                }
            } else {
                builder.subject(subject).input(input).valid(false)
                        .explanation("Must be of format <duration> <TimeUnit> where <duration> is a non-negative integer and TimeUnit is a supported Time Unit, such as: nanos, millis, secs, mins, hrs, days");
            }
            return builder.build();
        }
    }

    public static class FileExistsValidator implements Validator {

        private final boolean allowEL;

        public FileExistsValidator(final boolean allowExpressionLanguage) {
            this.allowEL = allowExpressionLanguage;
        }

        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            final String substituted;
            if (allowEL) {
                try {
                    substituted = context.newPropertyValue(value).evaluateAttributeExpressions().getValue();
                } catch (final Exception e) {
                    return new ValidationResult.Builder().subject(subject).input(value).valid(false)
                            .explanation("Not a valid Expression Language value: " + e.getMessage()).build();
                }
            } else {
                substituted = value;
            }

            final File file = new File(substituted);
            final boolean valid = file.exists();
            final String explanation = valid ? null : "File " + file + " does not exist";
            return new ValidationResult.Builder().subject(subject).input(value).valid(valid).explanation(explanation).build();
        }
    }

    public static class DirectoryExistsValidator implements Validator {

        private final boolean allowEL;
        private final boolean create;

        public DirectoryExistsValidator(final boolean allowExpressionLanguage, final boolean create) {
            this.allowEL = allowExpressionLanguage;
            this.create = create;
        }

        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            final String substituted;
            if (allowEL) {
                try {
                    substituted = context.newPropertyValue(value).evaluateAttributeExpressions().getValue();
                } catch (final Exception e) {
                    return new ValidationResult.Builder().subject(subject).input(value).valid(false)
                            .explanation("Not a valid Expression Language value: " + e.getMessage()).build();
                }

                if (substituted.trim().isEmpty() && !value.trim().isEmpty()) {
                    // User specified an Expression and nothing more... assume valid.
                    return new ValidationResult.Builder().subject(subject).input(value).valid(true).build();
                }
            } else {
                substituted = value;
            }

            String reason = null;
            try {
                final File file = new File(substituted);
                if (!file.exists()) {
                    if (!create) {
                        reason = "Directory does not exist";
                    } else if (!file.mkdirs()) {
                        reason = "Directory does not exist and could not be created";
                    }
                } else if (!file.isDirectory()) {
                    reason = "Path does not point to a directory";
                }
            } catch (final Exception e) {
                reason = "Value is not a valid directory name";
            }

            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
        }
    }

    public static Validator createControllerServiceExistsValidator(final Class<? extends ControllerService> serviceClass) {
        return new Validator() {
            @Override
            public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
                final ControllerService svc = context.getControllerServiceLookup().getControllerService(input);

                if (svc == null) {
                    return new ValidationResult.Builder().valid(false).input(input).subject(subject).explanation("No Controller Service exists with this ID").build();
                }

                if (!serviceClass.isAssignableFrom(svc.getClass())) {
                    return new ValidationResult.Builder().valid(false).input(input).subject(subject).explanation("Controller Service with this ID is of type " + svc.getClass().getName() + " but is expected to be of type " + serviceClass.getName()).build();
                }

                final ValidationContext serviceValidationContext = context.getControllerServiceValidationContext(svc);
                final Collection<ValidationResult> serviceValidationResults = svc.validate(serviceValidationContext);
                for (final ValidationResult result : serviceValidationResults) {
                    if (!result.isValid()) {
                        return new ValidationResult.Builder().valid(false).input(input).subject(subject).explanation("Controller Service " + input + " is not valid: " + result.getExplanation()).build();
                    }
                }

                return new ValidationResult.Builder().input(input).subject(subject).valid(true).build();
            }
        };
    }
}


text:
import os
import sys

root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
sys.path.append(root)

# ----------------------------------------------------------------------------

# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code

# ----------------------------------------------------------------------------

from ccxt.pro.base.cache import ArrayCache, ArrayCacheByTimestamp, ArrayCacheBySymbolById  # noqa: F402

def equals(a, b):
    return a == b

# ----------------------------------------------------------------------------

cache = ArrayCache(3)

cache.append({'symbol': 'BTC/USDT', 'data': 1})
cache.append({'symbol': 'BTC/USDT', 'data': 2})
cache.append({'symbol': 'BTC/USDT', 'data': 3})
cache.append({'symbol': 'BTC/USDT', 'data': 4})

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'data': 2},
    {'symbol': 'BTC/USDT', 'data': 3},
    {'symbol': 'BTC/USDT', 'data': 4},
]))

cache.append({'symbol': 'BTC/USDT', 'data': 5})
cache.append({'symbol': 'BTC/USDT', 'data': 6})
cache.append({'symbol': 'BTC/USDT', 'data': 7})
cache.append({'symbol': 'BTC/USDT', 'data': 8})

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'data': 6},
    {'symbol': 'BTC/USDT', 'data': 7},
    {'symbol': 'BTC/USDT', 'data': 8},
]))

cache.clear()

cache.append({'symbol': 'BTC/USDT', 'data': 1})

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'data': 1},
]))

# ----------------------------------------------------------------------------

cache = ArrayCache(1)

cache.append({'symbol': 'BTC/USDT', 'data': 1})
cache.append({'symbol': 'BTC/USDT', 'data': 2})

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'data': 2},
]))

# ----------------------------------------------------------------------------

cache = ArrayCacheByTimestamp()

ohlcv1 = [100, 1, 2, 3]
ohlcv2 = [200, 5, 6, 7]
cache.append(ohlcv1)
cache.append(ohlcv2)

assert equals(cache, [ohlcv1, ohlcv2])

modify2 = [200, 10, 11, 12]
cache.append(modify2)

assert equals(cache, [ohlcv1, modify2])

# ----------------------------------------------------------------------------

cache = ArrayCacheBySymbolById()

object1 = {'symbol': 'BTC/USDT', 'id': 'abcdef', 'i': 1}
object2 = {'symbol': 'ETH/USDT', 'id': 'qwerty', 'i': 2}
object3 = {'symbol': 'BTC/USDT', 'id': 'abcdef', 'i': 3}
cache.append(object1)
cache.append(object2)
cache.append(object3)  # should update index 0

assert equals(cache, [object2, object3])

cache = ArrayCacheBySymbolById(5)

for i in range(1, 11):
    cache.append({
        'symbol': 'BTC/USDT',
        'id': str(i),
        'i': i,
    })

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'id': '6', 'i': 6},
    {'symbol': 'BTC/USDT', 'id': '7', 'i': 7},
    {'symbol': 'BTC/USDT', 'id': '8', 'i': 8},
    {'symbol': 'BTC/USDT', 'id': '9', 'i': 9},
    {'symbol': 'BTC/USDT', 'id': '10', 'i': 10},
]))

for i in range(1, 11):
    cache.append({
        'symbol': 'BTC/USDT',
        'id': str(i),
        'i': i + 10,
    })

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'id': '6', 'i': 16},
    {'symbol': 'BTC/USDT', 'id': '7', 'i': 17},
    {'symbol': 'BTC/USDT', 'id': '8', 'i': 18},
    {'symbol': 'BTC/USDT', 'id': '9', 'i': 19},
    {'symbol': 'BTC/USDT', 'id': '10', 'i': 20},
]))

middle = {'symbol': 'BTC/USDT', 'id': '8', 'i': 28}
cache.append(middle)

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'id': '6', 'i': 16},
    {'symbol': 'BTC/USDT', 'id': '7', 'i': 17},
    {'symbol': 'BTC/USDT', 'id': '9', 'i': 19},
    {'symbol': 'BTC/USDT', 'id': '10', 'i': 20},
    {'symbol': 'BTC/USDT', 'id': '8', 'i': 28},
]))

otherMiddle = {'symbol': 'BTC/USDT', 'id': '7', 'i': 27}
cache.append(otherMiddle)

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'id': '6', 'i': 16},
    {'symbol': 'BTC/USDT', 'id': '9', 'i': 19},
    {'symbol': 'BTC/USDT', 'id': '10', 'i': 20},
    {'symbol': 'BTC/USDT', 'id': '8', 'i': 28},
    {'symbol': 'BTC/USDT', 'id': '7', 'i': 27},
]))

for i in range(30, 33):
    cache.append({
        'symbol': 'BTC/USDT',
        'id': str(i),
        'i': i + 10,
    })

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'id': '8', 'i': 28},
    {'symbol': 'BTC/USDT', 'id': '7', 'i': 27},
    {'symbol': 'BTC/USDT', 'id': '30', 'i': 40},
    {'symbol': 'BTC/USDT', 'id': '31', 'i': 41},
    {'symbol': 'BTC/USDT', 'id': '32', 'i': 42}]))

first = {'symbol': 'BTC/USDT', 'id': '8', 'i': 38}
cache.append(first)

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'id': '7', 'i': 27},
    {'symbol': 'BTC/USDT', 'id': '30', 'i': 40},
    {'symbol': 'BTC/USDT', 'id': '31', 'i': 41},
    {'symbol': 'BTC/USDT', 'id': '32', 'i': 42},
    {'symbol': 'BTC/USDT', 'id': '8', 'i': 38},
]))

another = {'symbol': 'BTC/USDT', 'id': '30', 'i': 50}
cache.append(another)

assert(equals(cache, [
    {'symbol': 'BTC/USDT', 'id': '7', 'i': 27},
    {'symbol': 'BTC/USDT', 'id': '31', 'i': 41},
    {'symbol': 'BTC/USDT', 'id': '32', 'i': 42},
    {'symbol': 'BTC/USDT', 'id': '8', 'i': 38},
    {'symbol': 'BTC/USDT', 'id': '30', 'i': 50},
]))

# ----------------------------------------------------------------------------

# test ArrayCacheBySymbolById limit with symbol set
symbol = 'BTC/USDT'
cache = ArrayCacheBySymbolById()
initialLength = 5
for i in range(0, initialLength):
    cache.append({
        'symbol': symbol,
        'id': str(i),
        'i': i,
    })

limited = cache.getLimit(symbol, None)

assert initialLength == limited

cache = ArrayCacheBySymbolById()
appendItemsLength = 3
for i in range(0, appendItemsLength):
    cache.append({
        'symbol': symbol,
        'id': str(i),
        'i': i,
    })

outsideLimit = 5
limited = cache.getLimit(symbol, outsideLimit)

assert appendItemsLength == limited

outsideLimit = 2  # if limit < newsUpdate that should be returned
limited = cache.getLimit(symbol, outsideLimit)

assert outsideLimit == limited

# ----------------------------------------------------------------------------

# test ArrayCacheBySymbolById limit with symbol None
symbol = 'BTC/USDT'
cache = ArrayCacheBySymbolById()
initialLength = 5
for i in range(0, initialLength):
    cache.append({
        'symbol': symbol,
        'id': str(i),
        'i': i,
    })

limited = cache.getLimit(None, None)

assert initialLength == limited

cache = ArrayCacheBySymbolById()
appendItemsLength = 3
for i in range(0, appendItemsLength):
    cache.append({
        'symbol': symbol,
        'id': str(i),
        'i': i,
    })

outsideLimit = 5
limited = cache.getLimit(symbol, outsideLimit)

assert appendItemsLength == limited

outsideLimit = 2  # if limit < newsUpdate that should be returned
limited = cache.getLimit(symbol, outsideLimit)

assert outsideLimit == limited

# ----------------------------------------------------------------------------
# test ArrayCacheBySymbolById, same order should not increase the limit

cache = ArrayCacheBySymbolById()
symbol = 'BTC/USDT'
otherSymbol = 'ETH/USDT'

cache.append({'symbol': symbol, 'id': 'singleId', 'i': 3})
cache.append({'symbol': symbol, 'id': 'singleId', 'i': 3})
cache.append({'symbol': otherSymbol, 'id': 'singleId', 'i': 3})
outsideLimit = 5
limited = cache.getLimit(symbol, outsideLimit)
limited2 = cache.getLimit(None, outsideLimit)

assert 1 == limited
assert 2 == limited2

# ----------------------------------------------------------------------------
# test testLimitArrayCacheByTimestamp limit

cache = ArrayCacheByTimestamp()

initialLength = 5
for i in range(0, initialLength):
    cache.append([
        i * 10,
        i * 10,
        i * 10,
        i * 10
    ])

limited = cache.getLimit(None, None)

assert initialLength == limited

appendItemsLength = 3
for i in range(0, appendItemsLength):
    cache.append([
        i * 4,
        i * 4,
        i * 4,
        i * 4
    ])

outsideLimit = 5
limited = cache.getLimit(None, outsideLimit)

assert appendItemsLength == limited

outsideLimit = 2  # if limit < newsUpdate that should be returned
limited = cache.getLimit(None, outsideLimit)

assert outsideLimit == limited

# ----------------------------------------------------------------------------
# test ArrayCacheBySymbolById, watch all orders, same symbol and order id gets updated

cache = ArrayCacheBySymbolById()
symbol = 'BTC/USDT'
outsideLimit = 5
cache.append({'symbol': symbol, 'id': 'oneId', 'i': 3})  # create first order
cache.getLimit(None, outsideLimit)  # watch all orders
cache.append({'symbol': symbol, 'id': 'oneId', 'i': 4})  # first order is closed
cache.getLimit(None, outsideLimit)  # watch all orders
cache.append({'symbol': symbol, 'id': 'twoId', 'i': 5})  # create second order
cache.getLimit(None, outsideLimit)  # watch all orders
cache.append({'symbol': symbol, 'id': 'twoId', 'i': 6})  # second order is closed
limited = cache.getLimit(None, outsideLimit)  # watch all orders
assert limited == 1  # one new update

# ----------------------------------------------------------------------------
# test ArrayCacheBySymbolById, watch all orders, and watchOrders(symbol) work independently

cache = ArrayCacheBySymbolById()
symbol = 'BTC/USDT'
symbol2 = 'ETH/USDT'

outsideLimit = 5
cache.append({'symbol': symbol, 'id': 'one', 'i': 1})  # create first order
cache.append({'symbol': symbol2, 'id': 'two', 'i': 1})  # create second order
assert cache.getLimit(None, outsideLimit) == 2  # watch all orders
assert cache.getLimit(symbol, outsideLimit) == 1  # watch by symbol
cache.append({'symbol': symbol, 'id': 'one', 'i': 2})  # update first order
cache.append({'symbol': symbol2, 'id': 'two', 'i': 2})  # update second order
assert cache.getLimit(symbol, outsideLimit) == 1  # watch by symbol
assert cache.getLimit(None, outsideLimit) == 2  # watch all orders
cache.append({'symbol': symbol2, 'id': 'two', 'i': 3})  # update second order
cache.append({'symbol': symbol2, 'id': 'three', 'i': 3})  # create third order
assert cache.getLimit(None, outsideLimit) == 2  # watch all orders


text:
Add User

    <?php if(!$this->form_validation->run() && isset($_POST['username'])){ ?>

      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

 Alert!

      <?php echo validation_errors()?>

    <?php
  }
    ?>

    <?php if(isset($error)){
    echo $error;
  }
    ?>
    <?php echo form_open_multipart('');?>

    <form role="form" method="POST" action="">

        Username
        <input type="text" class="form-control" placeholder="username" name="username" value="<?php echo set_value('username')?>">

        Password
        <input type="password" class="form-control" placeholder="password" name="password">

        Image
        <input type="file" class="form-control"  name="userfile">

        Email
        <input type="text" class="form-control" placeholder="Vorcee@gmail.com" name="email" value="<?php echo set_value('email')?>">

        Full Name
        <input type="text" class="form-control"  placeholder="Vorcee" name="full_name" value="<?php echo set_value('full_name')?>">

        Phone number
        <input type="text" class="form-control"  placeholder="Vorcee" name="phone_number" value="<?php echo set_value('phone_number')?>">

        Gender
        <select class="form-control" name="gender" value="<?php echo set_value('gender')?>">
          <option value="0">Not set</option>
          <option value="1">Male</option>
          <option value="2">Female</option>
        </select>

        Address
        <textarea class="form-control" rows="3" placeholder="Address" name="address"><?php echo set_value('username')?></textarea>

        Country
      <select class="form-control" name="country" value="<?php echo set_value('country')?>">
        <option>Indonesia</option>
        <option>Another Country</option>
      </select>

        Province
        <?php
          $options = array(
            'Aceh' => 'Aceh',
            'Sumut' => 'Sumatera Utara',
            'Sumbar'=> 'Sumatra Barat',
            'Riau' => 'Riau',
            'Jambi'=> 'Jambi',
            'Sumsel' => 'Sumatra Selatan',
            'Bengkulu' => 'Bengkulu',
            'Lampung' => 'Lampung',
            'Babel' => 'Kep. Bangka Belitung',
            'kepRiau' =>'Kepulauan Riau',
            'Jakarta' =>'Jakarta',
            'Jabar' => 'Jawa Barat',
            'Banten'=> 'Banten',
            'Jateng'=> 'Jateng',
            'Yogyakarta'=> 'Yogyakarta',
            'Jatim'=> 'Jawa Timur',
            'Kalbar'=> 'Kalimantan Barat',
            'Kalteng'=> 'Kalimantan Tengah',
            'Kalsel'=> 'Kalimantan Selatan',
            'Kaltim'=> 'Kalimantan Timur',
            'Kaltra'=> 'Kalimantan Utara',
            'Bali'=> 'Bali',
            'NTT'=> 'Nusa Tenggara Timur',
            'NTB'=> 'Nusa Tenggara Barat',
            'Sulut'=> 'Sulawesi Utara',
            'Sulteng'=> 'Sulawesi Tengah',
            'Sulsel'=> 'Sulawesi Selatan',
            'Sultengg'=> 'Sulawesi Tenggara',
            'Sulbar'=> 'Sulawesi Barat',
            'Gorontalo'=> 'Gorontalo',
            'Maluku'=> 'Maluku',
            'Maluku Utara'=> 'Maluku Utara',
            'Papua'=> 'Papua',
            'Papua Barat'=> 'Papua Barat',
          );
          echo form_dropdown('province',$options,set_value('province'),'class="form-control"');
       ?>

        City
        <input type="text" class="form-control"  placeholder="Jakarta" name="city" value="<?php echo set_value('city')?>">

        About User
        <textarea class="form-control" rows="3"  name="about_user"><?php echo set_value('about_user')?></textarea>

        Status User
        <select class="form-control" name="status_user" value="<?php echo set_value('status_user')?>">
          <option value="0">Non Active</option>
          <option value="1">Active</option>
          <option value="2">Banned</option>
        </select>

        Permission
        <select class="form-control" name="permission" value="<?php echo set_value('permission')?>">
          <option value="0">Donatur</option>
          <option value="1">Admin</option>
          <option value="2">Campaigner</option>
        </select>

        <button type="submit" class="btn btn-primary">Submit</button>

    </form>


text:
package es.bsc.compss.executor.external.commands;

public class CompssExceptionExternalCommand implements ExternalCommand {

    @Override
    public CommandType getType() {
        return CommandType.COMPSS_EXCEPTION;
    }

    @Override
    public String getAsString() {
        return CommandType.COMPSS_EXCEPTION.name();
    }
}


text:
/* global describe, it, require */
'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	abs = require( './../lib/accessor.js' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'accessor abs', function tests() {

	it( 'should export a function', function test() {
		expect( abs ).to.be.a( 'function' );
	});

	it( 'should compute the absolute value using an accessor', function test() {
		var data, actual, expected;

		data = [
			{'x':-3},
			{'x':-2},
			{'x':-1},
			{'x':0},
			{'x':1},
			{'x':2},
			{'x':3}
		];
		actual = new Array( data.length );
		actual = abs( actual, data, getValue );

		expected = [
			3,
			2,
			1,
			0,
			1,
			2,
			3,
		];

		assert.deepEqual( actual, expected );

		function getValue( d ) {
			return d.x;
		}
	});

	it( 'should return empty array if provided an empty array', function test() {
		assert.deepEqual( abs( [], [], getValue ), [] );
		function getValue( d ) {
			return d.x;
		}
	});

	it( 'should handle non-numeric values by setting the element to NaN', function test() {
		var data, actual, expected;

		data = [
			{'x':-3},
			{'x':null},
			{'x':2}
		];
		actual = new Array( data.length );
		actual = abs( actual, data, getValue );

		expected = [ 3, NaN, 2 ];

		assert.deepEqual( actual, expected );

		function getValue( d ) {
			return d.x;
		}
	});

});


text:
<?php

namespace Fxp\Component\Cache\Adapter;

use Symfony\Component\Cache\Adapter\PdoAdapter as BasePdoAdapter;

/**
 * Pdo Cache Adapter.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class PdoAdapter extends BasePdoAdapter implements AdapterInterface
{
    use AdapterTrait;

    /**
     * {@inheritdoc}
     */
    protected function doClearByPrefix(string $namespace, string $prefix): bool
    {
        return $this->doClear($namespace.$prefix);
    }
}


text:
package com.tjoris.util;

/*
 File: Semaphore.java

 Originally written by Doug Lea and released into the public domain.
 This may be used for any purposes whatsoever without acknowledgment.
 Thanks for the assistance and support of Sun Microsystems Labs,
 and everyone contributing, testing, and using this code.

 History:
 Date       Who                What
 11Jun1998  dl               Create public version
 5Aug1998  dl               replaced int counters with longs
 24Aug1999  dl               release(n): screen arguments
 */

/**
 * Base class for counting semaphores.
 * Conceptually, a semaphore maintains a set of permits.
 * Each acquire() blocks if necessary
 * until a permit is available, and then takes it.
 * Each release adds a permit. However, no actual permit objects
 * are used; the Semaphore just keeps a count of the number
 * available and acts accordingly.
 *

 * A semaphore initialized to 1 can serve as a mutual exclusion
 * lock.
 *

 * Different implementation subclasses may provide different
 * ordering guarantees (or lack thereof) surrounding which
 * threads will be resumed upon a signal.
 *

 * The default implementation makes NO
 * guarantees about the order in which threads will
 * acquire permits. It is often faster than other implementations.
 *

 * Sample usage. Here is a class that uses a semaphore to
 * help manage access to a pool of items.
 *

 * class Pool {
 *   static final MAX_AVAILABLE = 100;
 *   private final Semaphore available = new Semaphore(MAX_AVAILABLE);
 *
 *   public Object getItem() throws InterruptedException { // no synch
 *     available.acquire();
 *     return getNextAvailableItem();
 *   }
 *
 *   public void putItem(Object x) { // no synch
 *     if (markAsUnused(x))
 *       available.release();
 *   }
 *
 *   // Not a particularly efficient data structure; just for demo
 *
 *   protected Object[] items = ... whatever kinds of items being managed
 *   protected boolean[] used = new boolean[MAX_AVAILABLE];
 *
 *   protected synchronized Object getNextAvailableItem() {
 *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
 *       if (!used[i]) {
 *          used[i] = true;
 *          return items[i];
 *       }
 *     }
 *     return null; // not reached
 *   }
 *
 *   protected synchronized boolean markAsUnused(Object item) {
 *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
 *       if (item == items[i]) {
 *          if (used[i]) {
 *            used[i] = false;
 *            return true;
 *          }
 *          else
 *            return false;
 *       }
 *     }
 *     return false;
 *   }
 *
 * }
 *

 *
[ Introduction to this package. ]
 **/

import java.io.*;

public class Semaphore implements Serializable
{
	private static final long serialVersionUID = 1L;

	/** current number of available permits **/
	protected long permits_;

	/**
	 * Create a Semaphore with the given initial number of permits.
	 * Using a seed of one makes the semaphore act as a mutual exclusion lock.
	 * Negative seeds are also allowed, in which case no acquires will proceed
	 * until the number of releases has pushed the number of permits past 0.
	 **/
	public Semaphore(long initialPermits)
	{
		permits_ = initialPermits;
	}

	/** Wait until a permit is available, and take one **/
	public void acquire() throws InterruptedException
	{
		if (Thread.interrupted()) throw new InterruptedException();
		synchronized (this)
		{
			try
			{
				while (permits_ <= 0)
				{
					wait();
				}
				--permits_;
			}
			catch (InterruptedException ex)
			{
				notify();
				throw ex;
			}
		}
	}

	/** Wait at most msecs millisconds for a permit. **/
	public boolean attempt(long msecs) throws InterruptedException
	{
		if (Thread.interrupted())
		{
			throw new InterruptedException();
		}

		synchronized (this)
		{
			if (permits_ > 0)
			{
				--permits_;
				return true;
			}
			else if (msecs <= 0)
			{
				return false;
			}
			else
			{
				try
				{
					long startTime = System.currentTimeMillis();
					long waitTime = msecs;

					for (; ;)
					{
						wait(waitTime);
						if (permits_ > 0)
						{
							--permits_;
							return true;
						}
						else
						{
							waitTime = msecs - (System.currentTimeMillis() - startTime);
							if (waitTime <= 0)
							{
								return false;
							}
						}
					}
				}
				catch (InterruptedException ex)
				{
					notify();
					throw ex;
				}
			}
		}
	}

	/** Release a permit **/
	public synchronized void release()
	{
		++permits_;
		notify();
	}

	/**
	 * Release N permits. release(n) is
	 * equivalent in effect to:
	 *

	 *   for (int i = 0; i < n; ++i) release();
	 *

	 *

	 * But may be more efficient in some semaphore implementations.
	 * @exception IllegalArgumentException if n is negative.
	 **/
	public synchronized void release(long n)
	{
		if (n < 0)
		{
			throw new IllegalArgumentException("Negative argument");
		}

		permits_ += n;
		for (long i = 0; i < n; ++i)
		{
			notify();
		}
	}

	/**
	 * Return the current number of available permits.
	 * Returns an accurate, but possibly unstable value,
	 * that may change immediately after returning.
	 **/
	public synchronized long permits()
	{
		return permits_;
	}

}


text: require File.dirname(__FILE__) + "/lib/mms2r"


text:
<?php namespace Anomaly\AddonsModule\Console\Command;

use Anomaly\Streams\Platform\Application\Application;
use Anomaly\Streams\Platform\Application\Command\ReadEnvironmentFile;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Process\Process;

/**
 * Class RunProcess
 *
 * @link   http://pyrocms.com/
 * @author PyroCMS, Inc. <support@pyrocms.com>
 * @author Ryan Thompson <ryan@pyrocms.com>
 */
class RunProcess
{

    /**
     * The command instance.
     *
     * @var Command
     */
    protected $command;

    /**
     * The process instance.
     *
     * @var Process
     */
    protected $process;

    /**
     * Create a new RunProcess instance.
     *
     * @param Command $command
     * @param Process $process
     */
    public function __construct(Command $command, Process $process)
    {
        $this->command = $command;
        $this->process = $process;
    }

    /**
     * Handle the command.
     *
     * @param Application $application
     * @param Filesystem $files
     */
    public function handle(Application $application, Filesystem $files)
    {
        $log = $application->getAssetsPath('process.log');

        $files->put($log, '');

        $this->process->run(
            function ($type, $buffer) use ($log, $files) {

                if (empty($buffer = trim($buffer))) {
                    return;
                }

                $files->put($log, $buffer);

                $this->command->info("{$buffer}");
            }
        );

        if (!$this->process->isSuccessful()) {
            $files->put($log, $this->process->getErrorOutput());
        }
    }
}


text:
import {ConnectFourGame} from "../../shared/connect-four-game";

describe('win state tests', () => {
  let connectFourGame: ConnectFourGame;

  beforeEach(() =>
      connectFourGame = new ConnectFourGame()
  );

  function setPlayerOneWin(): void {
    connectFourGame.currentState.dropDisc(0);
    connectFourGame.currentState.dropDisc(1);
    connectFourGame.currentState.dropDisc(0);
    connectFourGame.currentState.dropDisc(1);
    connectFourGame.currentState.dropDisc(0);
    connectFourGame.currentState.dropDisc(1);
    connectFourGame.currentState.dropDisc(0);
  }

  function setPlayerTwoWin(): void {
    connectFourGame.currentState.dropDisc(3);
    connectFourGame.currentState.dropDisc(1);
    connectFourGame.currentState.dropDisc(0);
    connectFourGame.currentState.dropDisc(1);
    connectFourGame.currentState.dropDisc(0);
    connectFourGame.currentState.dropDisc(1);
    connectFourGame.currentState.dropDisc(0);
    connectFourGame.currentState.dropDisc(1);
  }

  it('should declare a win for player one', () => {
    setPlayerOneWin();
    expect(connectFourGame.currentState.message).toEqual('Player One Won');
  });

  it('should declare a win for player two', () => {
    setPlayerTwoWin();
    expect(connectFourGame.currentState.message).toEqual('Player Two Won');
  });

  it('should not drop a disc when player one wins', () => {
    setPlayerOneWin();
    connectFourGame.currentState.dropDisc(0);
    expect(connectFourGame.currentState.message).toEqual("Please start a new game.");
    expect(connectFourGame.board.getCell(0,4).state).toEqual("empty");
  });

  it('should not drop a disc when player two wins', () => {
    setPlayerTwoWin();
    connectFourGame.currentState.dropDisc(1);
    expect(connectFourGame.currentState.message).toEqual("Please start a new game.");
    expect(connectFourGame.board.getCell(0,4).state).toEqual("empty");
  });

  it('should be able to reset game when player one wins', () => {
    setPlayerOneWin();
    connectFourGame.currentState.resetGame();
    expect(connectFourGame.currentState).toEqual(connectFourGame.playerOne);
    expect(connectFourGame.board.getCell(0,0).state).toEqual("empty");
  });

  it('should be able to reset game when player two wins', () => {
    setPlayerTwoWin();
    connectFourGame.currentState.resetGame();
    expect(connectFourGame.currentState).toEqual(connectFourGame.playerOne);
    expect(connectFourGame.board.getCell(0,0).state).toEqual("empty");
  });
});


text:
set define off verify off feedback off
whenever sqlerror exit sql.sqlcode rollback
--------------------------------------------------------------------------------
--
-- ORACLE Application Express (APEX) export file
--
-- You should run the script connected to SQL*Plus as the Oracle user
-- APEX_050100 or as the owner (parsing schema) of the application.
--
-- NOTE: Calls to apex_application_install override the defaults below.
--
--------------------------------------------------------------------------------
begin
wwv_flow_api.import_begin (
 p_version_yyyy_mm_dd=>'2016.08.24'
,p_release=>'5.1.1.00.08'
,p_default_workspace_id=>11910739974752839674
,p_default_application_id=>20459
,p_default_owner=>'T4'
);
end;
/
prompt --application/ui_types
begin
null;
end;
/
prompt --application/shared_components/plugins/region_type/com_blogspot_apexnotes_apex_rds_customizable
begin
wwv_flow_api.create_plugin(
 p_id=>wwv_flow_api.id(11970926940241413112)
,p_plugin_type=>'REGION TYPE'
,p_name=>'COM.BLOGSPOT.APEXNOTES.APEX.RDS_CUSTOMIZABLE'
,p_display_name=>'RDS Customizable'
,p_supported_ui_types=>'DESKTOP'
,p_plsql_code=>wwv_flow_string.join(wwv_flow_t_varchar2(
'-- ------------------------------------------------------------------------------------',
'-- Function       : render_RDS',
'-- Author         : Tereska Jagiello',
'-- Description    : render function for Region Display Selector plugin',
'-- ------------------------------------------------------------------------------------',
'-- Created On     : 2011.11.21',
'-- Curent version : 1.1',
'-- ------------------------------------------------------------------------------------',
'-- Credits        :',
'-- Martin Giffy D''Souza for help with the authorization function',
'-- Jose Murillo for thoroughly testing version 1.1 of the plugin',
'-- ------------------------------------------------------------------------------------',
'-- Changed On     : 2012.01.10',
'-- Version        : 1.1',
'--',
'-- exchanged "cursor for loop" (causing ORA-06502 in XE 10g edition) for "bulk collect"',
'-- rewritten query for better readability',
'-- ------------------------------------------------------------------------------------',
'-- Changed On     : 2017.04.21 by iminglei.blogspot.com',
'-- Version        : 1.2',
'--',
'-- 1. normalize RDS id to regionID || ''_RDS'' or staticID || ''_RDS''',
'-- 2. add order of "regions_and_label" in the main sql statement to fix display order bug',
'-- 3. set showing all tabs when ShowAll tab is displayed, otherwise show the first tab',
'-- 4. upgrade to use 5.1 released apex.widget.regionDisplaySelector',
'-- ------------------------------------------------------------------------------------',
'function render_RDS (',
'    p_region              in apex_plugin.t_region,',
'    p_plugin              in apex_plugin.t_plugin,',
'    p_is_printer_friendly in boolean )',
'  return apex_plugin.t_region_render_result',
'as',
'  /* plugin parameters */',
'  l_group_class     p_region.attribute_01%type;  ',
'  l_display_ALL     number(1);',
'  l_ALL_label       p_region.attribute_03%type;',
'  l_ALL_css         p_region.attribute_05%type;',
'  l_ALL_position    number(1);',
'  -- id of the plugin region',
'  l_id p_region.static_id%TYPE;',
'  ',
'  l_attr_list   sys.odcivarchar2list;',
'  l_name_list   sys.odcivarchar2list;',
'  l_id_list   sys.odcivarchar2list;',
'  l_seq_list   sys.odcinumberlist;',
'  ',
'begin',
'  -- ::debug: metadata',
'  if apex_application.g_debug',
'  then',
'    apex_plugin_util.debug_region(p_plugin               => p_plugin,',
'                                  p_region               => p_region,',
'                                  p_is_printer_friendly  => p_is_printer_friendly);',
'  end if;',
'',
'  l_group_class := case when p_region.attribute_01 is not null then '' ''||p_region.attribute_01||'' '' end;',
'  l_display_ALL := case p_region.attribute_02 when ''Y'' then 1 else 0 end;',
'  l_ALL_label := apex_plugin_util.escape(p_region.attribute_03, case p_region.attribute_04 when ''Y'' then true else false end);   ',
'  l_ALL_css   := p_region.attribute_05;',
'  l_ALL_position := case p_region.attribute_06 when ''f'' then 0 else null end;',
'    ',
'  -- get the id of the region into local variable',
'  l_id := case upper(apex_plugin_util.escape(p_region.static_id,true)) when ''R''||to_char(p_region.id) then to_char(p_region.id) else apex_plugin_util.escape(p_region.static_id,true) end;',
'  ',
'  -- ::debug: variables ',
'  if apex_application.g_debug then',
'     apex_application.debug(''RDS Variables: l_group_class: ''  || l_group_class ||',
'                                 '', l_display_ALL: ''  || l_display_ALL ||',
'                                 '', l_ALL_label: ''    || l_ALL_label ||',
'                                 '', l_ALL_css: ''      || l_ALL_css ||',
'                                 '', l_ALL_position: '' || l_ALL_position );',
'  end if;',
'  ',
'  -- get the values',
'  with regions as ( ',
'     select  aapr.REGION_NAME  reg_name',
'     -- if no id (STATIC_ID) is given, then the one from apex (REGION_ID)',
'            ,decode (aapr.STATIC_ID',
'                         ,null, ''#R'' || to_char(aapr.REGION_ID)',
'                              , ''#''  || aapr.STATIC_ID)                   reg_id                    ',
'       from  APEX_APPLICATION_PAGE_REGIONS aapr                       ',
'      where  aapr.APPLICATION_ID = wwv_flow.g_flow_id ',
'        and  aapr.PAGE_ID = wwv_flow.g_flow_step_id',
'        and  aapr.DISPLAY_REGION_SELECTOR = ''Yes''',
'        -- filter the region with the given class name if available',
'        and  decode(l_group_class, null, 1, instr(replace(aapr.REGION_ATTRIBUTES_SUBSTITUTION, ''"'', '' ''), l_group_class)) > 0 ',
'        -- check if the region is displayed e.g. through authorization, conditions...',
'        and  1 = apex_plugin_util.get_plsql_function_result(',
'                                     ''begin '' ||',
'                                        ''if ''||',
'                                           ''apex_plugin_util.is_component_used(''||',
'                                               ''p_build_option_id => '' || decode(aapr.BUILD_OPTION_ID, null,''null'',aapr.BUILD_OPTION_ID) ||',
'                                              '',p_authorization_scheme_id =>'''''' || aapr.AUTHORIZATION_SCHEME_ID ||',
'                                            '''''',p_condition_type          =>'''''' || (select d from apex_standard_conditions where r = aapr.CONDITION_TYPE) ||',
'                                            '''''',p_condition_expression1   =>'''''' || aapr.CONDITION_EXPRESSION1 ||',
'                                            '''''',p_condition_expression2   =>'''''' || aapr.CONDITION_EXPRESSION2 ||',
'                                            '''''',p_component => ''''region'''') '' ||',
'                                        ''then '' ||',
'                                            ''return 1;'' ||',
'                                        ''else '' ||',
'                                            ''return 0;''||',
'                                        ''end if; '' ||',
'                                      ''end;'')',
'      order by aapr.DISPLAY_SEQUENCE',
'   ) ',
'   , custom_label as (',
'        select  l_ALL_label, ''#SHOW_ALL'', l_ALL_position',
'          from  dual',
'         where  1=l_display_ALL                             ',
'   )',
'   , regions_and_label as (',
'        select  regions.* ',
'               ,rownum     seq ',
'          from  regions',
'         union all',
'        select  * ',
'          from  custom_label ',
'         order by seq nulls last',
'   )',
'   , count_all as (',
'        select count(*) reg_count from regions_and_label',
'   )',
'   select  decode(rownum, 1, '' class="apex-rds-item apex-rds-first"'', reg_count, '' class="apex-rds-item apex-rds-last"'', '' class="apex-rds-item"'') attr',
'          ,regions_and_label.*',
'     BULK collect into   l_attr_list, l_name_list , l_id_list, l_seq_list',
'     from  regions_and_label',
'          ,count_all;',
'          ',
'  -- open
 and
',
'  htp.p(''
'');  ',
'  htp.p(''
'');  ',
'  -- print the list',
'  for i in 1 .. l_attr_list.count loop',
'    htp.p(''
''); ',
'    htp.p('''' || l_name_list(i) ||''
'');',
'  end loop;',
'  -- close the tags',
'  htp.p(''
'');',
'  htp.p(''
'');',
'',
'  -- add the click event for the RDS region and trigger click on the ''Show All'' "tab"',
'  apex_javascript.add_onload_code(',
'    ''apex.widget.regionDisplaySelector("''|| l_id ||''",{"useSlider":true,"mode":"standard"});'' ||',
'         ''apex.jQuery("#''|| l_id ||''_RDS > li:'' || case when l_display_ALL = 1 then ',
'                                                                       ( case l_ALL_position when 0 then ''first'' else ''last'' end )',
'                                                                     else ''first'' end || '' > a:first").trigger("click");'');',
'',
'  return null;  ',
'  exception when others then',
'    apex_application.debug(sqlerrm);',
'    apex_application.debug(dbms_utility.format_error_stack);',
'    raise;',
'end render_RDS;'))
,p_api_version=>1
,p_render_function=>'render_RDS'
,p_substitute_attributes=>true
,p_subscribe_plugin_settings=>true
,p_help_text=>wwv_flow_string.join(wwv_flow_t_varchar2(
'
This plugin is intended to be a replacement for displaying RDS (Region Display Selector).
',
'
With this plugin it is possible to select regions going into RDS as well as to control the "Show All"-tab behavior (Show/Hide, Position, Label, Css-Attributs).
',
'
The customizations are listed below:
',
'
',
'
',
'		Region Grouping Class Name - choice of regions going into RDS.',
'		Regions going into the RDS selector can be restricted by class name - put in the Region Attributes, e.g. class="rds-example"
',
'
',
'		Display "Show All" - option if the "Show All"-tab should be displayed or not
',
'
',
'		Label of "Show All" - label of the "Show All" tab can be changed
',
'
',
'		Escape label of "Show All" - needed in case your label contains html tags (e.g. )
',
'
',
'		Css Attribute of "Show All" - you can set css attributes like title="your title" or class="class-name"
',
'
',
'		Position of "Show All" - first or last, default is last
',
'
',
'

',
'
',
'	Example:
',
'
',
'	In the regions going into the RDS, set Region Display Selector to "Yes" - as you would with the standard RDS.
',
'	Additionally, in the Region Attributes, set a class of your choice (e.g. class="rds-example").
',
'	Repeat this for all regions you want to group in this particular RDS - important: the class name must be the same.
',
'	In the RDS plugin attributes, set the first parameter Region Grouping Class Name to the name of the class you previously put in the regions'' attribute (e.g. rds-example).
',
'
',
'	You will find more detailed instructions on the demo page (link above).
'))
,p_version_identifier=>'1.1'
,p_about_url=>'http://apex.oracle.com/pls/apex/f?p=TER:RDS_CUSTOMIZABLE'
);
wwv_flow_api.create_plugin_attribute(
 p_id=>wwv_flow_api.id(11970934218208416166)
,p_plugin_id=>wwv_flow_api.id(11970926940241413112)
,p_attribute_scope=>'COMPONENT'
,p_attribute_sequence=>1
,p_display_sequence=>10
,p_prompt=>'Region Grouping Class Name'
,p_attribute_type=>'TEXT'
,p_is_required=>false
,p_display_length=>30
,p_max_length=>30
,p_is_translatable=>false
,p_help_text=>'The region can be grouped by class. Once a class is chosen, only those regions with the class go into the RDS. If left empty, all regions will be in the RDS.'
);
wwv_flow_api.create_plugin_attribute(
 p_id=>wwv_flow_api.id(11970934614953416167)
,p_plugin_id=>wwv_flow_api.id(11970926940241413112)
,p_attribute_scope=>'COMPONENT'
,p_attribute_sequence=>2
,p_display_sequence=>20
,p_prompt=>'Display "Show All"'
,p_attribute_type=>'CHECKBOX'
,p_is_required=>false
,p_default_value=>'Y'
,p_is_translatable=>false
,p_help_text=>'Display or hide the tab "Show All".'
);
wwv_flow_api.create_plugin_attribute(
 p_id=>wwv_flow_api.id(11970935015356416171)
,p_plugin_id=>wwv_flow_api.id(11970926940241413112)
,p_attribute_scope=>'COMPONENT'
,p_attribute_sequence=>3
,p_display_sequence=>30
,p_prompt=>'Label of "Show All"'
,p_attribute_type=>'TEXT'
,p_is_required=>false
,p_default_value=>'Show All'
,p_display_length=>65
,p_max_length=>200
,p_is_translatable=>false
,p_depending_on_attribute_id=>wwv_flow_api.id(11970934614953416167)
,p_depending_on_has_to_exist=>true
,p_depending_on_condition_type=>'EQUALS'
,p_depending_on_expression=>'Y'
,p_help_text=>'Custom label for "Show All" tab. This can also be an html tag. If so, you need to set the next attribute Escape label of "Show All" to "No".'
);
wwv_flow_api.create_plugin_attribute(
 p_id=>wwv_flow_api.id(11970935412147416172)
,p_plugin_id=>wwv_flow_api.id(11970926940241413112)
,p_attribute_scope=>'COMPONENT'
,p_attribute_sequence=>4
,p_display_sequence=>40
,p_prompt=>'Escape label of "Show All"'
,p_attribute_type=>'CHECKBOX'
,p_is_required=>false
,p_default_value=>'N'
,p_is_translatable=>false
,p_depending_on_attribute_id=>wwv_flow_api.id(11970934614953416167)
,p_depending_on_has_to_exist=>true
,p_depending_on_condition_type=>'EQUALS'
,p_depending_on_expression=>'Y'
,p_help_text=>'In case you want to set an html tag instead of simple text (e.g. ), set this attribute to "No"; otherwise leave the default value.'
);
wwv_flow_api.create_plugin_attribute(
 p_id=>wwv_flow_api.id(11970935816698416173)
,p_plugin_id=>wwv_flow_api.id(11970926940241413112)
,p_attribute_scope=>'COMPONENT'
,p_attribute_sequence=>5
,p_display_sequence=>50
,p_prompt=>'Css Attribute of "Show All"'
,p_attribute_type=>'TEXT'
,p_is_required=>false
,p_display_length=>65
,p_max_length=>200
,p_is_translatable=>false
,p_depending_on_attribute_id=>wwv_flow_api.id(11970934614953416167)
,p_depending_on_has_to_exist=>true
,p_depending_on_condition_type=>'EQUALS'
,p_depending_on_expression=>'Y'
,p_help_text=>wwv_flow_string.join(wwv_flow_t_varchar2(
'This can be any css attribute, e.g:',
'
class="your-class-name"
',
'or ',
'
style="color:red;"
',
'or',
'
title="your title"
',
''))
);
wwv_flow_api.create_plugin_attribute(
 p_id=>wwv_flow_api.id(11970936235133416175)
,p_plugin_id=>wwv_flow_api.id(11970926940241413112)
,p_attribute_scope=>'COMPONENT'
,p_attribute_sequence=>6
,p_display_sequence=>60
,p_prompt=>'Position of "Show All"'
,p_attribute_type=>'SELECT LIST'
,p_is_required=>false
,p_default_value=>'f'
,p_is_translatable=>false
,p_depending_on_attribute_id=>wwv_flow_api.id(11970934614953416167)
,p_depending_on_has_to_exist=>true
,p_depending_on_condition_type=>'EQUALS'
,p_depending_on_expression=>'Y'
,p_lov_type=>'STATIC'
,p_help_text=>'The position of the "Show All" tab. Unlike in the standard RDS, the default position here is the first one.'
);
wwv_flow_api.create_plugin_attr_value(
 p_id=>wwv_flow_api.id(11970936610485416176)
,p_plugin_attribute_id=>wwv_flow_api.id(11970936235133416175)
,p_display_sequence=>10
,p_display_value=>'First'
,p_return_value=>'f'
);
wwv_flow_api.create_plugin_attr_value(
 p_id=>wwv_flow_api.id(11970937121353416177)
,p_plugin_attribute_id=>wwv_flow_api.id(11970936235133416175)
,p_display_sequence=>20
,p_display_value=>'Last'
,p_return_value=>'l'
);
end;
/
begin
wwv_flow_api.import_end(p_auto_install_sup_obj => nvl(wwv_flow_application_install.get_auto_install_sup_obj, false), p_is_component_import => true);
commit;
end;
/
set verify on feedback on define on
prompt  ...done


text:
angular.module('biodags-admin').service('MovieService', function ($http, $q, $rootScope) {

    this.get = function () {

        return $http({
                    method: 'GET',
                    url: $rootScope.appSettings.backendUrl + "status"
                });

    };

});


text:
require 'rails_helper'

RSpec.describe "reviews/new", type: :view do
  before(:each) do
    assign(:review, Review.new(
      :rating => 1,
      :comment => "MyText"
    ))
  end

  it "renders new review form" do
    render

    assert_select "form[action=?][method=?]", reviews_path, "post" do

      assert_select "input#review_rating[name=?]", "review[rating]"

      assert_select "textarea#review_comment[name=?]", "review[comment]"
    end
  end
end


text:
		<?php
		// $slider = array(1,0);
		// $slider_rand_key = array_rand($slider, 1);
		// echo ($slider_rand_key);
		// if ($slider[$slider_rand_key]<1) {
		?>

		<?php
		// }else{
		?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<assessment xmlns="http://conqat.cs.tum.edu/ns/architecture-assessment">
  <component name="BigA">
    <component name="A">
      <component name="SmallA" />
    </component>
  </component>
  <component name="BigB">
    <component name="B">
      <component name="SmallB" />
    </component>
  </component>
  <orphan name="i.am.an.Orphan" />
</assessment>


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/automl/v1/geometry.proto

namespace GPBMetadata\Google\Cloud\Automl\V1;

class Geometry
{
    public static $is_initialized = false;

    public static function initOnce() {
        $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();

        if (static::$is_initialized == true) {
          return;
        }
        $pool->internalAddGeneratedFile(
            '
õ
%google/cloud/automl/v1/geometry.protogoogle.cloud.automl.v1"(
NormalizedVertex
x (
y ("U
BoundingPolyE
normalized_vertices (2(.google.cloud.automl.v1.NormalizedVertexBª
com.google.cloud.automl.v1PZ<google.golang.org/genproto/googleapis/cloud/automl/v1;automlªGoogle.Cloud.AutoML.V1ÊGoogle\\Cloud\\AutoMl\\V1êGoogle::Cloud::AutoML::V1bproto3'
        , true);

        static::$is_initialized = true;
    }
}


text:
package com.hazelcast.config;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SecurityConfig {

    private boolean enabled = false;

    private CredentialsFactoryConfig memberCredentialsConfig = new CredentialsFactoryConfig();

    private List<LoginModuleConfig> memberLoginModuleConfigs = new ArrayList<LoginModuleConfig>();

    private List<LoginModuleConfig> clientLoginModuleConfigs = new ArrayList<LoginModuleConfig>();

    private PermissionPolicyConfig clientPolicyConfig = new PermissionPolicyConfig();

    private Set<PermissionConfig> clientPermissionConfigs = new HashSet<PermissionConfig>();

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public void addMemberLoginModuleConfig(LoginModuleConfig loginModuleConfig) {
        memberLoginModuleConfigs.add(loginModuleConfig);
    }

    public void addClientLoginModuleConfig(LoginModuleConfig loginModuleConfig) {
        clientLoginModuleConfigs.add(loginModuleConfig);
    }

    public void addClientPermissionConfig(PermissionConfig permissionConfig) {
        clientPermissionConfigs.add(permissionConfig);
    }

    public List<LoginModuleConfig> getClientLoginModuleConfigs() {
        return clientLoginModuleConfigs;
    }

    public void setClientLoginModuleConfigs(List<LoginModuleConfig> loginModuleConfigs) {
        this.clientLoginModuleConfigs = loginModuleConfigs;
    }

    public List<LoginModuleConfig> getMemberLoginModuleConfigs() {
        return memberLoginModuleConfigs;
    }

    public void setMemberLoginModuleConfigs(
            List<LoginModuleConfig> memberLoginModuleConfigs) {
        this.memberLoginModuleConfigs = memberLoginModuleConfigs;
    }

    public PermissionPolicyConfig getClientPolicyConfig() {
        return clientPolicyConfig;
    }

    public void setClientPolicyConfig(PermissionPolicyConfig policyConfig) {
        this.clientPolicyConfig = policyConfig;
    }

    public Set<PermissionConfig> getClientPermissionConfigs() {
        return clientPermissionConfigs;
    }

    public void setClientPermissionConfigs(Set<PermissionConfig> permissions) {
        this.clientPermissionConfigs = permissions;
    }

    public CredentialsFactoryConfig getMemberCredentialsConfig() {
        return memberCredentialsConfig;
    }

    public void setMemberCredentialsConfig(
            CredentialsFactoryConfig credentialsFactoryConfig) {
        this.memberCredentialsConfig = credentialsFactoryConfig;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("SecurityConfig");
        sb.append("{enabled=").append(enabled);
        sb.append(", memberCredentialsConfig=").append(memberCredentialsConfig);
        sb.append(", memberLoginModuleConfigs=").append(memberLoginModuleConfigs);
        sb.append(", clientLoginModuleConfigs=").append(clientLoginModuleConfigs);
        sb.append(", clientPolicyConfig=").append(clientPolicyConfig);
        sb.append(", clientPermissionConfigs=").append(clientPermissionConfigs);
        sb.append('}');
        return sb.toString();
    }
}


text:
module Onboarding
  class ClusteringController < BaseController
    before_action only: [:new, :create] do
      redirect_if_event(:onboarding_user_created, new_onboarding_school_details_path(@school_onboarding))
    end

    def new
    end

    def create
      @school_onboarding.update!(created_user: current_user)
      @school_onboarding.events.create!(event: :onboarding_user_created)
      redirect_to new_onboarding_school_details_path(@school_onboarding)
    end
  end
end


text:
#ifndef POLYGRAPH__CSM_RNDBODYITER_H
#define POLYGRAPH__CSM_RNDBODYITER_H

#include "csm/BodyIter.h"

class RndBodyIter: public BodyIter {
	public:
		virtual RndBodyIter *clone() const;

	protected:
		virtual bool pourBody();
		virtual void calcContentSize() const;
};

#endif


text:
#ifndef TALK_MEDIA_SCTP_HYBRIDDATAENGINE_H_
#define TALK_MEDIA_SCTP_HYBRIDDATAENGINE_H_

#include <string>
#include <vector>

#include "talk/media/base/codec.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/mediaengine.h"
#include "webrtc/base/scoped_ptr.h"

namespace cricket {

class HybridDataEngine : public DataEngineInterface {
 public:
  // Takes ownership.
  HybridDataEngine(DataEngineInterface* first,
                   DataEngineInterface* second)
      : first_(first),
        second_(second) {
    codecs_ = first_->data_codecs();
    codecs_.insert(
        codecs_.end(),
        second_->data_codecs().begin(),
        second_->data_codecs().end());
  }

  virtual DataMediaChannel* CreateChannel(DataChannelType data_channel_type) {
    DataMediaChannel* channel = NULL;
    if (first_) {
      channel = first_->CreateChannel(data_channel_type);
    }
    if (!channel && second_) {
      channel = second_->CreateChannel(data_channel_type);
    }
    return channel;
  }

  virtual const std::vector<DataCodec>& data_codecs() { return codecs_; }

 private:
  rtc::scoped_ptr<DataEngineInterface> first_;
  rtc::scoped_ptr<DataEngineInterface> second_;
  std::vector<DataCodec> codecs_;
};

}  // namespace cricket

#endif  // TALK_MEDIA_SCTP_HYBRIDDATAENGINE_H_