text:
package org.apache.isis.core.metamodel.facets.param.parameter;

import org.apache.isis.applib.annotation.*;
import org.apache.isis.core.commons.config.IsisConfiguration;
import org.apache.isis.core.metamodel.facetapi.Facet;
import org.apache.isis.core.metamodel.facetapi.FacetUtil;
import org.apache.isis.core.metamodel.facetapi.FeatureType;
import org.apache.isis.core.metamodel.facetapi.MetaModelValidatorRefiner;
import org.apache.isis.core.metamodel.facets.Annotations;
import org.apache.isis.core.metamodel.facets.FacetFactoryAbstract;
import org.apache.isis.core.metamodel.facets.FacetedMethodParameter;
import org.apache.isis.core.metamodel.facets.objectvalue.mandatory.MandatoryFacet;
import org.apache.isis.core.metamodel.facets.objectvalue.regex.RegExFacet;
import org.apache.isis.core.metamodel.facets.objectvalue.regex.TitleFacetFormattedByRegex;
import org.apache.isis.core.metamodel.facets.param.parameter.fileaccept.FileAcceptFacetForParameterAnnotation;
import org.apache.isis.core.metamodel.facets.param.parameter.mandatory.MandatoryFacetForParameterAnnotation;
import org.apache.isis.core.metamodel.facets.param.parameter.mandatory.MandatoryFacetInvertedByNullableAnnotationOnParameter;
import org.apache.isis.core.metamodel.facets.param.parameter.mandatory.MandatoryFacetInvertedByOptionalAnnotationOnParameter;
import org.apache.isis.core.metamodel.facets.param.parameter.maxlen.MaxLengthFacetForMaxLengthAnnotationOnParameter;
import org.apache.isis.core.metamodel.facets.param.parameter.maxlen.MaxLengthFacetForParameterAnnotation;
import org.apache.isis.core.metamodel.facets.param.parameter.mustsatisfy.MustSatisfySpecificationFacetForMustSatisfyAnnotationOnParameter;
import org.apache.isis.core.metamodel.facets.param.parameter.mustsatisfy.MustSatisfySpecificationFacetForParameterAnnotation;
import org.apache.isis.core.metamodel.facets.param.parameter.regex.RegExFacetForParameterAnnotation;
import org.apache.isis.core.metamodel.facets.param.parameter.regex.RegExFacetFromRegExAnnotationOnParameter;
import org.apache.isis.core.metamodel.services.ServicesInjector;
import org.apache.isis.core.metamodel.specloader.validator.MetaModelValidatorComposite;
import org.apache.isis.core.metamodel.specloader.validator.MetaModelValidatorForConflictingOptionality;
import org.apache.isis.core.metamodel.specloader.validator.MetaModelValidatorForDeprecatedAnnotation;

import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class ParameterAnnotationFacetFactory extends FacetFactoryAbstract implements MetaModelValidatorRefiner {

    private final MetaModelValidatorForDeprecatedAnnotation maxLengthValidator = new MetaModelValidatorForDeprecatedAnnotation(MaxLength.class);
    private final MetaModelValidatorForDeprecatedAnnotation mustSatisfyValidator = new MetaModelValidatorForDeprecatedAnnotation(MustSatisfy.class);
    private final MetaModelValidatorForDeprecatedAnnotation regexValidator = new MetaModelValidatorForDeprecatedAnnotation(RegEx.class);
    private final MetaModelValidatorForDeprecatedAnnotation optionalValidator = new MetaModelValidatorForDeprecatedAnnotation(Optional.class);
    private final MetaModelValidatorForConflictingOptionality conflictingOptionalityValidator = new MetaModelValidatorForConflictingOptionality();

    public ParameterAnnotationFacetFactory() {
        super(FeatureType.PARAMETERS_ONLY);
    }

    @Override
    public void processParams(final ProcessParameterContext processParameterContext) {

        final Method method = processParameterContext.getMethod();
        final int paramNum = processParameterContext.getParamNum();

        final Class<?>[] parameterTypes = method.getParameterTypes();
        if (paramNum >= parameterTypes.length) {
            return; // ignore
        }

        processParamsMaxLength(processParameterContext);
        processParamsMustSatisfy(processParameterContext);
        processParamsRegEx(processParameterContext);
        processParamsOptional(processParameterContext);
        processParamsFileAccept(processParameterContext);
    }

    void processParamsMaxLength(final ProcessParameterContext processParameterContext) {

        final Method method = processParameterContext.getMethod();
        final int paramNum = processParameterContext.getParamNum();
        final FacetedMethodParameter holder = processParameterContext.getFacetHolder();
        final Annotation[] parameterAnnotations = Annotations.getParameterAnnotations(method)[paramNum];

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof MaxLength) {
                final MaxLength annotation = (MaxLength) parameterAnnotation;
                final org.apache.isis.core.metamodel.facets.objectvalue.maxlen.MaxLengthFacet facet = MaxLengthFacetForMaxLengthAnnotationOnParameter.create(annotation, processParameterContext.getFacetHolder());
                FacetUtil.addFacet(maxLengthValidator.flagIfPresent(facet, processParameterContext));
                return;
            }
        }

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof Parameter) {
                final Parameter parameter = (Parameter) parameterAnnotation;
                FacetUtil.addFacet(
                        MaxLengthFacetForParameterAnnotation.create(parameter, holder));
                return;
            }
        }
    }

    void processParamsMustSatisfy(final ProcessParameterContext processParameterContext) {

        final Method method = processParameterContext.getMethod();
        final int paramNum = processParameterContext.getParamNum();
        final FacetedMethodParameter holder = processParameterContext.getFacetHolder();
        final Annotation[] parameterAnnotations = Annotations.getParameterAnnotations(method)[paramNum];

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof MustSatisfy) {
                final MustSatisfy annotation = (MustSatisfy) parameterAnnotation;
                final Facet facet = MustSatisfySpecificationFacetForMustSatisfyAnnotationOnParameter.create(annotation, processParameterContext.getFacetHolder(), servicesInjector);
                FacetUtil.addFacet(mustSatisfyValidator.flagIfPresent(facet, processParameterContext));
                return;
            }
        }

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof Parameter) {
                final Parameter parameter = (Parameter) parameterAnnotation;
                FacetUtil.addFacet(
                        MustSatisfySpecificationFacetForParameterAnnotation.create(parameter, holder, servicesInjector));
                return;
            }
        }
    }

    void processParamsRegEx(final ProcessParameterContext processParameterContext) {

        final Method method = processParameterContext.getMethod();
        final int paramNum = processParameterContext.getParamNum();
        final FacetedMethodParameter holder = processParameterContext.getFacetHolder();
        final Class<?>[] parameterTypes = method.getParameterTypes();
        final Annotation[] parameterAnnotations = Annotations.getParameterAnnotations(method)[paramNum];

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            final Class<?> parameterType = parameterTypes[paramNum];
            if (parameterAnnotation instanceof RegEx) {
                final RegEx annotation = (RegEx) parameterAnnotation;
                final RegExFacet facet = RegExFacetFromRegExAnnotationOnParameter.create(annotation, parameterType, holder);
                FacetUtil.addFacet(regexValidator.flagIfPresent(facet, processParameterContext));
                final RegExFacet regExFacet = facet;

                // regex also adds a title facet
                if(regExFacet != null) {
                    FacetUtil.addFacet(new TitleFacetFormattedByRegex(regExFacet));
                }
                return;
            }
        }

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof Parameter) {
                final Parameter parameter = (Parameter) parameterAnnotation;
                final Class<?> parameterType = parameterTypes[paramNum];
                FacetUtil.addFacet(
                        RegExFacetForParameterAnnotation.create(parameter, parameterType, holder));
                return;
            }
        }
    }

    void processParamsOptional(final ProcessParameterContext processParameterContext) {

        final Method method = processParameterContext.getMethod();
        final int paramNum = processParameterContext.getParamNum();
        final FacetedMethodParameter holder = processParameterContext.getFacetHolder();
        final Class<?>[] parameterTypes = method.getParameterTypes();
        final Annotation[] parameterAnnotations = Annotations.getParameterAnnotations(method)[paramNum];

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            final Class<?> parameterType = parameterTypes[paramNum];
            if (parameterAnnotation instanceof Optional) {
                final Optional annotation = (Optional) parameterAnnotation;
                FacetUtil.addFacet(optionalValidator.flagIfPresent(
                        MandatoryFacetInvertedByOptionalAnnotationOnParameter.create(
                                annotation, parameterType, holder), processParameterContext));
            }
        }

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            final Class<?> parameterType = parameterTypes[paramNum];
            if (parameterAnnotation instanceof javax.annotation.Nullable) {
                final Nullable annotation = (Nullable) parameterAnnotation;
                final MandatoryFacet facet =
                        MandatoryFacetInvertedByNullableAnnotationOnParameter.create(annotation, parameterType, holder);
                FacetUtil.addFacet(facet);
                conflictingOptionalityValidator.flagIfConflict(
                        facet, "Conflicting @Nullable with other optionality annotation");
            }
        }

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof Parameter) {
                final Parameter parameter = (Parameter) parameterAnnotation;
                final Class<?> parameterType = parameterTypes[paramNum];
                final MandatoryFacet facet =
                        MandatoryFacetForParameterAnnotation.create(parameter, parameterType, holder);
                FacetUtil.addFacet(facet);
                conflictingOptionalityValidator.flagIfConflict(
                        facet, "Conflicting @Parameter#optionality with other optionality annotation");
            }
        }
    }

    void processParamsFileAccept(final ProcessParameterContext processParameterContext) {

        final Method method = processParameterContext.getMethod();
        final int paramNum = processParameterContext.getParamNum();
        final FacetedMethodParameter holder = processParameterContext.getFacetHolder();
        final Annotation[] parameterAnnotations = Annotations.getParameterAnnotations(method)[paramNum];

        for (final Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof Parameter) {
                final Parameter parameter = (Parameter) parameterAnnotation;
                FacetUtil.addFacet(
                        FileAcceptFacetForParameterAnnotation.create(parameter, holder));
                return;
            }
        }
    }

    @Override
    public void refineMetaModelValidator(final MetaModelValidatorComposite metaModelValidator, final IsisConfiguration configuration) {
        metaModelValidator.add(maxLengthValidator);
        metaModelValidator.add(mustSatisfyValidator);
        metaModelValidator.add(regexValidator);
        metaModelValidator.add(optionalValidator);
        metaModelValidator.add(conflictingOptionalityValidator);
    }

    @Override
    public void setServicesInjector(final ServicesInjector servicesInjector) {
        super.setServicesInjector(servicesInjector);
        IsisConfiguration configuration = servicesInjector.getConfigurationServiceInternal();
        maxLengthValidator.setConfiguration(configuration);
        mustSatisfyValidator.setConfiguration(configuration);
        regexValidator.setConfiguration(configuration);
        optionalValidator.setConfiguration(configuration);
    }

}


text:
import Wreqr from 'backbone.wreqr';
import Marionette from 'backbone.marionette';
import template from 'templates/contributionErrorNotification.ejs';

export default Marionette.LayoutView.extend({
  template,

  behaviors: {
    l20n: {},
    notification: {
      destroyOnClose: true
    }
  },

  ui: {
    notification: '.notification',

    content: '.content',

    retryButton: '.retry_btn'
  },

  events: {
    'click @ui.retryButton': 'onClickRetry'
  },

  initialize() {
    this._radio = Wreqr.radio.channel('global');

    return this.render();
  },

  open() {
    this.triggerMethod('open');
    return this;
  },

  close() {
    this.triggerMethod('close');
    return this;
  },

  onClickRetry() {
    this.options.retryCallback();

    this.close();
  }
});

redpajama_set_name: RedPajamaGithub


text:
require 'test/unit'
require_relative '../lib/fakir'

class VersionTest < Test::Unit::TestCase
  def test_version
    assert_equal "0.0.1", Fakir::VERSION
  end
end


text:
module LSQS
  module Actions
    class GetQueueUrl < Base
      ##
      # Performs the specific action.
      #
      # @param [Hash] params
      #
      # @return [String]
      #
      def perform(params)
        base_url = params['base_url']
        name     = params['QueueName']

        queue = queue_list.find(name)

        url = build_url(base_url, name)

        builder.QueueUrl build_url(base_url, name)
      end
    end # GetQueueUrl
  end # Actions
end # LSQS


text:
namespace mozc {
namespace gui {

WindowsSelectionHandler::WindowsSelectionHandler() {}
WindowsSelectionHandler::~WindowsSelectionHandler() {}

void WindowsSelectionHandler::Select(const QString &str) {
  vector<INPUT> inputs;
  for (int i = 0; i < str.size(); ++i) {
    INPUT input = { 0 };
    KEYBDINPUT kb = { 0 };
    const wchar_t ucs2 = static_cast<wchar_t>(str[i].unicode());

    // down
    kb.wScan = ucs2;
    kb.dwFlags = KEYEVENTF_UNICODE;
    input.type = INPUT_KEYBOARD;
    input.ki = kb;
    inputs.push_back(input);

    // up
    kb.wScan = ucs2;
    kb.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
    input.type = INPUT_KEYBOARD;
    input.ki = kb;
    inputs.push_back(input);
  }

  if (inputs.empty()) {
    return;
  }

  if (!::SendInput(static_cast<UINT>(inputs.size()),
                   &inputs[0], sizeof(inputs[0]))) {
    LOG(ERROR)<< "SendInput failed: " << ::GetLastError();
    return;
  }
}
}  // namespace gui
}  // namespace mozc
#endif   // OS_WIN


text:
package com.sebastian_daschner.jaxrs_analyzer.backend;

import com.sebastian_daschner.jaxrs_analyzer.model.rest.*;

import javax.json.*;
import javax.json.spi.JsonProvider;
import javax.json.stream.JsonGenerator;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;

import static com.sebastian_daschner.jaxrs_analyzer.model.JavaUtils.toReadableType;
import static java.util.Collections.singletonMap;
import static java.util.Comparator.comparing;

/**
 * A backend that is backed by Strings (plain text).
 *
 * @author Sebastian Daschner
 */
public abstract class StringBackend implements Backend {

    public static final String INLINE_PRETTIFY = "inlinePrettify";
    private static final String INLINE_PRETTIFY_DEFAULT = "true";
    private static final Pattern CLEAR_COMPONENT_TYPE = Pattern.compile("[+\\-]");

    protected final Lock lock = new ReentrantLock();
    protected StringBuilder builder;
    protected Resources resources;
    protected String projectName;
    protected String projectVersion;
    protected boolean prettify;

    @Override
    public void configure(final Map<String, String> config) {
        prettify = Boolean.parseBoolean(config.getOrDefault(INLINE_PRETTIFY, INLINE_PRETTIFY_DEFAULT));
    }

    @Override
    public byte[] render(final Project project) {
        lock.lock();
        try {
            initRender(project);

            final String output = renderInternal();

            return serialize(output);
        } finally {
            lock.unlock();
        }
    }

    private void initRender(final Project project) {
        // initialize fields
        builder = new StringBuilder();
        resources = project.getResources();
        projectName = project.getName();
        projectVersion = project.getVersion();
    }

    private String renderInternal() {
        appendHeader();

        resources.getResources().stream().sorted().forEach(this::appendResource);

        return builder.toString();
    }

    private void appendHeader() {
        appendFirstLine();
        builder.append(projectVersion).append("\n\n");
    }

    private void appendResource(final String resource) {
        resources.getMethods(resource).stream()
                .sorted(comparing(ResourceMethod::getMethod))
                .forEach(resourceMethod -> {
                    appendMethod(resources.getBasePath(), resource, resourceMethod);
                    appendRequest(resourceMethod);
                    appendResponse(resourceMethod);
                    appendResourceEnd();
                });
    }

    protected abstract void appendFirstLine();

    protected abstract void appendMethod(String baseUri, String resource, ResourceMethod resourceMethod);

    protected abstract void appendRequest(ResourceMethod resourceMethod);

    protected abstract void appendResponse(ResourceMethod resourceMethod);

    protected void appendResourceEnd() {
    }

    protected String doVisit(final TypeRepresentation typeRepresentation) {
        final StringBuilder builder = new StringBuilder();
        final TypeRepresentationVisitor appender = new JsonRepresentationAppender(builder,
                resources.getTypeRepresentations());
        typeRepresentation.accept(appender);
        final String json = builder.toString();
        return prettify ? format(json) : json;
    }

    protected String toReadableComponentType(TypeIdentifier componentType) {
        final String type = componentType.getType();
        return toReadableType(CLEAR_COMPONENT_TYPE.matcher(type).replaceAll(""));
    }

    private static byte[] serialize(final String output) {
        return output.getBytes();
    }

    private String format(final String json) {
        final JsonProvider provider = JsonProvider.provider();
        final StringWriter out = new StringWriter();
        try (final JsonReader reader = provider.createReader(new StringReader(json));
             final JsonWriter jsonWriter = provider.createWriterFactory(singletonMap(JsonGenerator.PRETTY_PRINTING, true))
                     .createWriter(out)) {

            // jsonWriter.write(reader.readValue()); // bug in RI, can switch to johnzon
            final JsonStructure read = reader.read();
            if (read.getValueType() == JsonValue.ValueType.OBJECT) {
                jsonWriter.writeObject(JsonObject.class.cast(read));
            } else if (read.getValueType() == JsonValue.ValueType.ARRAY) {
                jsonWriter.writeArray(JsonArray.class.cast(read));
            } else { // no reformatting
                return json;
            }
            return out.toString().trim();
        }
    }
}


text:
import logging
import sys

logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
                    level=logging.DEBUG,
                    stream=sys.stdout)
from xml.dom import minidom
import pymysql
import pymysql.cursors
from dbconfig import mysql
import re

def simplify_latex(latex):
    latex = latex.strip()
    pattern = re.compile("^\\\mbox\{(.*?)\}$")
    matches = pattern.findall(latex)
    if len(matches) == 1 and len(matches[0]) > 0:
        latex = matches[0]
    return latex

def read():
    latex2unicode_dec = {}

    xmldoc = minidom.parse('unicode.xml')
    itemlist = xmldoc.getElementsByTagName('character')
    logging.info("Read %i characters.", len(itemlist))
    for s in itemlist:
        t = s.getElementsByTagName('mathlatex')
        tn = s.getElementsByTagName('latex')
        desctags = s.getElementsByTagName('description')
        if len(desctags) > 0 and desctags[0].firstChild is not None:
            desc = desctags[0].firstChild.nodeValue.strip()
        if "'" in desc:
            desc = desc.replace("'", "\\'")
        if len(t) >= 1:
            dec = s.attributes['dec'].value
            for el in t:
                latex = simplify_latex(el.firstChild.nodeValue)
                if len(t) > 1:
                    logging.info("multiple (mathmode): '%s'", latex)
                try:
                    latex2unicode_dec[latex] = {'dec': int(dec),
                                                'desc': desc}
                except:
                    logging.debug("%s did not work", dec)
        if len(tn) >= 1:
            dec = s.attributes['dec'].value
            for el in tn:
                latex = simplify_latex(el.firstChild.nodeValue)
                if len(t) > 1:
                    logging.info("multiple (not mathmode): '%s'", latex)
                try:
                    latex2unicode_dec[latex] = {'dec': int(dec),
                                                'desc': desc}
                except:
                    logging.debug("%s did not work", dec)
        # else:
        #     t = s.getElementsByTagName('description')
        # if len(t) > 0 and t[0].firstChild is not None:
        #     desc = t[0].firstChild.nodeValue
        #     if not any([desc.startswith("VARIATION SELECTOR"),
        #                 desc.startswith("CJK COMPATIBILITY IDEOGRAPH")]):
        #         logging.info("'%s' has no latex", desc)
        # else:
        #     char_id = s.attributes['id'].value
        #     logging.info("Charid'%s' has no latex and no desc.", char_id)
    return latex2unicode_dec

def get_formula_datasets():
    connection = pymysql.connect(host=mysql['host'],
                                 user=mysql['user'],
                                 passwd=mysql['passwd'],
                                 db=mysql['db'],
                                 cursorclass=pymysql.cursors.DictCursor)
    cursor = connection.cursor()
    sql = ("SELECT id, formula_in_latex FROM `wm_formula` "
           "WHERE formula_type = 'single symbol'")
    cursor.execute(sql)
    datasets = cursor.fetchall()
    formula_datasets = {}
    for el in datasets:
        formula_datasets[el['formula_in_latex']] = el['id']
    return formula_datasets

def update(latex2unicode, formula_datasets):
    connection = pymysql.connect(host=mysql['host'],
                                 user=mysql['user'],
                                 passwd=mysql['passwd'],
                                 db=mysql['db'],
                                 cursorclass=pymysql.cursors.DictCursor)
    cursor = connection.cursor()
    for latex, mysql_id in formula_datasets.items():
        if latex in latex2unicode:
            unicode_dec = latex2unicode[latex]['dec']
            desc = latex2unicode[latex]['desc']
            sql = ("UPDATE `wm_formula` "
                   "SET `unicode_dec` = '%i', `unicodexml_description` = '%s' "
                   "WHERE `id`= %i LIMIT 1;") % (unicode_dec, desc, mysql_id)
            # Commented out to prevent accidents
            # try:
            #     print(sql)
            #     cursor.execute(sql)
            #     connection.commit()
            # except Exception as e:
            #     print(e)
        else:
            logging.info("%s is not in latex2unicode", latex)

def main():
    # 1. Download all data (id, latex)
    formula_datasets = get_formula_datasets()
    logging.info("Got %i datasets from server.", len(formula_datasets))

    # 2. Get data from unicode.xml
    latex2unicode = read()
    logging.info("Got %i elements.", len(latex2unicode))

    # 3. update unicode_dec where latex matches
    update(latex2unicode, formula_datasets)

    # 4. Find my datasets where no unicode_dec is specified - later
    # 4. find unicode_dec which don't have an entry in my database

if __name__ == '__main__':
    main()


text:
<?php

namespace Arauco\BaseBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;

class Builder extends ContainerAware
{
    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');

        $menu->addChild('Inicio', array('route' => 'arauco_home'));
        $menu->addChild('Stock', array('route' => 'arauco_stock_index'));
        $menu->addChild('Pedidos', array('route' => 'arauco_pedido_index'));
        $menu->addChild('Balance', array('route' => 'arauco_balance_index'));

        /*$pedidos->addChild('Todos', array('route' => 'arauco_pedido_index'));
        $pedidos->addChild('AASA', array('route' => 'arauco_pedido_index_aasa'));
        $pedidos->addChild('PASA', array('route' => 'arauco_pedido_index_pasa'));*/

        return $menu;
    }
}


text:
<?php

namespace Splash\Tests;
use Splash\Splash;

class CustomIteratorTest extends \PHPUnit_Framework_TestCase {
  /**
   * Test the CallbackIterator
   */
  public function testCallback() {
    $expected = array(
      11,
      21,
    );
    $actual = splash(10, 20)->callback(function (&$v) {
      $v++;
      return TRUE;
    })->toArray();
    $this->assertEquals($expected, $actual);

    $expected = array(
      11,
      21,
    );
    $actual = splash(1, 2)->callback(function ($v, $k, $it, $new) {
      if ($v == 1) {
        $new->append(11);
        $new->append(21);
      }
    })->toArray();
    $this->assertEquals($expected, $actual);
  }

  /**
   * Test the InverseRegexIterator
   */
  public function testInverseRegex() {
    $data = array(
      'foo',
      'bar',
    );
    $expected = array(
      'foo',
    );
    $actual = splash()->appendArray($data)->inverseRegex('/bar/')->toArray();
    $this->assertEquals($expected, $actual);
  }

  /**
   * Test the SliceIterator
   */
  public function testSlice() {
    $expected = array(
      'bar',
      'bar2',
    );
    $actual = splash('foo', 'bar', 'bar2')->slice(1)->toArray();
    $this->assertEquals($expected, $actual);

    $expected = array(
      'bar',
    );
    $actual = splash('foo', 'bar', 'bar2')->slice(1, 1)->toArray();
    $this->assertEquals($expected, $actual);
  }

}


text:
using namespace std;

class IrisFatalErrorHandler
{
public:

	typedef void(*FatalErrorMessageFunction)(const string& strMessage);

	enum class FatalErrorType {
		SyntaxIrregular = 0,
		IdenfierTypeIrregular,
		NoMethodIrregular,
		IrregularNotDealedIrregular,
		SourceObjectIrregular,
		IdentifierNotFoundIrregular,
		ReturnIrregular,
		LeftValueIrregular,
		SelfPointerIrregular,
		ConstanceReassignIrregular,
		ConstanceDeclareIrregular,
		ClassVariableDeclareIrregular,
		MethodAuthorityIrregular,
		ClassNotCompleteIrregular,
		ParameterNotFitIrregular,
		NoMethodCanSuperIrregular,
		FieldCannotRoutedIrregular,
		ContinueIrregular,
		BreakIrregular,
		UnkownIrregular,

		InvalidLeftExpressionIrregular,
		CastExpressionIrregular,
		SelfExpressionIrregular,
		AuthorityStatementIrregular,
		BlockStatementIrregular,
		AccessorStatementIrregular,
		ClassStatementIrregular,
		InterfaceFunctionStatementIrregular,
		SuperStatementIrregular,
	};

private:
	static IrisFatalErrorHandler* sm_pInstance;

private:
	FatalErrorMessageFunction s_pfMessageFunction;

public:
	static IrisFatalErrorHandler* CurrentFatalHandler();
	static void SetCurrentFatalHandler(IrisFatalErrorHandler* pHandler);

public:
	void SetFatalErrorMessageFuncton(FatalErrorMessageFunction pfFunction);
	void ShowFatalErrorMessage(FatalErrorType eType, size_t nLineNumber, size_t nBelongingFileIndex, const string & strFatalErrorMessage);
	void ShowFatalErrorDirectly(const string& strFatalErrorMessage);

private:
	IrisFatalErrorHandler();
public:
	~IrisFatalErrorHandler();
};

#endif


text:
/* global ng */

(function(app) {
  app.ExamplesComponent = ng.core.Component({
    selector: 'box-ui-examples',
    templateUrl: 'examples.component.html',
    directives: [app.CollapseButtonDirective],
    host: {
      'class': 'page-content'
    }
  })
  .Class({
    constructor: function () {}
  });

})(window.app || (window.app = {}));


text:
class DebianStorageMining : public iStrategy
{
public:
    DebianStorageMining();
    QJsonObject getData();
};

#endif // DEBIANSTORAGEMINING_H


text:
var _ = require("lodash");
var tipe = require("tipe");

module.exports = function( chunk, context, bodies, params ) {

	var direction, scale, attributes;

	// Logic for 'class' option
	if( params.class === undefined ) {
		params.class = "default";
	} else {
		params.class = params.class + "";
	}

	// Logic for 'style' option
	if( params.style === undefined ) {
		params.style = "scruffy";
	}

	switch( params.style ) {

		case "plain":
		case "boring":
			break;

		default:
			params.style = "scruffy";

	}

	// Logic for 'dir' (or 'direction') option
	if( params.direction !== undefined ) {
		direction = params.direction;
	} else if( params.dir !== undefined ) {
		direction = params.dir;
	} else {
		direction = "AUTO";
	}
	direction = direction.toUpperCase();
	switch( direction ) {

		case "RL":
		case "LR":
		case "TB":
		case "BT":
			break;

		default:
			direction = "AUTO";
			break;

	}

	// Logic for 'scale' option
	if( params.scale !== undefined ) {
		scale = params.scale;
	} else {
		scale = 100;
	}
	scale = parseDiagramScale( scale );

	// Put direction and scale together
	attributes = "";
	if( direction !== "AUTO" ) {
		attributes += ";dir:" + direction;
	}
	attributes += ";scale:" + scale;

	// Return the chunk to prevent HTML sanitization
	return chunk.tap(function(data) {

		// Return
		return "

";

	}).render(bodies.block, context).untap();

};

// Standardizes the "scale" option
function parseDiagramScale( scale ) {

	// Handle strings
	if( tipe( scale ) === "string" ) {

		switch( scale.toLowerCase() ) {

			case "huge":
				scale = 180;
				break;

			case "big":
				scale = 150;
				break;

			case "default":
			case "normal":
				scale = 100;
				break;

			case "small":
				scale = 75;
				break;

			case "tiny":
				scale = 50;
				break;

			default:
				scale = parseInt( scale, 10 );
				break;

		}

	} else if( tipe( scale ) !== "number" ) {

		// Only strings or numbers are valid..
		scale = 100;

	}

	// Catch bad numbers
	if( _.isNaN( scale ) ) {
		scale = 100;
	}

	// Round the number to 5s
	scale = Math.round( scale / 5 ) * 5;

	// Clamp between 20 and 200
	scale = _.clamp( scale, 20, 200 );

	// All done
	return scale;

}


text:
#pragma once
#ifndef PYTHON_PROPERTY_HPP
#define PYTHON_PROPERTY_HPP

#include "core_reflection/interfaces/i_base_property.hpp"

namespace wgt
{
class IComponentContext;
namespace PyScript
{
	class ScriptObject;
} // namespace PyScript

namespace ReflectedPython
{

/**
 *	Python-specific property that belongs to a Definition.
 */
class Property : public IBaseProperty
{
public:
	/**
	 *	Construct a property given the attribute name and value.
	 *
	 *	@param key name of the attribute. The property will copy the string
	 *		to its own storage.
	 *	@param attribute value of the attribute. Keeps a reference.
	 */
	Property( IComponentContext & context,
		const char * key,
		const PyScript::ScriptObject & pythonObject );

	Property( IComponentContext & context,
		const char * key,
		const TypeId & typeId,
		const PyScript::ScriptObject & pythonObject );

	const TypeId & getType() const override;

	const char * getName() const override;

	uint64_t getNameHash() const override;

	MetaHandle getMetaData() const override;

	bool readOnly() const override;

	bool isMethod() const override;
	bool isValue() const override;

	bool set( const ObjectHandle & handle,
		const Variant & value,
		const IDefinitionManager & definitionManager ) const override;

	Variant get( const ObjectHandle & handle,
		const IDefinitionManager & definitionManager ) const override;

	Variant invoke( const ObjectHandle& object,
		const IDefinitionManager & definitionManager,
		const ReflectedMethodParameters& parameters ) override;

	size_t parameterCount() const override;

private:
	class Implementation;
	std::unique_ptr< Implementation > impl_;
};

} // namespace ReflectedPython
} // end namespace wgt
#endif // PYTHON_PROPERTY_HPP


text:
module.exports = {run: run, tc: tc};

/*
 * Drive a generator, which may toss async ops like generators, promises,
 * thunks to us via `yield`, which we get by calling `genObj.next()`.  We
 * resolve the async request and bounce the result back via the next
 * `genObj.next(res)`, which is received by `genObj` as the result of the
 * `yield`.
 */

function run(gen, cb) {
    if (!isGenerator(gen)) throw new TypeError("Not a generator object");
    return (typeof cb === 'function') ? _run(x => cb(null, x), cb) : new Promise(_run);

    function _run(resolve, reject) {
        const genstack = [gen];
        return step();

        function step(res) {
            while (true) {
                const g = genstack[genstack.length - 1];
                try {
                    const {value, done} = res instanceof Error ? g.throw(res) : g.next(res);
                    if (done) {
                        genstack.pop();
                        if (isTailCall(value)) {
                            genstack.push(value._gentrify_tc);
                            res = undefined;
                            continue;
                        }
                        if (genstack.length === 0) return resolve(value);
                        res = value;
                    } else if (isGenerator(value)) {
                        res = undefined;
                        genstack.push(value);
                    } else if (isPromise(value)) {
                        return value.then(x => step(x),
                            x => step(x instanceof Error ? x : new Error(x)));
                    } else if (typeof value === 'function') { /* thunk */
                        return value((e, r) => step(e ? (e instanceof Error ?
                            e : new Error(e)) : r));
                    } else {
                        throw new TypeError("Unsupported type yielded");
                    }
                } catch (e) {
                    genstack.pop();
                    if (genstack.length === 0) return reject(e);
                    res = e;
                }
            }
        }
    }
}

/*
 * Wrap generator to signal to the trampoline that this is a tail call
 */

function tc(g) {
    if (!isGenerator(g)) throw new Error("Only generators can be returned in tail calls");
    return {_gentrify_tc: g};
}

function isGenerator(g) {
    return g && typeof g.next === 'function' && typeof g.throw === 'function';
}

function isPromise(p) {
    return p && typeof p.then === 'function';
}

function isTailCall(v) {
    return v && isGenerator(v._gentrify_tc);
}


text:
<?php

namespace CmsLayout\Exception;

/**
 * Invalid argument exception for CmsLayout
 */
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>src\components\menu\Menu.js - Firebrick UI API</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 0.20.22

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

components.button.Button

components.button.ButtonGroup

components.button.components.common.mixins.Items

components.button.components.common.MultiplesBase

components.button.components.menu.Menu

components.common.components.fields.Input

components.common.mixins.components.button.ButtonGroupBase

components.common.mixins.components.button.ToggleButton

components.common.mixins.components.common.Base

components.common.mixins.components.containers.Base

components.common.mixins.components.nav.Toolbar

components.common.view.Base

components.containers.border.Pane

components.containers.border.plugins.Draggable

components.containers.BorderLayout

components.containers.components.common.mixins.Column

components.containers.components.common.mixins.Toolbars

components.containers.components.fields.Base

components.containers.Fieldset

components.containers.Form

components.containers.FormPanel

components.containers.GridColumn

components.containers.GridRow

components.containers.Panel

components.containers.tab.components.containers.Modal

components.containers.tab.Pane

components.display.Alert

components.display.components.containers.TabPanel

components.display.components.nav.Base

components.display.Divider

components.display.Header

components.display.Image

components.display.Loader

components.display.Progress

components.display.Span

components.fields.Checkbox

components.fields.ComboBox

components.fields.components.button.Icon

components.fields.components.display.Text

components.fields.Datepicker

components.fields.Display

components.fields.Email

components.fields.File

components.fields.Hidden

components.fields.HtmlEditor

components.fields.Password

components.fields.plugins.InplaceEdit

components.fields.Radio

components.fields.Suggest

components.fields.TextArea

components.menu.components.common.mixins.Badges

components.menu.components.fields.SelectBox

components.menu.Item

components.nav.Breadcrumbs

components.nav.components.common.mixins.Label

components.nav.components.display.List

components.nav.components.menu.ContextMenu

components.nav.List

components.nav.Navbar

components.table.plugins.EditableTable

components.table.Table

components.table.TreeTable

helper

KeyEvents

plugins.components.containers.Accordion

plugins.components.containers.Box

plugins.components.nav.Pagination

renderer

ui

utils

view.Base

Firebrick.engine

Firebrick.ui

Firebrick.ui.components

plugins

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: src\components\menu\Menu.js

/*!
 * @author Steven Masala [me@smasala.com]
 */

/**
 * @private
 * @module Firebrick.ui.components
 * @extends components.common.Base
 * @namespace components.menu
 * @class Menu
 */
define( [ "text!./Menu.html", "../common/Base", "../common/mixins/Items", "./Item" ], function( tpl ) {
	"use strict";

	return Firebrick.define( "Firebrick.ui.menu.Menu", {
	    extend: "Firebrick.ui.common.Base",
	    mixins: "Firebrick.ui.common.mixins.Items",
	    /**
	     * @property sName
	     * @type {String}
	     * @default "menu.list",
	     */
	    sName: "menu.menu",
	    /**
	     * @property tpl
	     */
	    tpl: tpl,
	    /**
	     * @property defaults
	     * @type {object}
	     * @default {
	     * 		sName: "menu.item"
	     * }
	     */
	    defaults: {
		    sName: "menu.item"
	    },
	    /**
	     * @property ariaLabelledBy
	     * @type {String}
	     * @default ""
	     */
	    ariaLabelledBy: "",
	    /**
	     * @method init
	     */
	    init: function() {
		    var me = this;

		    me._prepItems();

		    return me.callParent( arguments );
	    },
	    /**
	     * @method _prepItems
	     * @private
	     */
	    _prepItems: function() {
		    var me = this, it, items = me.items;

		    for ( var i = 0, l = items.length; i < l; i++ ) {
			    it = items[ i ];
			    if ( it === "|" ) {
				    it = {
					    divider: true
				    };
			    } else if ( it.sName && it.sName !== "menu.item" ) {
				    it = {
					    items: [ items[ i ] ]
				    };
			    }

			    items[ i ] = it;
		    }
	    },
	    /**
	     * @method bindings
	     * @return {Object}
	     */
	    bindings: function() {
		    var me = this, obj = me.callParent( arguments );
		    obj.css = {
			    "'dropdown-menu'": true
		    };
		    if ( !obj.attr ) {
			    obj.attr = {};
		    }
		    obj.attr.role = "'menu'";
		    obj.attr[ "'aria-labelledby'" ] = me.parseBind( me.ariaLabelledBy );

		    return obj;
	    }
	} );
} );


text:
from django.contrib.auth import get_user_model, authenticate
from django.conf import settings
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.contrib.auth.tokens import default_token_generator
from django.utils.http import urlsafe_base64_decode as uid_decoder
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_text

from rest_framework import serializers, exceptions
from rest_framework.exceptions import ValidationError

from .models import TokenModel
from .utils import import_callable

# Get the UserModel
UserModel = get_user_model()

class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(required=False, allow_blank=True)
    email = serializers.EmailField(required=False, allow_blank=True)
    password = serializers.CharField(style={'input_type': 'password'})

    def _validate_email(self, email, password):
        user = None

        if email and password:
            user = authenticate(email=email, password=password)
        else:
            msg = _('Must include "email" and "password".')
            raise exceptions.ValidationError(msg)

        return user

    def _validate_username(self, username, password):
        user = None

        if username and password:
            user = authenticate(username=username, password=password)
        else:
            msg = _('Must include "username" and "password".')
            raise exceptions.ValidationError(msg)

        return user

    def _validate_username_email(self, username, email, password):
        user = None

        if email and password:
            user = authenticate(email=email, password=password)
        elif username and password:
            user = authenticate(username=username, password=password)
        else:
            msg = _('Must include either "username" or "email" and "password".')
            raise exceptions.ValidationError(msg)

        return user

    def validate(self, attrs):
        username = attrs.get('username')
        email = attrs.get('email')
        password = attrs.get('password')

        user = None

        if 'allauth' in settings.INSTALLED_APPS:
            from allauth.account import app_settings

            # Authentication through email
            if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL:
                user = self._validate_email(email, password)

            # Authentication through username
            if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.USERNAME:
                user = self._validate_username(username, password)

            # Authentication through either username or email
            else:
                user = self._validate_username_email(username, email, password)

        else:
            # Authentication without using allauth
            if email:
                try:
                    username = UserModel.objects.get(email__iexact=email).get_username()
                except UserModel.DoesNotExist:
                    pass

            if username:
                user = self._validate_username_email(username, '', password)

        # Did we get back an active user?
        if user:
            if not user.is_active:
                msg = _('User account is disabled.')
                raise exceptions.ValidationError(msg)
        else:
            msg = _('Unable to log in with provided credentials.')
            raise exceptions.ValidationError(msg)

        # If required, is the email verified?
        if 'rest_auth.registration' in settings.INSTALLED_APPS:
            from allauth.account import app_settings
            if app_settings.EMAIL_VERIFICATION == app_settings.EmailVerificationMethod.MANDATORY:
                email_address = user.emailaddress_set.get(email=user.email)
                if not email_address.verified:
                    raise serializers.ValidationError(_('E-mail is not verified.'))

        attrs['user'] = user
        return attrs

class TokenSerializer(serializers.ModelSerializer):
    """
    Serializer for Token model.
    """

    class Meta:
        model = TokenModel
        fields = ('key',)

class UserDetailsSerializer(serializers.ModelSerializer):
    """
    User model w/o password
    """
    class Meta:
        model = UserModel
        fields = ('pk', 'username', 'email', 'first_name', 'last_name')
        read_only_fields = ('email', )

class JWTSerializer(serializers.Serializer):
    """
    Serializer for JWT authentication.
    """
    token = serializers.CharField()
    user = serializers.SerializerMethodField()

    def get_user(self, obj):
        """
        Required to allow using custom USER_DETAILS_SERIALIZER in
        JWTSerializer. Defining it here to avoid circular imports
        """
        rest_auth_serializers = getattr(settings, 'REST_AUTH_SERIALIZERS', {})
        JWTUserDetailsSerializer = import_callable(
            rest_auth_serializers.get('USER_DETAILS_SERIALIZER', UserDetailsSerializer)
        )
        user_data = JWTUserDetailsSerializer(obj['user']).data
        return user_data

class PasswordResetSerializer(serializers.Serializer):
    """
    Serializer for requesting a password reset e-mail.
    """
    email = serializers.EmailField()

    password_reset_form_class = PasswordResetForm

    def get_email_options(self):
        """Override this method to change default e-mail options"""
        return {}

    def validate_email(self, value):
        # Create PasswordResetForm with the serializer
        self.reset_form = self.password_reset_form_class(data=self.initial_data)
        if not self.reset_form.is_valid():
            raise serializers.ValidationError(self.reset_form.errors)

        return value

    def save(self):
        request = self.context.get('request')
        # Set some values to trigger the send_email method.
        opts = {
            'use_https': request.is_secure(),
            'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
            'request': request,
        }

        opts.update(self.get_email_options())
        self.reset_form.save(**opts)

class PasswordResetConfirmSerializer(serializers.Serializer):
    """
    Serializer for requesting a password reset e-mail.
    """
    new_password1 = serializers.CharField(max_length=128)
    new_password2 = serializers.CharField(max_length=128)
    uid = serializers.CharField()
    token = serializers.CharField()

    set_password_form_class = SetPasswordForm

    def custom_validation(self, attrs):
        pass

    def validate(self, attrs):
        self._errors = {}

        # Decode the uidb64 to uid to get User object
        try:
            uid = force_text(uid_decoder(attrs['uid']))
            self.user = UserModel._default_manager.get(pk=uid)
        except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
            raise ValidationError({'uid': ['Invalid value']})

        self.custom_validation(attrs)
        # Construct SetPasswordForm instance
        self.set_password_form = self.set_password_form_class(
            user=self.user, data=attrs
        )
        if not self.set_password_form.is_valid():
            raise serializers.ValidationError(self.set_password_form.errors)
        if not default_token_generator.check_token(self.user, attrs['token']):
            raise ValidationError({'token': ['Invalid value']})

        return attrs

    def save(self):
        self.set_password_form.save()

class PasswordChangeSerializer(serializers.Serializer):
    old_password = serializers.CharField(max_length=128)
    new_password1 = serializers.CharField(max_length=128)
    new_password2 = serializers.CharField(max_length=128)

    set_password_form_class = SetPasswordForm

    def __init__(self, *args, **kwargs):
        self.old_password_field_enabled = getattr(
            settings, 'OLD_PASSWORD_FIELD_ENABLED', False
        )
        self.logout_on_password_change = getattr(
            settings, 'LOGOUT_ON_PASSWORD_CHANGE', False
        )
        super(PasswordChangeSerializer, self).__init__(*args, **kwargs)

        if not self.old_password_field_enabled:
            self.fields.pop('old_password')

        self.request = self.context.get('request')
        self.user = getattr(self.request, 'user', None)

    def validate_old_password(self, value):
        invalid_password_conditions = (
            self.old_password_field_enabled,
            self.user,
            not self.user.check_password(value)
        )

        if all(invalid_password_conditions):
            raise serializers.ValidationError('Invalid password')
        return value

    def validate(self, attrs):
        self.set_password_form = self.set_password_form_class(
            user=self.user, data=attrs
        )

        if not self.set_password_form.is_valid():
            raise serializers.ValidationError(self.set_password_form.errors)
        return attrs

    def save(self):
        self.set_password_form.save()
        if not self.logout_on_password_change:
            from django.contrib.auth import update_session_auth_hash
            update_session_auth_hash(self.request, self.user)


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2009 CTTC
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Include., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Authors: Nicola Baldo <nbaldo@cttc.es>
 *          Sébastien Deronne <sebastien.deronne@gmail.com>
 */

#include <iomanip>
#include <cmath>
#include "ns3/log.h"
#include "radiotap-header.h"

namespace ns3 {

NS_LOG_COMPONENT_DEFINE ("RadiotapHeader");

NS_OBJECT_ENSURE_REGISTERED (RadiotapHeader);

RadiotapHeader::RadiotapHeader ()
  : m_length (8),
    m_present (0),
    m_tsft (0),
    m_flags (FRAME_FLAG_NONE),
    m_rate (0),
    m_channelFreq (0),
    m_channelFlags (CHANNEL_FLAG_NONE),
    m_antennaSignal (0),
    m_antennaNoise (0),
    m_ampduStatusRef (0),
    m_ampduStatusFlags (0),
    m_ampduStatusCRC (0),
    m_vhtPad (0),
    m_vhtKnown (0),
    m_vhtFlags (0),
    m_vhtBandwidth (0),
    m_vhtCoding (0),
    m_vhtGroupId (0),
    m_vhtPartialAid (0)
{
  NS_LOG_FUNCTION (this);
}

TypeId RadiotapHeader::GetTypeId (void)
{
  static TypeId tid = TypeId ("ns3::RadiotapHeader")
    .SetParent<Header> ()
    .SetGroupName ("Network")

    .AddConstructor<RadiotapHeader> ()
  ;
  return tid;
}

TypeId
RadiotapHeader::GetInstanceTypeId (void) const
{
  return GetTypeId ();
}

uint32_t
RadiotapHeader::GetSerializedSize (void) const
{
  NS_LOG_FUNCTION (this);
  return m_length;
}

void
RadiotapHeader::Serialize (Buffer::Iterator start) const
{
  NS_LOG_FUNCTION (this << &start);

  start.WriteU8 (0); // major version of radiotap header
  start.WriteU8 (0); // pad field
  start.WriteU16 (m_length); // entire length of radiotap data + header
  start.WriteU32 (m_present); // bits describing which fields follow header

  //
  // Time Synchronization Function Timer (when the first bit of the MPDU
  // arrived at the MAC)
  //
  if (m_present & RADIOTAP_TSFT) // bit 0
    {
      start.WriteU64 (m_tsft);
    }

  //
  // Properties of transmitted and received frames.
  //
  if (m_present & RADIOTAP_FLAGS) // bit 1
    {
      start.WriteU8 (m_flags);
    }

  //
  // TX/RX data rate in units of 500 kbps
  //
  if (m_present & RADIOTAP_RATE) // bit 2
    {
      start.WriteU8 (m_rate);
    }

  //
  // Tx/Rx frequency in MHz, followed by flags.
  //
  if (m_present & RADIOTAP_CHANNEL) // bit 3
    {
      start.WriteU8 (0, m_channelPad);
      start.WriteU16 (m_channelFreq);
      start.WriteU16 (m_channelFlags);
    }

  //
  // The hop set and pattern for frequency-hopping radios.  We don't need it but
  // still need to account for it.
  //
  if (m_present & RADIOTAP_FHSS) // bit 4
    {
      start.WriteU8 (0); //not yet implemented
    }

  //
  // RF signal power at the antenna, decibel difference from an arbitrary, fixed
  // reference.
  //
  if (m_present & RADIOTAP_DBM_ANTSIGNAL) // bit 5
    {
      start.WriteU8 (m_antennaSignal);
    }

  //
  // RF noise power at the antenna, decibel difference from an arbitrary, fixed
  // reference.
  //
  if (m_present & RADIOTAP_DBM_ANTNOISE) // bit 6
    {
      start.WriteU8 (m_antennaNoise);
    }

  //
  // Quality of Barker code lock.
  //
  if (m_present & RADIOTAP_LOCK_QUALITY) // bit 7
    {
      start.WriteU16 (0); //not yet implemented
    }

  //
  // Transmit power expressed as unitless distance from max power
  // set at factory calibration (0 is max power).
  //
  if (m_present & RADIOTAP_TX_ATTENUATION) // bit 8
    {
      start.WriteU16 (0); //not yet implemented
    }

  //
  // Transmit power expressed as decibel distance from max power
  // set at factory calibration (0 is max power).
  //
  if (m_present & RADIOTAP_DB_TX_ATTENUATION) // bit 9
    {
      start.WriteU16 (0); //not yet implemented
    }

  //
  // Transmit power expressed as dBm (decibels from a 1 milliwatt reference).
  // This is the absolute power level measured at the antenna port.
  //
  if (m_present & RADIOTAP_DBM_TX_POWER) // bit 10
    {
      start.WriteU8 (0); //not yet implemented
    }

  //
  // Unitless indication of the Rx/Tx antenna for this packet.
  // The first antenna is antenna 0.
  //
  if (m_present & RADIOTAP_ANTENNA) // bit 11
    {
      start.WriteU8 (0); //not yet implemented
    }

  //
  // RF signal power at the antenna (decibel difference from an arbitrary fixed reference).
  //
  if (m_present & RADIOTAP_DB_ANTSIGNAL) // bit 12
    {
      start.WriteU8 (0); //not yet implemented
    }

  //
  // RF noise power at the antenna (decibel difference from an arbitrary fixed reference).
  //
  if (m_present & RADIOTAP_DB_ANTNOISE) // bit 13
    {
      start.WriteU8 (0); //not yet implemented
    }

  //
  // Properties of received frames.
  //
  if (m_present & RADIOTAP_RX_FLAGS) // bit 14
    {
      start.WriteU16 (0); //not yet implemented
    }

  //
  // MCS field.
  //
  if (m_present & RADIOTAP_MCS) // bit 19
    {
      start.WriteU8 (m_mcsKnown);
      start.WriteU8 (m_mcsFlags);
      start.WriteU8 (m_mcsRate);
    }

  //
  // A-MPDU Status, information about the received or transmitted A-MPDU.
  //
  if (m_present & RADIOTAP_AMPDU_STATUS) // bit 20
    {
      start.WriteU8 (0, m_ampduStatusPad);
      start.WriteU32 (m_ampduStatusRef);
      start.WriteU16 (m_ampduStatusFlags);
      start.WriteU8 (m_ampduStatusCRC);
      start.WriteU8 (0);
    }

  //
  // Information about the received or transmitted VHT frame.
  //
  if (m_present & RADIOTAP_VHT) // bit 21
    {
      start.WriteU8 (0, m_vhtPad);
      start.WriteU16 (m_vhtKnown);
      start.WriteU8 (m_vhtFlags);
      start.WriteU8 (m_vhtBandwidth);
      for (uint8_t i = 0; i < 4; i++)
        {
          start.WriteU8 (m_vhtMcsNss[i]);
        }
      start.WriteU8 (m_vhtCoding);
      start.WriteU8 (m_vhtGroupId);
      start.WriteU16 (m_vhtPartialAid);
    }
}

uint32_t
RadiotapHeader::Deserialize (Buffer::Iterator start)
{
  NS_LOG_FUNCTION (this << &start);

  uint8_t tmp = start.ReadU8 (); // major version of radiotap header
  NS_ASSERT_MSG (tmp == 0x00, "RadiotapHeader::Deserialize(): Unexpected major version");
  start.ReadU8 (); // pad field

  m_length = start.ReadU16 (); // entire length of radiotap data + header
  m_present = start.ReadU32 (); // bits describing which fields follow header

  uint32_t bytesRead = 8;

  //
  // Time Synchronization Function Timer (when the first bit of the MPDU arrived at the MAC)
  //
  if (m_present & RADIOTAP_TSFT) // bit 0
    {
      m_tsft = start.ReadU64 ();
      bytesRead += 8;
    }

  //
  // Properties of transmitted and received frames.
  //
  if (m_present & RADIOTAP_FLAGS) // bit 1
    {
      m_flags = start.ReadU8 ();
      ++bytesRead;
    }

  //
  // TX/RX data rate in units of 500 kbps
  //
  if (m_present & RADIOTAP_RATE) // bit 2
    {
      m_rate = start.ReadU8 ();
      ++bytesRead;
    }

  //
  // Tx/Rx frequency in MHz, followed by flags.
  //
  if (m_present & RADIOTAP_CHANNEL) // bit 3
    {
      m_channelPad = ((2 - bytesRead % 2) % 2);
      start.Next (m_channelPad);
      m_channelFreq = start.ReadU16 ();
      m_channelFlags = start.ReadU16 ();
      bytesRead += (4 + m_channelPad);
    }

  //
  // The hop set and pattern for frequency-hopping radios.  We don't need it but
  // still need to account for it.
  //
  if (m_present & RADIOTAP_FHSS) // bit 4
    {
      //not yet implemented
      start.ReadU8 ();
      ++bytesRead;
    }

  //
  // RF signal power at the antenna, decibel difference from an arbitrary, fixed
  // reference.
  //
  if (m_present & RADIOTAP_DBM_ANTSIGNAL) // bit 5
    {
      m_antennaSignal = start.ReadU8 ();
      ++bytesRead;
    }

  //
  // RF noise power at the antenna, decibel difference from an arbitrary, fixed
  // reference.
  //
  if (m_present & RADIOTAP_DBM_ANTNOISE) // bit 6
    {
      m_antennaNoise = start.ReadU8 ();
      ++bytesRead;
    }

  //
  // Quality of Barker code lock.
  //
  if (m_present & RADIOTAP_LOCK_QUALITY) // bit 7
    {
      //not yet implemented
      start.ReadU16 ();
      bytesRead += 2;
    }

  //
  // Transmit power expressed as unitless distance from max power
  // set at factory calibration (0 is max power).
  //
  if (m_present & RADIOTAP_TX_ATTENUATION) // bit 8
    {
      //not yet implemented
      start.ReadU16 ();
      bytesRead += 2;
    }

  //
  // Transmit power expressed as decibel distance from max power
  // set at factory calibration (0 is max power).
  //
  if (m_present & RADIOTAP_DB_TX_ATTENUATION) // bit 9
    {
      //not yet implemented
      start.ReadU16 ();
      bytesRead += 2;
    }

  //
  // Transmit power expressed as dBm (decibels from a 1 milliwatt reference).
  // This is the absolute power level measured at the antenna port.
  //
  if (m_present & RADIOTAP_DBM_TX_POWER) // bit 10
    {
      //not yet implemented
      start.ReadU8 ();
      ++bytesRead;
    }

  //
  // Unitless indication of the Rx/Tx antenna for this packet.
  // The first antenna is antenna 0.
  //
  if (m_present & RADIOTAP_ANTENNA) // bit 11
    {
      //not yet implemented
      start.ReadU8 ();
      ++bytesRead;
    }

  //
  // RF signal power at the antenna (decibel difference from an arbitrary fixed reference).
  //
  if (m_present & RADIOTAP_DB_ANTSIGNAL) // bit 12
    {
      //not yet implemented
      start.ReadU8 ();
      ++bytesRead;
    }

  //
  // RF noise power at the antenna (decibel difference from an arbitrary fixed reference).
  //
  if (m_present & RADIOTAP_DB_ANTNOISE) // bit 13
    {
      //not yet implemented
      start.ReadU8 ();
      ++bytesRead;
    }

  //
  // Properties of received frames.
  //
  if (m_present & RADIOTAP_RX_FLAGS) // bit 14
    {
      //not yet implemented
      start.ReadU16 ();
      bytesRead += 2;
    }

  //
  // MCS field.
  //
  if (m_present & RADIOTAP_MCS) // bit 19
    {
      m_mcsKnown = start.ReadU8 ();
      m_mcsFlags = start.ReadU8 ();
      m_mcsRate = start.ReadU8 ();
      bytesRead += 3;
    }

  //
  // A-MPDU Status, information about the received or transmitted A-MPDU.
  //
  if (m_present & RADIOTAP_AMPDU_STATUS) // bit 20
    {
      m_ampduStatusPad = ((4 - bytesRead % 4) % 4);
      start.Next (m_ampduStatusPad);
      m_ampduStatusRef = start.ReadU32 ();
      m_ampduStatusFlags = start.ReadU16 ();
      m_ampduStatusCRC = start.ReadU8 ();
      start.ReadU8 ();
      bytesRead += (8 + m_ampduStatusPad);
    }

  //
  // Information about the received or transmitted VHT frame.
  //
  if (m_present & RADIOTAP_VHT) // bit 21
    {
      m_vhtPad = ((2 - bytesRead % 2) % 2);
      start.Next (m_vhtPad);
      m_vhtKnown = start.ReadU16 ();
      m_vhtFlags = start.ReadU8 ();
      m_vhtBandwidth = start.ReadU8 ();
      for (uint8_t i = 0; i < 4; i++)
        {
          m_vhtMcsNss[i] = start.ReadU8 ();
        }
      m_vhtCoding = start.ReadU8 ();
      m_vhtGroupId = start.ReadU8 ();
      m_vhtPartialAid = start.ReadU16 ();
      bytesRead += (12 + m_vhtPad);
    }

  NS_ASSERT_MSG (m_length == bytesRead, "RadiotapHeader::Deserialize(): expected and actual lengths inconsistent");
  return bytesRead;
}

void
RadiotapHeader::Print (std::ostream &os) const
{
  NS_LOG_FUNCTION (this << &os);
  os << " tsft=" << m_tsft
     << " flags=" << std::hex << m_flags << std::dec
     << " rate=" << (uint16_t) m_rate
     << " freq=" << m_channelFreq
     << " chflags=" << std::hex << (uint32_t)m_channelFlags << std::dec
     << " signal=" << (int16_t) m_antennaSignal
     << " noise=" << (int16_t) m_antennaNoise
     << " mcsKnown=" << m_mcsKnown
     << " mcsFlags=" << m_mcsFlags
     << " mcsRate=" << m_mcsRate
     << " ampduStatusFlags=" << (int16_t) m_ampduStatusFlags
     << " vhtKnown=" << m_vhtKnown
     << " vhtFlags=" << m_vhtFlags
     << " vhtBandwidth=" << m_vhtBandwidth
     << " vhtMcsNss for user 1=" << m_vhtMcsNss[0]
     << " vhtMcsNss for user 2=" << m_vhtMcsNss[1]
     << " vhtMcsNss for user 3=" << m_vhtMcsNss[2]
     << " vhtMcsNss for user 4=" << m_vhtMcsNss[3]
     << " vhtCoding=" << m_vhtCoding
     << " vhtGroupId=" << m_vhtGroupId
     << " vhtPartialAid=" << m_vhtPartialAid;
}

void
RadiotapHeader::SetTsft (uint64_t value)
{
  NS_LOG_FUNCTION (this << value);
  m_tsft = value;

  if (!(m_present & RADIOTAP_TSFT))
    {
      m_present |= RADIOTAP_TSFT;
      m_length += 8;
    }

  NS_LOG_LOGIC (this << " m_length=" << m_length << " m_present=0x" << std::hex << m_present << std::dec);
}

uint64_t
RadiotapHeader::GetTsft () const
{
  NS_LOG_FUNCTION (this);
  return m_tsft;
}

void
RadiotapHeader::SetFrameFlags (uint8_t flags)
{
  NS_LOG_FUNCTION (this << static_cast<uint32_t> (flags));
  m_flags = flags;

  if (!(m_present & RADIOTAP_FLAGS))
    {
      m_present |= RADIOTAP_FLAGS;
      m_length += 1;
    }

  NS_LOG_LOGIC (this << " m_length=" << m_length << " m_present=0x" << std::hex << m_present << std::dec);
}

uint8_t
RadiotapHeader::GetFrameFlags (void) const
{
  NS_LOG_FUNCTION (this);
  return m_flags;
}

void
RadiotapHeader::SetRate (uint8_t rate)
{
  NS_LOG_FUNCTION (this << static_cast<uint32_t> (rate));
  m_rate = rate;

  if (!(m_present & RADIOTAP_RATE))
    {
      m_present |= RADIOTAP_RATE;
      m_length += 1;
    }

  NS_LOG_LOGIC (this << " m_length=" << m_length << " m_present=0x" << std::hex << m_present << std::dec);
}

uint8_t
RadiotapHeader::GetRate (void) const
{
  NS_LOG_FUNCTION (this);
  return m_rate;
}

void
RadiotapHeader::SetChannelFrequencyAndFlags (uint16_t frequency, uint16_t flags)
{
  NS_LOG_FUNCTION (this << frequency << flags);
  m_channelFreq = frequency;
  m_channelFlags = flags;

  if (!(m_present & RADIOTAP_CHANNEL))
    {
      m_channelPad = ((2 - m_length % 2) % 2);
      m_present |= RADIOTAP_CHANNEL;
      m_length += (4 + m_channelPad);
    }

  NS_LOG_LOGIC (this << " m_length=" << m_length << " m_present=0x" << std::hex << m_present << std::dec);
}

uint16_t
RadiotapHeader::GetChannelFrequency (void) const
{
  NS_LOG_FUNCTION (this);
  return m_channelFreq;
}

uint16_t
RadiotapHeader::GetChannelFlags (void) const
{
  NS_LOG_FUNCTION (this);
  return m_channelFlags;
}

void
RadiotapHeader::SetAntennaSignalPower (double signal)
{
  NS_LOG_FUNCTION (this << signal);

  if (!(m_present & RADIOTAP_DBM_ANTSIGNAL))
    {
      m_present |= RADIOTAP_DBM_ANTSIGNAL;
      m_length += 1;
    }
  if (signal > 127)
    {
      m_antennaSignal = 127;
    }
  else if (signal < -128)
    {
      m_antennaSignal = -128;
    }
  else
    {
      m_antennaSignal = static_cast<int8_t> (floor (signal + 0.5));
    }

  NS_LOG_LOGIC (this << " m_length=" << m_length << " m_present=0x" << std::hex << m_present << std::dec);
}

uint8_t
RadiotapHeader::GetAntennaSignalPower (void) const
{
  NS_LOG_FUNCTION (this);
  return m_antennaSignal;
}

void
RadiotapHeader::SetAntennaNoisePower (double noise)
{
  NS_LOG_FUNCTION (this << noise);

  if (!(m_present & RADIOTAP_DBM_ANTNOISE))
    {
      m_present |= RADIOTAP_DBM_ANTNOISE;
      m_length += 1;
    }
  if (noise > 127.0)
    {
      m_antennaNoise = 127;
    }
  else if (noise < -128.0)
    {
      m_antennaNoise = -128;
    }
  else
    {
      m_antennaNoise = static_cast<int8_t> (floor (noise + 0.5));
    }

  NS_LOG_LOGIC (this << " m_length=" << m_length << " m_present=0x" << std::hex << m_present << std::dec);
}

uint8_t
RadiotapHeader::GetAntennaNoisePower (void) const
{
  NS_LOG_FUNCTION (this);
  return m_antennaNoise;
}

void
RadiotapHeader::SetMcsFields (uint8_t known, uint8_t flags, uint8_t mcs)
{
  NS_LOG_FUNCTION (this << known << flags << mcs);
  m_mcsKnown = known;
  m_mcsFlags = flags;
  m_mcsRate = mcs;
  if (!(m_present & RADIOTAP_MCS))
    {
      m_present |= RADIOTAP_MCS;
      m_length += 3;
    }

  NS_LOG_LOGIC (this << " m_length=" << m_length << " m_present=0x" << std::hex << m_present << std::dec);
}

uint8_t
RadiotapHeader::GetMcsKnown () const
{
  NS_LOG_FUNCTION (this);
  return m_mcsKnown;
}

uint8_t
RadiotapHeader::GetMcsFlags () const
{
  NS_LOG_FUNCTION (this);
  return m_mcsFlags;
}

uint8_t
RadiotapHeader::GetMcsRate () const
{
  NS_LOG_FUNCTION (this);
  return m_mcsRate;
}

void
RadiotapHeader::SetAmpduStatus (uint32_t referenceNumber, uint16_t flags, uint8_t crc)
{
  NS_LOG_FUNCTION (this << referenceNumber << flags);
  m_ampduStatusRef = referenceNumber;
  m_ampduStatusFlags = flags;
  m_ampduStatusCRC = crc;
  if (!(m_present & RADIOTAP_AMPDU_STATUS))
    {
      m_ampduStatusPad = ((4 - m_length % 4) % 4);
      m_present |= RADIOTAP_AMPDU_STATUS;
      m_length += (8 + m_ampduStatusPad);
    }

  NS_LOG_LOGIC (this << " m_length=" << m_length << " m_present=0x" << std::hex << m_present << std::dec);
}

uint32_t
RadiotapHeader::GetAmpduStatusRef () const
{
  NS_LOG_FUNCTION (this);
  return m_ampduStatusRef;
}

uint16_t
RadiotapHeader::GetAmpduStatusFlags () const
{
  NS_LOG_FUNCTION (this);
  return m_ampduStatusFlags;
}

void
RadiotapHeader::SetVhtFields (uint16_t known, uint8_t flags, uint8_t bandwidth, uint8_t mcs_nss[4], uint8_t coding, uint8_t group_id, uint16_t partial_aid)
{
  NS_LOG_FUNCTION (this << known << flags << mcs_nss[0] << mcs_nss[1] << mcs_nss[2] << mcs_nss[3] << coding << group_id << partial_aid);
  m_vhtKnown = known;
  m_vhtFlags = flags;
  m_vhtBandwidth = bandwidth;
  for (uint8_t i = 0; i < 4; i++)
    {
      m_vhtMcsNss[i] = mcs_nss[i];
    }
  m_vhtCoding = coding;
  m_vhtGroupId = group_id;
  m_vhtPartialAid = partial_aid;
  if (!(m_present & RADIOTAP_VHT))
    {
      m_vhtPad = ((2 - m_length % 2) % 2);
      m_present |= RADIOTAP_VHT;
      m_length += (12 + m_vhtPad);
    }

  NS_LOG_LOGIC (this << " m_length=" << m_length << " m_present=0x" << std::hex << m_present << std::dec);
}

uint16_t
RadiotapHeader::GetVhtKnown () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtKnown;
}

uint8_t
RadiotapHeader::GetVhtFlags () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtFlags;
}

uint8_t
RadiotapHeader::GetVhtBandwidth () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtBandwidth;
}

uint8_t
RadiotapHeader::GetVhtMcsNssUser1 () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtMcsNss[0];
}

uint8_t
RadiotapHeader::GetVhtMcsNssUser2 () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtMcsNss[1];
}

uint8_t
RadiotapHeader::GetVhtMcsNssUser3 () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtMcsNss[2];
}

uint8_t
RadiotapHeader::GetVhtMcsNssUser4 () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtMcsNss[3];
}

uint8_t
RadiotapHeader::GetVhtCoding () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtCoding;
}

uint8_t
RadiotapHeader::GetVhtGroupId () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtGroupId;
}

uint8_t
RadiotapHeader::GetVhtPartialAid () const
{
  NS_LOG_FUNCTION (this);
  return m_vhtPartialAid;
}

} // namespace ns3


text:
import unittest

from acronym import abbreviate

# Tests adapted from `problem-specifications//canonical-data.json` @ v1.7.0

class AcronymTest(unittest.TestCase):
    def test_basic(self):
        self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG')

    def test_lowercase_words(self):
        self.assertEqual(abbreviate('Ruby on Rails'), 'ROR')

    def test_punctuation(self):
        self.assertEqual(abbreviate('First In, First Out'), 'FIFO')

    def test_all_caps_words(self):
        self.assertEqual(abbreviate('GNU Image Manipulation Program'), 'GIMP')

    def test_punctuation_without_whitespace(self):
        self.assertEqual(
            abbreviate('Complementary metal-oxide semiconductor'), 'CMOS')

    def test_very_long_abbreviation(self):
        self.assertEqual(
            abbreviate("Rolling On The Floor Laughing So Hard That "
                       "My Dogs Came Over And Licked Me"), "ROTFLSHTMDCOALM")

    def test_consecutive_delimiters(self):
        self.assertEqual(
            abbreviate('Something - I made up from thin air'), 'SIMUFTA')

    def test_apostrophes(self):
        self.assertEqual(abbreviate("Halley's Comet"), 'HC')

    def test_underscore_emphasis(self):
        self.assertEqual(abbreviate("The Road _Not_ Taken"), 'TRNT')

if __name__ == '__main__':
    unittest.main()


text:
<?php

/** Zend_Memory */
require_once 'Zend/Memory.php';

/**
 * @category   Zend
 * @package    Zend_Memory
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Memory
 */
class Zend_Memory_Container_LockedTest extends PHPUnit_Framework_TestCase
{
    /**
     * tests the Movable memory container object creation
     */
    public function testCreation()
    {
        $memObject = new Zend_Memory_Container_Locked('0123456789');

        $this->assertTrue($memObject instanceof Zend_Memory_Container_Locked);
    }

    /**
     * tests the value access methods
     */
    public function testValueAccess()
    {
        $memObject = new Zend_Memory_Container_Locked('0123456789');

        // getRef() method
        $this->assertEquals($memObject->getRef(), '0123456789');

        $valueRef = &$memObject->getRef();
        $valueRef[3] = '_';
        $this->assertEquals($memObject->getRef(), '012_456789');

        // value property
        $this->assertEquals((string)$memObject->value, '012_456789');

        $memObject->value[7] = '_';
        $this->assertEquals((string)$memObject->value, '012_456_89');

        $memObject->value = 'another value';
        $this->assertEquals((string)$memObject->value, 'another value');
    }

    /**
     * tests lock()/unlock()/isLocked() functions
     */
    public function testLock()
    {
        $memObject = new Zend_Memory_Container_Locked('0123456789');

        // It's always locked
        $this->assertTrue((boolean)$memObject->isLocked());

        $memObject->lock();
        $this->assertTrue((boolean)$memObject->isLocked());

        $memObject->unlock();
        // It's always locked
        $this->assertTrue((boolean)$memObject->isLocked());
    }

    /**
     * tests the touch() method
     */
    public function testTouch()
    {
        $memObject = new Zend_Memory_Container_Locked('0123456789');

        $memObject->touch();

        // Nothing to check
    }
}


text:
package log

import (
	"os"
)

var console = NewLogger(os.Stderr)

func init() {
	console.isConsole = true
	console.SetLayouts(defaultLayout)
}


text:
package org.cf.smalivm.opcode;

import org.cf.smalivm.context.ExecutionNode;
import org.cf.smalivm.context.HeapItem;
import org.cf.smalivm.context.MethodState;
import org.cf.util.Utils;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.formats.Instruction12x;

public class UnaryMathOp extends MethodStateOp {

    private static String getResultTypeName(String opName) {
        String[] parts = opName.split("-");
        String type = parts[parts.length - 1];
        String resultType = null;
        if ("int".equals(type)) {
            resultType = "I";
        } else if ("long".equals(type)) {
            resultType = "J";
        } else if ("float".equals(type)) {
            resultType = "F";
        } else if ("byte".equals(type)) {
            resultType = "B";
        } else if ("char".equals(type)) {
            resultType = "C";
        } else if ("double".equals(type)) {
            resultType = "D";
        } else if ("short".equals(type)) {
            resultType = "S";
        }

        return resultType;
    }

    static UnaryMathOp create(Instruction instruction, int address) {
        String opName = instruction.getOpcode().name;
        int childAddress = address + instruction.getCodeUnits();

        Instruction12x instr = (Instruction12x) instruction;
        int destRegister = instr.getRegisterA();
        int srcRegister = instr.getRegisterB();

        return new UnaryMathOp(address, opName, childAddress, destRegister, srcRegister);
    }

    private final int destRegister;
    private final int srcRegister;

    private UnaryMathOp(int address, String opName, int childAddress, int destRegister, int srcRegister) {
        super(address, opName, childAddress);

        this.destRegister = destRegister;
        this.srcRegister = srcRegister;
    }

    @Override
    public void execute(ExecutionNode node, MethodState mState) {
        HeapItem item = mState.readRegister(srcRegister);
        HeapItem resultItem;
        String type = getResultTypeName(getName());
        if (item.isUnknown()) {
            resultItem = HeapItem.newUnknown(type);
        } else {
            Object resultValue = perform(item.getValue(), getName());
            resultItem = new HeapItem(resultValue, type);
        }
        mState.assignRegister(destRegister, resultItem);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(getName());
        sb.append(" r").append(destRegister).append(", r").append(srcRegister);

        return sb.toString();
    }

    private Object perform(Object value, String opName) {
        // Stupid, but simple. Deals.
        Object resultValue = null;
        if (opName.startsWith("double")) {
            Double typedValue = Utils.getDoubleValue(value);
            if (opName.endsWith("float")) {
                resultValue = typedValue.floatValue();
            } else if (opName.endsWith("int")) {
                resultValue = typedValue.intValue();
            } else if (opName.endsWith("long")) {
                resultValue = typedValue.longValue();
            }
        } else if (opName.startsWith("float")) {
            Float typedValue = Utils.getFloatValue(value);
            if (opName.endsWith("double")) {
                resultValue = typedValue.doubleValue();
            } else if (opName.endsWith("int")) {
                resultValue = typedValue.intValue();
            } else if (opName.endsWith("long")) {
                resultValue = typedValue.longValue();
            }
        } else if (opName.startsWith("long")) {
            Long typedValue = Utils.getLongValue(value);
            if (opName.endsWith("double")) {
                resultValue = typedValue.doubleValue();
            } else if (opName.endsWith("int")) {
                resultValue = typedValue.intValue();
            } else if (opName.endsWith("float")) {
                resultValue = typedValue.floatValue();
            }
        } else if (opName.startsWith("int")) {
            // Could be something other than an int, such as short
            Integer typedValue = Utils.getIntegerValue(value);
            if (opName.endsWith("byte")) {
                resultValue = typedValue.byteValue();
            } else if (opName.endsWith("char")) {
                resultValue = (char) typedValue.intValue();
            } else if (opName.endsWith("short")) {
                resultValue = typedValue.shortValue();
            } else if (opName.endsWith("double")) {
                resultValue = typedValue.doubleValue();
            } else if (opName.endsWith("long")) {
                resultValue = typedValue.longValue();
            } else if (opName.endsWith("float")) {
                resultValue = typedValue.floatValue();
            }
        } else if (opName.startsWith("neg")) {
            if (opName.endsWith("double")) {
                Double typedValue = Utils.getDoubleValue(value);
                resultValue = -typedValue;
            } else if (opName.endsWith("float")) {
                Float typedValue = Utils.getFloatValue(value);
                resultValue = -typedValue;
            } else if (opName.endsWith("int")) {
                Integer typedValue = Utils.getIntegerValue(value);
                resultValue = -typedValue;
            } else if (opName.endsWith("long")) {
                Long typedValue = Utils.getLongValue(value);
                resultValue = -typedValue;
            }
        } else if (opName.startsWith("not")) {
            if (opName.endsWith("int")) {
                Integer typedValue = Utils.getIntegerValue(value);
                resultValue = ~typedValue;
            } else if (opName.endsWith("long")) {
                Long typedValue = Utils.getLongValue(value);
                resultValue = ~typedValue;
            }
        }

        return resultValue;
    }

    @Override
    public boolean modifiesRegister(int register) {
        return register == destRegister;
    }
}


text:
module Phaxio
  module Resources
    # Provides functionality for viewing and managing phone numbers.
    class PhoneNumber < Resource
      PHONE_NUMBERS_PATH = 'phone_numbers'.freeze
      private_constant :PHONE_NUMBERS_PATH

      # @return [String] The phone number itself, in E.164 format.
      # @!attribute phone_number

      # @return [String] The city associated with the phone number.
      # @!attribute city

      # @return [String] The state associated with the phone number.
      # @!attribute state

      # @return [String] The country associated with the phone number.
      # @!attribute country

      # @return [Integer] The cost of the phone number in cents.
      # @!attribute cost

      # @return [String] The callback URL associated with the phone number.
      # @!attribute callback_url

      has_normal_attributes %w(phone_number city state country cost callback_url)

      # @return [Time] The time at which the phone number was provisioned.
      # @!attribute provisioned_at

      # @return [Time] The last time the phone number was billed.
      # @!attribute last_billed_at

      has_time_attributes %w(provisioned_at last_billed_at)

      # A reference to a phone number, returned by some actions.
      class Reference
        # @return [String]
        #   The phone number in E.164 format.
        attr_accessor :phone_number

        def to_s
          phone_number
        end

        # Gets the referenced phone number.
        # @return [Phaxio::Resources::PhoneNumber]
        #   The referenced phone number.
        def get
          PhoneNumber.get self
        end
        alias :retrieve :get
        alias :find :get

        private

        def initialize phone_number
          self.phone_number = phone_number
        end
      end

      private

      class << self
        # Provision a new phone number.
        # @param params [Hash]
        #   A hash of parameters to send to Phaxio:
        #   - *country_code* [Integer] - The country code (E.164) of the number you'd like to provision.
        #   - *area_code* [Integer] - The area code of the number you'd like to provision.
        #   - *callback_url* [String] - A callback URL that we'll post to when a fax is received by this number. This will override the global receive callback URL, if you have one specified.
        # @return [Phaxio::Resources::PhoneNumber] The newly provisioned number.
        # @raise [Phaxio::Error::PhaxioError]
        # @see https://www.phaxio.com/docs/api/v2.1/phone_numbers/provision
        def create params = {}
          response = Client.request :post, phone_numbers_endpoint, params
          response_record response
        end
        alias :provision :create

        # Get information about a specific phone number.
        # @param phone_number [String]
        #   The phone number itself, in E.164 format, which you want to get information about.
        # @param params [Hash]
        #   A hash of parameters to send to Phaxio. This action has no unique parameters.
        # @return [Phaxio::Resources::PhoneNumber] The requested number.
        # @raise [Phaxio::Error::PhaxioError]
        # @see https://www.phaxio.com/docs/api/v2.1/phone_numbers/get_number
        def get phone_number, params = {}
          response = Client.request :get, phone_number_endpoint(phone_number.to_s), params
          response_record response
        end
        alias :find :get
        alias :retrieve :get

        # @macro paging
        # Get a list of phone numbers that you currently own on Phaxio.
        # @param params [Hash]
        #   A hash of parameters to send to Phaxio.
        #   - *country_code* [Integer] - An E.164 country code that you'd like to filter by.
        #   - *area_code* [Integer] - An area code that you'd like to filter by. If an area code is
        #     specified, then *country_code* is required.
        # @return [Phaxio::Resource::Collection<Phaxio::Resources::PhoneNumber>]
        #   A collection of phone numbers.
        # @raise [Phaxio::Error::PhaxioError]
        # @see https://www.phaxio.com/docs/api/v2.1/phone_numbers/list
        def list params = {}
          response = Client.request :get, phone_numbers_endpoint, params
          response_collection response
        end

        # Release a phone number that you no longer need. Once a phone number is released you will
        # no longer be charged for it.
        # @param phone_number [String]
        #   The phone number itself, in E.164 format, which you want to release.
        # @param params [Hash]
        #   A hash of parameters to send to Phaxio. This action has no unique parameters.
        # @return true
        # @raise [Phaxio::Error::PhaxioError]
        # @see https://www.phaxio.com/docs/api/v2.1/phone_numbers/release
        def delete phone_number, params = {}
          Client.request :delete, phone_number_endpoint(phone_number), params
          true
        end
        alias :release :delete

        private

        def phone_numbers_endpoint
          PHONE_NUMBERS_PATH
        end

        def phone_number_endpoint phone_number
          "#{phone_numbers_endpoint}/#{phone_number}"
        end
      end
    end
  end
end


text:
import { Body } from './body';
/**
 * Creates `Response` instances from provided values.
 *
 * Though this object isn't
 * usually instantiated by end-users, it is the primary object interacted with when it comes time to
 * add data to a view.
 *
 * ### Example
 *
 * ```
 * http.request('my-friends.txt').subscribe(response => this.friends = response.text());
 * ```
 *
 * The Response's interface is inspired by the Response constructor defined in the [Fetch
 * Spec](https://fetch.spec.whatwg.org/#response-class), but is considered a static value whose body
 * can be accessed many times. There are other differences in the implementation, but this is the
 * most significant.
 *
 * @experimental
 */
export class Response extends Body {
    constructor(responseOptions) {
        super();
        this._body = responseOptions.body;
        this.status = responseOptions.status;
        this.ok = (this.status >= 200 && this.status <= 299);
        this.statusText = responseOptions.statusText;
        this.headers = responseOptions.headers;
        this.type = responseOptions.type;
        this.url = responseOptions.url;
    }
    toString() {
        return `Response with status: ${this.status} ${this.statusText} for URL: ${this.url}`;
    }
}
//# sourceMappingURL=static_response.js.map


text:
$(document).ready(function() {
  var MakeFirstParagraphLead = function(elem) {
    var lead = $(elem).children("p:first");
    lead.addClass("lead");
    if (lead.html()) {
      lead.html(lead.html().charAt(0).toUpperCase() + lead.html().slice(1));
    }
    return elem;
  };

  var RemoveEmptyParagraphs = function(parent) {
    $(parent).find("p").each(
      function() {
        if ($(this).html() == "") {
          $(this).detach();
        }
      }
    );
    return parent;
  };

  var GetMetablock = function(elem) {
    if ($(elem).hasClass("memdoc")) {
      return $(elem).parent().find(".meta-info-block");
    } else {
      return $(elem).find(".meta-info-block");
    }
  };

  var AddToMetablock = function(elem, css) {
    var parent = $(elem).parent();
    var metablock = GetMetablock(parent);

    if (metablock.length == 0) {
      if (parent.hasClass("memdoc")) {
        parent.after("

");
      } else {
        // we are in a details textblock
        $(elem).before("

");
      }
    }
    metablock = GetMetablock(parent);

    $(elem).detach();
    metablock.append("
" + $(elem).html() + "
");
  };

  var TweakMemberDocStyle = function(elem) {
    var definition = $(elem).find("p").filter(function() {
      return ($(this).text()).match('^Definition at line.*\.$');
    });
    var overloaded = $(elem).find("p").filter(function() {
      return ($(this).text()).match('^This is an overloaded.*\.$');
    });
    var referenced = $(elem).find("p").filter(function() {
      return ($(this).text()).match('^Referenced by.*\.$');
    });
    var references = $(elem).find("p").filter(function() {
      return ($(this).text()).match('^References.*\.$');
    });
    var reimpl     = $(elem).find("p").filter(function() {
      return ($(this).text()).match('^Reimplemented (in|from).*\.$');
    });
    var impl       = $(elem).find("p").filter(function() {
      return ($(this).text()).match('^Implement(ed in|s).*\.$');
    });

    AddToMetablock(definition, 'meta-definition');
    AddToMetablock(overloaded, 'meta-overload');
    AddToMetablock(referenced, 'meta-referenced');
    AddToMetablock(references, 'meta-references');
    AddToMetablock(reimpl, 'meta-reimplemented');
    AddToMetablock(impl, 'meta-implemented');

    var metablock = GetMetablock($(elem));

    metablock.find("li a.el").addClass("code").removeClass("el");

    // make the first paragraph stand out
    MakeFirstParagraphLead($(elem));

    // remove empty paragraphs
    RemoveEmptyParagraphs($(elem));
  };

  var MakePanel = function(container, title, content, footer) {
    $(container).addClass("panel panel-default");
    $(container).find(title).addClass("panel-heading");
    $(container).find(content).addClass("panel-body");
    if (typeof(footer) !== 'undefined') {
      $(container).find(footer).addClass("panel-footer");
      if ($(container).find(content).text() === ""
          && $(container).find(footer).text() === "") {
        $(container).detach();
      }
    } else {
      if ($(container).find(content).text() == "") {
        $(container).detach();
      }
    }
  };

  var TweakMemberSections = function(dl) {
    MakePanel($(dl), 'dt', 'dd');
    dl.addClass("member-section").removeClass("panel-default");
    var dt = dl.find("dt");
    switch (dt.text()) {
      case "Template Parameters":
        dl.addClass("panel-primary");
        break;
      case "Parameters":
        dl.addClass("panel-primary");
        break;
      case "Returns":
        dl.addClass("panel-success");
        break;
      case "Precondition":
        dl.addClass("panel-info");
        break;
      case "Note":
        dl.addClass("panel-info");
        break;
      case "Exceptions":
        dl.addClass("panel-danger");
        break;
      case "Todo:":
        dl.addClass("panel-warning");
        break;
      default:  // 'See also', 'Since'
        dl.addClass("panel-default");
        break;
    }

    var param_table = dl.find("table.params, table.tparams, table.exception");
    if (param_table.length > 0) {
      param_table.addClass("table");
      param_table.unwrap();
    }

    var dds = dl.find("dd");
    if (dds.length > 1) {
      dt.after("

");
      var new_dds = dt.next();
      dds.each(function() {
        new_dds.append("
" + $(this).html() + "
");
        $(this).detach();
      });
    } else {
      dds.replaceWith(function() { return "
" + $(this).html() + "
"; });
    }
    dt.replaceWith("
" + dt.html() + "
");
    dl.replaceWith("
" + dl.html() + "
");
  };

  // detailed description text
  $("h2.groupheader:contains('Detailed Description')").each(
    function() {
      TweakMemberDocStyle($(this).next());
    }
  );

  // member details doc
  $(".memdoc").each(function() {
    TweakMemberDocStyle($(this));
    $(this).find("dl").each(function() {
      TweakMemberSections($(this));
    });
  });

  $(".memitem").each(function() {
    MakePanel($(this), '.memproto', '.memdoc');
  });

  $(".memitem").each(function() {
    var header = $(this).children(".panel-heading");
    var footer = $(this).children(".panel-footer").find(".meta-info-block");
    if (footer.find(".meta-overload").is(".meta-overload")) {
      header.find(".mlabels td.mlabels-right > .mlabels").prepend("overload");
    }
  });

  $(".mlabel").each(function() {
    switch ($(this).text()) {
      case "delete":
        $(this).addClass("label label-danger");
        break;
      case "private":
        $(this).addClass("label label-warning");
        break;
      case "protected":
        $(this).addClass("label label-primary");
        break;
      case "static":
        $(this).addClass("label label-success");
        break;
      case "virtual":
        $(this).addClass("label label-info");
        break;
      default:  // 'override', 'inline'
        $(this).addClass("label label-default");
    }
  });

  // directory tables
  $(".directory table.directory").each(function() {
    $(this).addClass("table");
    $(this).find("span.icon").unwrap().addClass("badge").removeClass("icon");
  });

  $("table.doxtable").addClass("table");

  // reflists (i.e. ToDos)
  $("div.textblock dl.reflist").each(function() {
    $(this).find("dt").each(function() {
      $(this).wrap("

");
      $(this).replaceWith("
" + $(this).html() + "
");
    });
    $(this).find("dd").each(function() {
      $(this).prev().append($(this));
      $(this).replaceWith("
" + $(this).html() + "
");
    });
    $(this).find(".panel-body p").removeClass();
  });

  // panels/blocks in detailed descriptions
  $("div.textblock").each(function() {
    $(this).find("dl").each(function() {
      TweakMemberSections($(this));
    });
  });
});


text:
[![Build Status](https://travis-ci.org/bcho/tidy.svg?branch=master)](https://travis-ci.org/bcho/tidy)
[![GoDoc](https://godoc.org/github.com/bcho/tidy?status.svg)](https://godoc.org/github.com/bcho/tidy)

Tidy my files up.

## Usage

```shell
$ tidy
$ tidy ../foo
$ tidy /path/to/my/dir
```

## LICENSE

MIT


text:
require 'spec_helper'

describe Dicer::Behavior do
  subject(:behavior) do
    Module.new do
      include Dicer::Behavior

      def foo; 2; end
    end
  end

  describe '.behavior_methods' do
    subject { behavior.behavior_methods }

    it { should have(1).item }
    it { should include(:foo) }
  end
end


text:
<?php

namespace BrainBundle\Controller;

use BrainBundle\Entity\Aiml;
use BrainBundle\Entity\AimlUploader;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

/**
 * Aiml controller.
 *
 */
class AimlController extends Controller
{
    public function uploadAction(Request $request)
    {
        $uploader = new AimlUploader();
        $form = $this->createForm('BrainBundle\Form\AimlUploaderType', $uploader);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($uploader);
            $em->flush();
        }

        return $this->render('BrainBundle:aiml:upload.html.twig', array(
            'uploader' => $uploader,
            'form' => $form->createView(),
        ));
    }
}


text:
#define OBSD_HAS_DECLARE_FUNCTION_NAME
#define OBSD_HAS_DECLARE_FUNCTION_SIZE
#define OBSD_HAS_DECLARE_OBJECT


text:
class TfrmSetupWizard : public TForm
{
__published:	// IDE-managed Components
    TPanel *panMessageHeader;
    TLabel *lblMessageTitle;
    TLabel *lblShortMessage;
    TBevel *bvlMessageTop;
    TImage *imgMessageIcon;
    TImage *imgInformation;
    TPanel *panRed;
    TPanel *panYellow;
    TPanel *panGreen;
    TPanel *panCyan;
    TButton *cmdClose;
    TPanel *Panel1;
private:	// User declarations
public:		// User declarations
    __fastcall TfrmSetupWizard(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TfrmSetupWizard *frmSetupWizard;
//---------------------------------------------------------------------------
#endif


text:
package tests;

import jpigpio.JPigpio;
import jpigpio.Pigpio;
import jpigpio.PigpioException;
import jpigpio.Utils;
import jpigpio.sensors.HC_SR04;

public class Test_HC_SR04 {

	private int triggerPin = 17;
	private int echoPin = 18;

	public static void main(String args[]) {
		System.out.println("Test HC-SR04");
		Test_HC_SR04 app = new Test_HC_SR04();
		app.run();
	}

	public void run() {
		try {
			// JPigpio pigpio = new PigpioSocket("raspi", 8888);
			JPigpio pigpio = new Pigpio();
			pigpio.setDebug(false);
			pigpio.gpioInitialize();

			// Create an instance of the HC_SR04 ultrasonic device
			HC_SR04 hcSR04 = new HC_SR04(pigpio, triggerPin, echoPin);
			Utils.addShutdown(pigpio);

			// Set the mode of the pins we will be using.
			pigpio.gpioSetMode(triggerPin, JPigpio.PI_OUTPUT);
			pigpio.gpioSetMode(echoPin, JPigpio.PI_INPUT);
			while (true) {
				System.out.println("Distance: " + hcSR04.getMetricDistance() * 100 + "cm");
				try {
					Thread.sleep(250);
				} catch (Exception e) {
					e.printStackTrace();
					return;
				}
			}
		} catch (PigpioException e) {
			e.printStackTrace();
		}
	}
} // End of class
// End of file


text:
namespace Hazel
{
	class NetworkConnectionListener
	{
	public:
		NetworkConnectionListener();
		NetworkEndPoint &GetEndPoint();

		std::function<void(NewConnectionEventArgs)> NewConnection;

		virtual void Start() = 0;

	protected:
		void SetEndPoint(NetworkEndPoint &end_point);

		void InvokeNewConnection(Bytes &bytes, NetworkConnection *connection);

		NetworkEndPoint end_point;
	};
}


text:
package com.navercorp.pinpoint.web.view;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.navercorp.pinpoint.web.applicationmap.histogram.AgentTimeHistogramSummary;

import java.io.IOException;
import java.util.List;

/**
 * @author Taejin Koo
 */
public class ApplicationTimeHistogramViewModelSerializer extends JsonSerializer<ApplicationTimeHistogramViewModel> {

    @Override
    public void serialize(ApplicationTimeHistogramViewModel value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeStartObject();

        writeSummary(value.getSummaryList(), jgen);
        writeTimeSeries(value.getTimeSeriesViewModel(), jgen);

        jgen.writeEndObject();
    }

    private void writeTimeSeries(List<AgentResponseTimeViewModel> timeSeriesViewModel, JsonGenerator jgen) throws IOException {
        jgen.writeObjectFieldStart("timeSeries");
        for (AgentResponseTimeViewModel agentResponseTimeViewModel : timeSeriesViewModel) {
            jgen.writeObjectField(agentResponseTimeViewModel.getAgentName(), agentResponseTimeViewModel.getResponseTimeViewModel());
        }
        jgen.writeEndObject();
    }

    private void writeSummary(List<AgentTimeHistogramSummary> summaryList, JsonGenerator jgen) throws IOException {
        jgen.writeObjectFieldStart("summary");
        for (AgentTimeHistogramSummary summary : summaryList) {
            jgen.writeObjectField(summary.getAgentId(), summary.getHistogram());
        }
        jgen.writeEndObject();
    }

}


text:
package net.i2geo.comped;

import junit.framework.TestCase;

public class AppTest extends TestCase {
    public void testGetHello() throws Exception {
        assertEquals("Hello", App.getHello());
    }
}