text:
(function (angular) {
  angular.module('app')
    .config(Routes);

  Routes.$inject = [
    '$stateProvider',
    '$urlRouterProvider',
  ];
  function Routes($stateProvider, $urlRouterProvider) {
    $stateProvider

      .state('home', {
        url: '/',
        templateUrl: 'templates/home.html',
        controller: 'HomeController',
        controllerAs: 'vm',
      })

      .state('chat', {
        url: '/chat/:username',
        templateUrl: 'templates/chat.html',
        controller: 'ChatController',
        controllerAs: 'vm',
      });

    $urlRouterProvider.otherwise('/');
  }
}(angular));


text:
package dsatool.ui;

import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.util.StringConverter;

public class ReactiveComboBox<T> extends ComboBox<T> {
	private static EventHandler<ActionEvent> filter = ActionEvent::consume;
	private final StringBuilder searchString = new StringBuilder();

	private long lastChange = 0;

	private final ChangeListener<String> textListener = (observable, oldValue, newValue) -> {
		final TextField editor = getEditor();
		final int previousCaret = editor.getCaretPosition() + 1;
		final String text = newValue;

		T item = null;
		if (previousCaret > 0 && previousCaret <= text.length()) {
			final String searchText = editor.getText().substring(0, previousCaret);
			final T selected = getSelectionModel().getSelectedItem();
			if (selected == null || !selected.toString().toLowerCase().startsWith(searchText.toLowerCase())) {
				item = findItem(searchText);
			}
		}

		if (item != null) {
			editor.setText(item.toString());
			Platform.runLater(() -> {
				editor.positionCaret(editor.getText().length());
				editor.selectPositionCaret(previousCaret);
			});
		} else {
			final StringConverter<T> converter = getConverter();
			if (converter != null) {
				addEventFilter(ActionEvent.ACTION, filter);
				setValue(converter.fromString(text));
				removeEventFilter(ActionEvent.ACTION, filter);
			}
		}
	};

	private final EventHandler<KeyEvent> searchHandler = event -> {
		final KeyCode code = event.getCode();
		if (!isEditable()) {
			final long current = System.currentTimeMillis();

			if (current > lastChange + 750) {
				searchString.setLength(0);
			}
			lastChange = current;
			if (code == KeyCode.BACK_SPACE && searchString.length() > 0) {
				searchString.setLength(searchString.length() - 1);
			} else if (code == KeyCode.ESCAPE) {
				searchString.setLength(0);
			} else if (code != KeyCode.ENTER && !code.isNavigationKey() && !code.isFunctionKey() && !code.isMediaKey() && !code.isModifierKey()) {
				searchString.append(event.getText());
			} else
				return;

			final T item = findItem(searchString.toString());
			if (item != null) {
				addEventFilter(ActionEvent.ACTION, filter);
				setValue(item);
				removeEventFilter(ActionEvent.ACTION, filter);
			}

			event.consume();
		} else if (code == KeyCode.ENTER) {
			final TextField editor = getEditor();
			if (!editor.getSelectedText().isEmpty()) {
				editor.positionCaret(editor.getText().length());
				event.consume();
			}
		}
	};

	public ReactiveComboBox() {
		getEditor().textProperty().addListener(textListener);
		setOnKeyPressed(searchHandler);
	}

	public ReactiveComboBox(final ObservableList<T> items) {
		super(items);

		getEditor().textProperty().addListener(textListener);
		setOnKeyPressed(searchHandler);
	}

	private final T findItem(final String prefix) {
		final ObservableList<T> items = getItems();
		for (final T item : items) {
			if (item.toString().toLowerCase().startsWith(prefix.toLowerCase())) return item;
		}
		return null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { test } from 'qunit';
import moduleForAcceptance from 'openworks-status-page/tests/helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | things');

test('viewing things at a location', function(assert) {
  const thingsCount = 4;
  let firstLocation = server.create('location');
  server.createList('thing', thingsCount, {locationId: firstLocation.id});

  visit('/locations/1/things');

  andThen(function() {
    assert.equal(currentURL(), '/locations/1/things');
    assert.equal(find('.card .card-header[data-thing-id]').length, 4);
  });
});

test('viewing a thing', function(assert) {
  let thing = server.create('location').createThing({name: 'Thing 1'});
  server.createList('property', 3, {thingId: thing.id});

  visit('/things/1');

  andThen(function() {
    assert.equal(currentURL(), '/things/1');
    assert.equal(find('[data-thing-id=1]').length, 1);
    assert.equal(find('[data-thing-id=1]').text(), 'Thing 1');
    assert.equal(find('h4.text-muted').text(), 'Location 1');
    assert.equal(find('h5.text-muted').length, 3);
  });
});

test('navigating from a thing to it\'s location', function(assert) {
  let thing = server.create('location').createThing({name: 'Thing 1'});
  server.createList('property', 3, {thingId: thing.id});

  visit('/things/1');
  click('h4:contains(Location 1)');

  andThen(function() {
    assert.equal(currentURL(), '/locations/1/things');
    assert.equal(find('.card .card-header[data-thing-id]').length, 1);
  });
});

test('creating a new thing from a location', function(assert) {
  server.create('location').createThing({name: 'Thing 1'});

  visit('/locations/1/things');
  click('.btn:contains(Create a New Thing)');

  andThen(function() {
    assert.equal(currentURL(), '/locations/1/things/new');
  });
});

test('should do this for all things routes', function(assert){
  visit('/things/');

  andThen(function() {
    assert.equal(this.$('.things-title').text().trim(), 'All the Things!');
    //this test will break when we add the things.new button near title
    assert.equal(this.$('.btn-primary').text().trim(), '');
    //assert.equal(this.$('.btn-primary').text().trim(), 'Add a Thing');
  });
});

test('should list zero things correctly', function(assert) {
  visit('/things/');

  andThen(function() {
    assert.equal(this.$('.empty-thing-title').text().trim(), 'No Things Yet');
    //this test will break when we add the things.new button under "No Things Yet"
    assert.equal(this.$('.btn-success').text().trim(), '');
    //assert.equal(this.$('.btn-success').text().trim(), 'Add a Thing');
  });
});

test('should list one thing correctly', function(assert) {
  server.create('location').createThing({name: 'Thing 1'});

  visit('/things/');

  andThen(function() {
    let card = find('.card');
    assert.equal(card.length, 1);
  });
});

test('should list many things correctly', function(assert) {
  let max = 10;
  for(var i=0; i < max; i++) {
    server.create('location').createThing({name: `Thing ${i+1}`});
  }

  visit('/things/');

  andThen(function() {
    let card = find('.card');
    assert.equal(card.length, max);
  });
});


text:
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <libgen.h>
#include <errno.h>

#include "common.h"
#include "module.h"

bool module_open(module_t *module, const char *path) {
	/* a loop index */
	size_t i = 0;

	/* the module file name extension */
	char *extension = NULL;

	assert(NULL != module);
	assert(NULL != path);

	/* get the module size */
	if (-1 == stat(path, &module->attributes)) {
		goto failure;
	}

	/* copy the module path */
	module->path = strdup(path);
	if (NULL == module->path) {
		goto failure;
	}

	/* get the module name */
	module->name = basename(module->path);
	if (NULL == module->name) {
		goto free_path;
	}

	/* strip the module file name extension */
	extension = strchr(module->name, '.');
	if (NULL == extension) {
		goto free_path;
	}
	extension[0] = '\0';

	/* replace all hyphens in the module name with underscores */
	for ( ; strlen(module->name) > i ; ++i) {
		if ('-' == module->name[i]) {
			module->name[i] = '_';
		}
	}

	/* open the module for reading */
	module->fd = open(path, O_RDONLY);
	if (-1 == module->fd) {
		goto free_path;
	}

	/* map the module to memory*/
	module->contents = mmap(NULL,
	                        (size_t) module->attributes.st_size,
	                        PROT_READ,
	                        MAP_PRIVATE,
	                        module->fd,
	                        0);
	if (MAP_FAILED == module->contents) {
		goto close_module;
	}

	return true;

	/* unmap the module contents */
	(void) munmap(module->contents, (size_t) module->attributes.st_size);

close_module:
	/* close the module */
	(void) close(module->fd);

free_path:
	/* free the module path */
	free(module->path);

failure:
	return false;
}

void module_close(module_t *module) {
	assert(NULL != module);
	assert(NULL != module->contents);
	assert(NULL != module->path);

	/* unmap the module contents */
	(void) munmap(module->contents, (size_t) module->attributes.st_size);

	/* close the module */
	(void) close(module->fd);

	/* free the module path */
	free(module->path);
}

bool module_load(module_t *module) {
	assert(NULL != module);
	assert(NULL != module->contents);
	assert(0 < module->attributes.st_size);

	if (-1 == syscall(SYS_init_module,
	                  module->contents,
	                  (unsigned long) module->attributes.st_size,
	                  "")) {
		if (EEXIST != errno) {
			return false;
		}
	}

	return true;
}

bool module_for_each_dependency(module_t *module,
                                const dependency_callback_t callback,
                                void *arg) {
	/* the current offset within the module contents */
	off_t offset = 0;

	/* the module dependencies */
	char *dependencies = NULL;

	/* strtok_r()'s position within the dependencies list */
	char *position = NULL;

	/* a single dependency */
	char *dependency = NULL;

	/* the return value */
	bool result = false;

	assert(NULL != module);
	assert(NULL != module->contents);
	assert(STRLEN("depends=") < module->attributes.st_size);
	assert(NULL != callback);

	/* find the module dependencies */
	for ( ;
	     module->attributes.st_size - STRLEN("depends=") > offset;
	     ++offset) {
		if (0 == strncmp((char *) (module->contents + offset),
		                 "depends=",
		                 STRLEN("depends="))) {
			dependencies = (char *) (module->contents + \
			                         offset + \
			                         STRLEN("depends="));
			break;
		}
	}

	/* if the dependencies were not found, report failure */
	if (NULL == dependencies) {
		goto end;
	}

	/* if the dependencies list is empty, report success */
	if ('\0' == dependencies[0]) {
		result = true;
		goto end;
	}

	/* duplicate the dependencies list */
	dependencies = strdup(dependencies);
	if (NULL == dependencies) {
		goto end;
	}

	/* run the callback for each dependency */
	dependency = strtok_r(dependencies, ",", &position);
	while (NULL != dependency) {
		if (false == callback(dependency, arg)) {
			goto free_dependencies;
		}
		dependency = strtok_r(NULL, ",", &position);
	}

	/* report success */
	result = true;

free_dependencies:
	/* free the dependencies list */
	free(dependencies);

end:
	return result;
}

bool module_for_each_alias(module_t *module,
                           const alias_callback_t callback,
                           void *arg) {
	/* the current offset within the module contents */
	off_t offset = 0;

	assert(NULL != module);
	assert(NULL != module->contents);
	assert(STRLEN("depends=") < module->attributes.st_size);
	assert(NULL != callback);

	/* find the module aliases and run the callback for each */
	for ( ;
	     module->attributes.st_size - STRLEN("alias=") > offset;
	     ++offset) {
		if (0 == strncmp((char *) (module->contents + offset),
		                 "alias=",
		                 STRLEN("alias="))) {
			if (false == callback(module->name,
			                      (char *) (module->contents + \
			                                offset + \
			                                STRLEN("alias=")),
			                      arg)) {
				return false;
			}
		}
	}

	return true;
}


text:
package rocks.jsre.exception;

/**
 * An InputValidationException occurs, when setting the input of the API.
 * When calling RuleEngine.setInput() the engine validates the input against the
 * specification in the configuration. If an input value does not fullfil the
 * requirements an InputValidationException is thrown.
 *
 * The exception contains further information of what went wrong.
 *
 * @author Florian Beese
 *
 */
public class InputValidationException extends Exception {

	private static final long serialVersionUID = 1L;

	public InputValidationException(String msg) {
		super(msg);
	}

}


text:
package com.ledger.ledgerwallet.app.m2fa.pairing

import java.util

import android.os.Bundle
import android.view.ViewGroup.LayoutParams
import android.view.{View, ViewGroup, LayoutInflater}
import com.ledger.ledgerwallet.R
import com.ledger.ledgerwallet.base.{BaseFragment, ContractFragment}
import com.ledger.ledgerwallet.utils.TR
import com.ledger.ledgerwallet.utils.logs.Logger
import com.ledger.ledgerwallet.widget.ScannerFrame
import me.dm7.barcodescanner.zbar.{BarcodeFormat, Result, ZBarScannerView}
import me.dm7.barcodescanner.zbar.ZBarScannerView.ResultHandler
import org.spongycastle.crypto.digests.SHA256Digest
import org.spongycastle.util.encoders.Hex

class ScanPairingQrCodeFragment extends BaseFragment with ContractFragment[CreateDonglePairingActivity.CreateDonglePairingProccessContract] with ResultHandler {

  private lazy val _scannerView = new ZBarScannerView(getActivity)

  override def onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle): View = {
    _scannerView.removeViewAt(1)
    _scannerView.addView(new ScannerFrame(getActivity), new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
    _scannerView
  }

  override def onResume(): Unit = {
    super.onResume()
    val formats = new util.ArrayList[BarcodeFormat](1)
    formats.add(BarcodeFormat.QRCODE)
    _scannerView.setResultHandler(this)
    _scannerView.setAutoFocus(true)
    _scannerView.setFormats(formats)
    _scannerView.startCamera()
  }

  override def onPause(): Unit = {
    super.onPause()
    _scannerView.stopCamera()
  }

  override def handleResult(result: Result): Unit = {
    val content = result.getContents
    try {
      val bytes = Hex.decode(content)
      if (bytes.length != 17) return
      val data = bytes.slice(0, 16)
      val chks = bytes(16).toInt
      val validChecksum = new Array[Byte](32)
      val sha256 = new SHA256Digest()
      sha256.update(data, 0, data.length)
      sha256.doFinal(validChecksum, 0)
      if (chks != validChecksum(0).toInt) {
       Logger.d("Invalid checksum")
      }
      contract.setPairingId(content)
    } catch {
      case ex: Throwable => ex.printStackTrace()
    }
  }

  override def tag: String = "ScanPairingQrCodeFragment"
}


text:
namespace Second {
    public class Generic2 {
        public static string Flag = typeof(Generic2).FullName;
    }
}


text:
```eval_rst
:Release: |version|
:Date: |today|

.. note:: Module is Python 3 compatible only.
```

This guide is intended as an introductory overview of Black Mamba and
explains how to install and make use of the most important features of
Black Mamba. For detailed reference documentation of the functions and
classes contained in the package, see the [API Reference](../api/index.md).

```eval_rst
.. toctree::
   :maxdepth: 1

   requirements
   install
   configuration
   shortcuts
   scripts
```


text:
<?php

namespace Wookieb\Tests\Resources;
require_once __DIR__.'/PointedZebra.php';

/**
 * http://strangenamesasaservice.nodejitsu.com/ <3
 *
 * @author Łukasz Kużyński "wookieb" <lukasz.kuzynski@gmail.com>
 */
class IntentionalQuiver extends PointedZebra
{
    public $knobbyXylophone = 'knowledgeable name';
}


text:
"use strict";

/**
 * This is the plugin for syncing location
 * @type {string}
 */
var EVENT_NAME = "browser:location";
var OPT_PATH   = "ghostMode.location";
exports.canEmitEvents = true;

/**
 * @param {BrowserSync} bs
 */
exports.init = function (bs) {
    bs.socket.on(EVENT_NAME, exports.socketEvent());
};

/**
 * Respond to socket event
 */
exports.socketEvent = function (bs) {
    return function (data) {
        if (data.override || bs.canSync(data, OPT_PATH)) {
            if (data.path) {
                exports.setPath(data.path);
            } else {
                exports.setUrl(data.url);
            }
        }
    };
};

/**
 * @param url
 */
exports.setUrl = function (url) {
    window.location = url;
};

/**
 * @param path
 */
exports.setPath = function (path) {
    window.location = window.location.protocol + "//" + window.location.host + path;
};


text:
Below, all contributors are thanked for their assistance and help. Every commit and pull request helps the platform grow!

_If you contributed and are not on this list but would like to be, please open a Pull Request to add your name and we will merge it in when available!_

We recommend you post your name as a ##, then a quick blurb about you, then your location, and a link you would like people to look at. But, whatever works for you, at our discretion of course.

## Kevin Eaton

* Geek, Programmer, Entrepreneur, Chaplain, Father

* Salem, NH

* [My Site](https://www.kevineaton.net)


text:
/* eslint no-underscore-dangle: ["error", { "allow": ["__"] }] */

import { Observable } from 'rxjs/Observable';
import * as R from 'ramda';
import { actions as uiActions } from './ui';
import { success, accessTokenSelector$ } from '../utils/cycleHelper';

// ----------------------------------------------------------------------------
// 1. Constants
// ----------------------------------------------------------------------------

const START = 'mcs-lite-admin-web/service/START';
const STOP = 'mcs-lite-admin-web/service/STOP';
const RESTART = 'mcs-lite-admin-web/service/RESTART';
const FETCH_IP_LIST = 'mcs-lite-admin-web/service/FETCH_IP_LIST';
const SET_IP_LIST = 'mcs-lite-admin-web/service/SET_IP_LIST';
const CLEAR = 'mcs-lite-admin-web/service/CLEAR';

export const constants = {
  START,
  STOP,
  RESTART,
  FETCH_IP_LIST,
  SET_IP_LIST,
  CLEAR,
};

// ----------------------------------------------------------------------------
// 2. Action Creators (Sync)
// ----------------------------------------------------------------------------

const start = message => ({ type: START, payload: message });
const stop = message => ({ type: STOP, payload: message });
const restart = message => ({ type: RESTART, payload: message });
const fetchIpList = () => ({ type: FETCH_IP_LIST });
const setIpList = ipList => ({ type: SET_IP_LIST, payload: ipList });
const clear = () => ({ type: CLEAR });

export const actions = {
  start,
  stop,
  restart,
  fetchIpList,
  setIpList,
  clear,
};

// ----------------------------------------------------------------------------
// 3. Cycle (Side-effects)
// ----------------------------------------------------------------------------

function startCycle(sources) {
  const accessToken$ = accessTokenSelector$(sources.STATE);

  const message$ = sources.ACTION.filter(action => action.type === START).pluck(
    'payload',
  );

  const request$ = sources.ACTION.filter(
    action => action.type === START,
  ).combineLatest(accessToken$, (action, accessToken) => ({
    url: '/api/service/start',
    method: 'GET',
    headers: { Authorization: `Bearer ${accessToken}` },
    category: START,
  }));

  const successRes$ = sources.HTTP.select(START).switchMap(success);

  const action$ = Observable.from([
    request$.mapTo(uiActions.setLoading()),
    successRes$
      .withLatestFrom(message$, (response, message) => message)
      .map(message =>
        uiActions.addToast({ kind: 'success', children: message }),
      ),
  ]).mergeAll();

  return {
    ACTION: action$,
    HTTP: request$,
  };
}

function stopCycle(sources) {
  const accessToken$ = accessTokenSelector$(sources.STATE);

  const message$ = sources.ACTION.filter(action => action.type === STOP).pluck(
    'payload',
  );

  const request$ = sources.ACTION.filter(
    action => action.type === STOP,
  ).combineLatest(accessToken$, (action, accessToken) => ({
    url: '/api/service/stop',
    method: 'GET',
    headers: { Authorization: `Bearer ${accessToken}` },
    category: STOP,
  }));

  const successRes$ = sources.HTTP.select(STOP).switchMap(success);

  const action$ = Observable.from([
    request$.mapTo(uiActions.setLoading()),
    successRes$
      .withLatestFrom(message$, (response, message) => message)
      .map(message =>
        uiActions.addToast({ kind: 'success', children: message }),
      ),
  ]).mergeAll();

  return {
    ACTION: action$,
    HTTP: request$,
  };
}

function restartCycle(sources) {
  const accessToken$ = accessTokenSelector$(sources.STATE);
  const message$ = sources.ACTION.filter(
    action => action.type === RESTART,
  ).pluck('payload');

  const stopRequest$ = sources.ACTION.filter(
    action => action.type === RESTART,
  ).combineLatest(accessToken$, (action, accessToken) => ({
    url: '/api/service/stop',
    method: 'GET',
    headers: { Authorization: `Bearer ${accessToken}` },
    category: `${RESTART}_STOP`,
  }));

  const successStopRes$ = sources.HTTP.select(`${RESTART}_STOP`).switchMap(
    success,
  );

  const startRequest$ = successStopRes$.withLatestFrom(
    accessToken$,
    (action, accessToken) => ({
      url: '/api/service/start',
      method: 'GET',
      headers: { Authorization: `Bearer ${accessToken}` },
      category: `${RESTART}_START`,
    }),
  );

  const successStartRes$ = sources.HTTP.select(`${RESTART}_START`).switchMap(
    success,
  );

  const action$ = Observable.from([
    stopRequest$.mapTo(uiActions.setLoading()),
    successStartRes$
      .withLatestFrom(message$, (response, message) => message)
      .map(message =>
        uiActions.addToast({ kind: 'success', children: message }),
      ),
  ]).mergeAll();

  const request$ = Observable.merge(stopRequest$, startRequest$);

  return {
    ACTION: action$,
    HTTP: request$,
  };
}

function fetchIpListCycle(sources) {
  const accessToken$ = accessTokenSelector$(sources.STATE);
  const fetchAction$ = sources.ACTION.filter(
    action => action.type === FETCH_IP_LIST,
  );
  const successResToFetch$ = sources.HTTP.select()
    .concatMap(success)
    .filter(
      R.pipe(
        R.path(['request', 'category']),
        R.contains(R.__, [STOP, START, `${RESTART}_START`]),
      ),
    );

  const request$ = Observable.merge(
    fetchAction$,
    successResToFetch$,
  ).combineLatest(accessToken$, (action, accessToken) => ({
    url: '/api/ip',
    method: 'GET',
    headers: { Authorization: `Bearer ${accessToken}` },
    category: FETCH_IP_LIST,
  }));

  const successRes$ = sources.HTTP.select(FETCH_IP_LIST).switchMap(success);

  const action$ = Observable.from([
    request$.mapTo(uiActions.setLoading()),
    successRes$.pluck('body', 'data').map(setIpList),
    successRes$.mapTo(uiActions.setLoaded()),
  ]).mergeAll();

  return {
    ACTION: action$,
    HTTP: request$,
  };
}

export const cycles = {
  startCycle,
  stopCycle,
  restartCycle,
  fetchIpListCycle,
};

// ----------------------------------------------------------------------------
// 4. Reducer as default (State shaper)
// ----------------------------------------------------------------------------

const initialState = [];

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case SET_IP_LIST:
      return action.payload;
    case CLEAR:
      return initialState;
    default:
      return state;
  }
}


text:
package nimble

import (
	"crypto/md5"
	"encoding/hex"
	"strings"
)

const UnitGi = 1024 * 1024 * 1024
const UnitMebi = 1024

func EncodeName(id string) string {
	h := md5.New()
	h.Write([]byte(id))
	encodedName := hex.EncodeToString(h.Sum(nil))
	prefix := strings.Split(id, "-")[0] + "-"
	postfix := encodedName[:MaxNameLength-len(prefix)]
	return prefix + postfix
}

func TruncateDescription(desc string) string {
	if len(desc) > MaxDescriptionLength {
		desc = desc[:MaxDescriptionLength]
	}
	return desc
}

func Byte2Gib(byteSize int64) int64 {
	return byteSize / UnitGi
}

func Gib2Mebi(gigabyte int64) int64 {
	return gigabyte * UnitMebi
}


text:
<?php

use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Php as PhpEngine;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter;
use Phalcon\Session\Adapter\Files as SessionAdapter;
use Phalcon\Flash\Session as FlashSession;
use Phalcon\Mvc\Model\Manager as ModelsManager;

/**
 * Shared configuration service
 */
$di->setShared('config', function () {
    return include APP_PATH . "/config/config.php";
});

/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->setShared('url', function () {
    $config = $this->getConfig();

    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);

    return $url;
});

/**
 * Setting up the view component
 */
$di->setShared('view', function () {
    $config = $this->getConfig();

    $view = new View();
    $view->setDI($this);
    $view->setViewsDir($config->application->viewsDir);

    $view->registerEngines([
        '.volt' => function ($view) {
            $config = $this->getConfig();

            $volt = new VoltEngine($view, $this);

            $volt->setOptions([
                'compiledPath' => $config->application->cacheDir,
                'compiledSeparator' => '_'
            ]);

            return $volt;
        },
        '.phtml' => PhpEngine::class

    ]);

    return $view;
});

/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->setShared('db', function () {
    $config = $this->getConfig();

    $class = 'Phalcon\Db\Adapter\Pdo\\' . $config->database->adapter;
    $params = [
        'host'     => $config->database->host,
        'username' => $config->database->username,
        'password' => $config->database->password,
        'dbname'   => $config->database->dbname,
        'charset'  => $config->database->charset
    ];

    if ($config->database->adapter == 'Postgresql') {
        unset($params['charset']);
    }

    $connection = new $class($params);

    return $connection;
});

/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->setShared('modelsMetadata', function () {
    return new MetaDataAdapter();
});

/**
 * Obtiene el administrador del los modelos para ejecutar consultas PSQL
 */
$di->set(
    "modelsManager",
    function() {
        return new ModelsManager();
    }
);

/**
 * Register the session flash service with the Twitter Bootstrap classes
 */
$di->set('flash', function () {
    return new FlashSession([
        'error'   => 'alert alert-danger',
        'success' => 'alert alert-success',
        'notice'  => 'alert alert-info',
        'warning' => 'alert alert-warning'
    ]);
});

/**
 * Start the session the first time some component request the session service
 */
$di->setShared('session', function () {
    $session = new SessionAdapter();
    $session->start();

    return $session;
});

$di->set('elements', function () {
    return new Elements();
});

$di->set('resources', function () {
    return new ResourceLoader();
});


text:
{% load i18n %}

{% if forum %}{% trans "New Topic" %}{% else %}{% trans "New Reply" %}{% endif %}

        <form id="post" action="{{ form_url|default_if_none:"." }}" method="post" enctype="multipart/form-data">
            {% csrf_token %}

My browser / operating system: {{ simple_user_agent|default:'NOT PROVIDED' }}

            {% if create_poll_form %}

                <fieldset>
                    <legend>{% trans "Create a poll" %}</legend>

                            {{ poll_form }}

                </fieldset>

            {% endif %}

Please enable JavaScript!

            {% if forum %}

                    {% trans "Subject" %}
                    {{ form.name.errors }}
                    {{ form.name }}

            {% endif %}

                {% trans "Message" %}
                {{ form.body.errors }}
                {{ form.body }}

                {{ form.subscribe }}

            {% if forum_settings.ATTACHMENT_SUPPORT %}

                    <fieldset>
                        <legend>{% trans "Attachment" %}</legend>

                            {{ form.attachment.errors }}

                                {{ form.attachment }}

                    </fieldset>

            {% endif %}

                <button type="submit" class="grey button" name="{{ form.FORM_NAME }}">{% trans "Submit" %}</button>
                {% trans "Go back" %}

        </form>


text:
package fr.minuskube.inv.content;

public class SlotPos {

    private final int row;
    private final int column;

    public SlotPos(int row, int column) {
        this.row = row;
        this.column = column;
    }

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

        SlotPos slotPos = (SlotPos) obj;

        return row == slotPos.row && column == slotPos.column;
    }

    @Override
    public int hashCode() {
        int result = row;
        result = 31 * result + column;

        return result;
    }

    public int getRow() { return row; }
    public int getColumn() { return column; }

    public static SlotPos of(int row, int column) {
        return new SlotPos(row, column);
    }

}


text:
@interface PodsDummy_Pods_KLDraggableTransition_Tests : NSObject
@end
@implementation PodsDummy_Pods_KLDraggableTransition_Tests
@end


text: Adds an index variable to a for loop iterating over a collection.


text:
package org.drools.core.runtime.rule.impl;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import org.kie.api.runtime.rule.ConsequenceExceptionHandler;
import org.kie.api.runtime.rule.Match;
import org.kie.api.runtime.rule.RuleRuntime;

public class DefaultConsequenceExceptionHandler implements ConsequenceExceptionHandler, Externalizable {

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    }

    public void writeExternal(ObjectOutput out) throws IOException {
    }

    public void handleException(Match activation,
                                RuleRuntime workingMemory,
                                Exception exception) {
        throw new org.kie.api.runtime.rule.ConsequenceException(exception, workingMemory, activation );
    }

}


text:
These files were copied from 2014.  Only the assign.yml file is actually being used.

There are assign state abbreviations for the view which are being used but
should probably be moved to a view transformer.

The transitions are being used to make choices for the signup forms.

The actual workflow state changes are being made in the controllers.
Only a few which actually change the state.

So the two actual workflow objects are not currently being used by 2016.


text:
import { EOL } from "os";
import log from "npmlog";
import path from "path";

// mocked modules
import writePkg from "write-pkg";
import ChildProcessUtilities from "../src/ChildProcessUtilities";
import FileSystemUtilities from "../src/FileSystemUtilities";

// file under test
import NpmUtilities from "../src/NpmUtilities";

jest.mock("write-pkg");
jest.mock("../src/ChildProcessUtilities");
jest.mock("../src/FileSystemUtilities");

// silence logs
log.level = "silent";

// we stub getExecOpts() in most tests because
// we already have enough tests of getExecOpts()
const nuGetExecOpts = NpmUtilities.getExecOpts;
const resetExecOpts = () => {
  NpmUtilities.getExecOpts = nuGetExecOpts;
};
const stubExecOpts = () => {
  NpmUtilities.getExecOpts = jest.fn(
    // shorthand so we don't have to mess with process.env everywhere
    (directory, registry) => ({ directory, registry })
  );
};

describe("NpmUtilities", () => {
  afterEach(() => jest.resetAllMocks());

  describe(".addDistTag()", () => {
    const directory = "/test/addDistTag";
    const packageName = "foo-pkg";
    const version = "1.0.0";
    const tag = "added-tag";

    beforeEach(stubExecOpts);
    afterEach(resetExecOpts);

    it("adds a dist-tag for a given package@version", () => {
      NpmUtilities.addDistTag(directory, packageName, version, tag);

      const cmd = "npm";
      const args = ["dist-tag", "add", "foo-pkg@1.0.0", "added-tag"];
      const opts = { directory, registry: undefined };
      expect(ChildProcessUtilities.execSync).lastCalledWith(cmd, args, opts);
    });

    it("supports custom registry", () => {
      const registry = "https://custom-registry/add";
      NpmUtilities.addDistTag(directory, packageName, version, tag, registry);

      const cmd = "npm";
      const args = ["dist-tag", "add", "foo-pkg@1.0.0", "added-tag"];
      const opts = { directory, registry };
      expect(ChildProcessUtilities.execSync).lastCalledWith(cmd, args, opts);
    });
  });

  describe(".removeDistTag()", () => {
    const directory = "/test/removeDistTag";
    const packageName = "bar-pkg";
    const tag = "removed-tag";

    beforeEach(stubExecOpts);
    afterEach(resetExecOpts);

    it("removes a dist-tag for a given package", () => {
      NpmUtilities.removeDistTag(directory, packageName, tag);

      const cmd = "npm";
      const args = ["dist-tag", "rm", "bar-pkg", "removed-tag"];
      const opts = { directory, registry: undefined };
      expect(ChildProcessUtilities.execSync).lastCalledWith(cmd, args, opts);
    });

    it("supports custom registry", () => {
      const registry = "https://custom-registry/remove";
      NpmUtilities.removeDistTag(directory, packageName, tag, registry);

      const cmd = "npm";
      const args = ["dist-tag", "rm", "bar-pkg", "removed-tag"];
      const opts = { directory, registry };
      expect(ChildProcessUtilities.execSync).lastCalledWith(cmd, args, opts);
    });
  });

  describe(".checkDistTag()", () => {
    const directory = "/test/checkDistTag";
    const packageName = "baz-pkg";

    beforeEach(stubExecOpts);
    afterEach(resetExecOpts);

    it("tests if a dist-tag for a given package exists", () => {
      ChildProcessUtilities.execSync.mockImplementation(() => ["latest", "target-tag"].join(EOL));

      expect(NpmUtilities.checkDistTag(directory, packageName, "target-tag")).toBe(true);
      expect(NpmUtilities.checkDistTag(directory, packageName, "latest")).toBe(true);
      expect(NpmUtilities.checkDistTag(directory, packageName, "missing")).toBe(false);

      const cmd = "npm";
      const args = ["dist-tag", "ls", "baz-pkg"];
      const opts = { directory, registry: undefined };
      expect(ChildProcessUtilities.execSync).toBeCalledWith(cmd, args, opts);
    });

    it("supports custom registry", () => {
      const registry = "https://custom-registry/check";
      ChildProcessUtilities.execSync.mockImplementation(() => "target-tag");

      expect(NpmUtilities.checkDistTag(directory, packageName, "target-tag", registry)).toBe(true);

      const cmd = "npm";
      const args = ["dist-tag", "ls", "baz-pkg"];
      const opts = { directory, registry };
      expect(ChildProcessUtilities.execSync).lastCalledWith(cmd, args, opts);
    });
  });

  describe(".runScriptInDir()", () => {
    it("runs an npm script in a directory", () => {
      const script = "foo";
      const args = ["--bar", "baz"];
      const directory = "/test/runScriptInDir";
      const callback = () => {};

      NpmUtilities.runScriptInDir(script, args, directory, callback);

      const cmd = "npm";
      const scriptArgs = ["run", "foo", "--bar", "baz"];
      const opts = {
        cwd: directory,
      };
      expect(ChildProcessUtilities.exec).lastCalledWith(cmd, scriptArgs, opts, expect.any(Function));
    });
  });

  describe(".runScriptInPackageStreaming()", () => {
    it("runs an npm script in a package with streaming", () => {
      const script = "foo";
      const args = ["--bar", "baz"];
      const pkg = {
        name: "qux",
        location: "/test/runScriptInPackageStreaming",
      };
      const callback = () => {};

      NpmUtilities.runScriptInPackageStreaming(script, args, pkg, callback);

      expect(ChildProcessUtilities.spawnStreaming).lastCalledWith(
        "npm",
        ["run", "foo", "--bar", "baz"],
        {
          cwd: pkg.location,
        },
        "qux",
        expect.any(Function)
      );
    });
  });

  describe(".publishTaggedInDir()", () => {
    const directory = "/test/publishTaggedInDir";
    const callback = () => {};

    beforeEach(stubExecOpts);
    afterEach(resetExecOpts);

    it("runs npm publish in a directory with --tag support", () => {
      NpmUtilities.publishTaggedInDir("published-tag", directory, undefined, callback);

      const cmd = "npm";
      const args = ["publish", "--tag", "published-tag"];
      const opts = { directory, registry: undefined };
      expect(ChildProcessUtilities.exec).lastCalledWith(cmd, args, opts, expect.any(Function));
    });

    it("trims trailing whitespace in tag parameter", () => {
      NpmUtilities.publishTaggedInDir("trailing-tag  ", directory, callback);

      const actualtag = ChildProcessUtilities.exec.mock.calls[0][1][2];
      expect(actualtag).toBe("trailing-tag");
    });

    it("supports custom registry", () => {
      const registry = "https://custom-registry/publishTaggedInDir";
      NpmUtilities.publishTaggedInDir("published-tag", directory, registry, callback);

      const cmd = "npm";
      const args = ["publish", "--tag", "published-tag"];
      const opts = { directory, registry };
      expect(ChildProcessUtilities.exec).lastCalledWith(cmd, args, opts, expect.any(Function));
    });
  });

  describe(".getExecOpts()", () => {
    const originalEnv = Object.assign({}, process.env);
    const mockEnv = {
      mock_value: 1,
      NODE_ENV: "lerna-test",
    };

    afterEach(() => {
      process.env = originalEnv;
    });

    it("should handle environment variables properly", () => {
      process.env = mockEnv;
      const opts = NpmUtilities.getExecOpts("test_dir", "https://my-secure-registry/npm");
      const want = {
        cwd: "test_dir",
        env: Object.assign({}, mockEnv, {
          npm_config_registry: "https://my-secure-registry/npm"
        })
      };
      expect(opts).toEqual(want);
    });

    it("should handle missing environment variables", () => {
      process.env = mockEnv;
      const opts = NpmUtilities.getExecOpts("test_dir");
      const want = {
        cwd: "test_dir",
      };
      expect(opts).toEqual(want);
    });
  });

  describe(".installInDir()", () => {
    const callbackSuccess = (...args) => args.pop()();

    beforeEach(() => {
      stubExecOpts();
      ChildProcessUtilities.exec.mockImplementation(callbackSuccess);
      FileSystemUtilities.rename.mockImplementation(callbackSuccess);
      writePkg.mockImplementation(() => Promise.resolve());
    });

    afterEach(resetExecOpts);

    it("installs dependencies in targeted directory", (done) => {
      const directory = path.normalize("/test/installInDir");
      const dependencies = [
        "@scoped/caret@^2.0.0",
        "@scoped/exact@2.0.0",
        "caret@^1.0.0",
        "exact@1.0.0",
      ];
      const config = {};

      NpmUtilities.installInDir(directory, dependencies, config, (err) => {
        if (err) return done.fail(err);

        try {
          expect(FileSystemUtilities.rename).lastCalledWith(
            path.join(directory, "package.json"),
            path.join(directory, "package.json.lerna_backup"),
            expect.any(Function),
          );
          expect(FileSystemUtilities.renameSync).lastCalledWith(
            path.join(directory, "package.json.lerna_backup"),
            path.join(directory, "package.json"),
          );
          expect(writePkg).lastCalledWith(
            path.join(directory, "package.json"),
            {
              dependencies: {
                "@scoped/caret": "^2.0.0",
                "@scoped/exact": "2.0.0",
                caret: "^1.0.0",
                exact: "1.0.0",
              },
            },
          );
          expect(ChildProcessUtilities.exec).lastCalledWith("npm", ["install"], {
            directory,
            registry: undefined,
          }, expect.any(Function));

          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });

    it("supports custom registry", (done) => {
      const registry = "https://custom-registry/installInDir";
      const directory = path.normalize("/test/installInDir");
      const dependencies = [
        "@scoped/tagged@next",
        "tagged@next",
      ];
      const config = {
        registry,
      };

      NpmUtilities.installInDir(directory, dependencies, config, (err) => {
        if (err) return done.fail(err);

        try {
          expect(writePkg.mock.calls[0][1]).toEqual(
            {
              dependencies: {
                "@scoped/tagged": "next",
                tagged: "next",
              },
            },
          );
          expect(ChildProcessUtilities.exec.mock.calls[0][2]).toMatchObject({
            registry,
          });

          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });

    it("supports npm install --global-style", (done) => {
      const directory = path.normalize("/test/installInDir");
      const dependencies = [
        "@scoped/foo@latest",
        "foo@latest",
      ];
      const config = {};
      const npmGlobalStyle = true;

      NpmUtilities.installInDir(directory, dependencies, config, npmGlobalStyle, (err) => {
        if (err) return done.fail(err);

        try {
          expect(writePkg.mock.calls[0][1]).toEqual(
            {
              dependencies: {
                "@scoped/foo": "latest",
                foo: "latest",
              },
            },
          );
          expect(ChildProcessUtilities.exec).lastCalledWith(
            "npm",
            ["install", "--global-style"],
            {
              directory,
              registry: undefined,
            },
            expect.any(Function)
          );

          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });

    it("supports custom npmClient", (done) => {
      const directory = path.normalize("/test/installInDir");
      const dependencies = [
        "@scoped/something@github:foo/bar",
        "something@github:foo/foo",
      ];
      const config = {
        npmClient: "yarn",
        mutex: "network:12345",
      };

      NpmUtilities.installInDir(directory, dependencies, config, (err) => {
        if (err) return done.fail(err);

        try {
          expect(writePkg.mock.calls[0][1]).toEqual(
            {
              dependencies: {
                "@scoped/something": "github:foo/bar",
                something: "github:foo/foo",
              },
            },
          );
          expect(ChildProcessUtilities.exec).lastCalledWith(
            "yarn",
            ["install", "--mutex", "network:12345", "--non-interactive"],
            {
              directory,
              registry: undefined,
            },
            expect.any(Function)
          );

          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });

    it("overrides custom npmClient when using global style", (done) => {
      const directory = path.normalize("/test/installInDir");
      const dependencies = [
        "@scoped/something@github:foo/bar",
        "something@github:foo/foo",
      ];
      const config = {
        npmClient: "yarn",
        mutex: "network:12345",
      };
      const npmGlobalStyle = true;

      NpmUtilities.installInDir(directory, dependencies, config, npmGlobalStyle, (err) => {
        if (err) return done.fail(err);

        try {
          expect(writePkg.mock.calls[0][1]).toEqual(
            {
              dependencies: {
                "@scoped/something": "github:foo/bar",
                something: "github:foo/foo",
              },
            },
          );
          expect(ChildProcessUtilities.exec).lastCalledWith(
            "npm",
            ["install", "--global-style"],
            {
              directory,
              registry: undefined,
            },
            expect.any(Function)
          );

          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });

    it("finishes early when no dependencies exist", (done) => {
      const directory = path.normalize("/test/installInDir");
      const dependencies = [];
      const config = {};

      NpmUtilities.installInDir(directory, dependencies, config, (err) => {
        if (err) return done.fail(err);
        try {
          expect(NpmUtilities.getExecOpts).not.toBeCalled();
          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });

    it("defaults temporary dependency versions to '*'", (done) => {
      const directory = path.normalize("/test/installInDir");
      const dependencies = [
        "noversion",
        "@scoped/noversion", // sorted by write-pkg
      ];
      const config = {};

      NpmUtilities.installInDir(directory, dependencies, config, (err) => {
        if (err) return done.fail(err);

        try {
          expect(writePkg.mock.calls[0][1]).toEqual(
            {
              dependencies: {
                "@scoped/noversion": "*",
                noversion: "*",
              },
            },
          );

          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });

    it("passes rename error to callback", (done) => {
      const directory = path.normalize("/test/installInDir/renameError");
      const dependencies = [
        "I'm just here so we don't exit early",
      ];
      const config = {};

      FileSystemUtilities.rename.mockImplementation((from, to, cb) => {
        return cb(new Error("Unable to rename file"));
      });

      NpmUtilities.installInDir(directory, dependencies, config, (err) => {
        try {
          expect(err.message).toBe("Unable to rename file");

          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });

    it("cleans up synchronously after writeFile error", (done) => {
      const directory = path.normalize("/test/installInDir/writeError");
      const dependencies = [
        "I'm just here so we don't exit early",
      ];
      const config = {};

      writePkg.mockImplementation(() => {
        return Promise.reject(new Error("Unable to write file"));
      });

      NpmUtilities.installInDir(directory, dependencies, config, (err) => {
        try {
          expect(err.message).toBe("Unable to write file");

          expect(FileSystemUtilities.renameSync).lastCalledWith(
            path.join(directory, "package.json.lerna_backup"),
            path.join(directory, "package.json"),
          );

          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });

    it("cleans up synchronously after client install error", (done) => {
      const directory = path.normalize("/test/installInDir/clientError");
      const dependencies = [
        "I'm just here so we don't exit early",
      ];
      const config = {};

      ChildProcessUtilities.exec.mockImplementation((client, args, opts, cb) => {
        return cb(new Error("Unable to install dependency"));
      });

      NpmUtilities.installInDir(directory, dependencies, config, (err) => {
        try {
          expect(err.message).toBe("Unable to install dependency");

          expect(FileSystemUtilities.renameSync).lastCalledWith(
            path.join(directory, "package.json.lerna_backup"),
            path.join(directory, "package.json"),
          );

          done();
        } catch (ex) {
          done.fail(ex);
        }
      });
    });
  });
});


text:
package sun.jvm.hotspot.ci;

import java.io.*;
import java.util.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.runtime.*;
import sun.jvm.hotspot.oops.*;
import sun.jvm.hotspot.types.*;

public class ciMethodData extends ciMetadata {
  static {
    VM.registerVMInitializedObserver(new Observer() {
        public void update(Observable o, Object data) {
          initialize(VM.getVM().getTypeDataBase());
        }
      });
  }

  private static synchronized void initialize(TypeDataBase db) throws WrongTypeException {
    Type type      = db.lookupType("ciMethodData");
    origField = type.getAddressField("_orig");
    currentMileageField = new CIntField(type.getCIntegerField("_current_mileage"), 0);
    argReturnedField = new CIntField(type.getCIntegerField("_arg_returned"), 0);
    argStackField = new CIntField(type.getCIntegerField("_arg_stack"), 0);
    argLocalField = new CIntField(type.getCIntegerField("_arg_local"), 0);
    eflagsField = new CIntField(type.getCIntegerField("_eflags"), 0);
    hintDiField = new CIntField(type.getCIntegerField("_hint_di"), 0);
    currentMileageField = new CIntField(type.getCIntegerField("_current_mileage"), 0);
    dataField = type.getAddressField("_data");
    extraDataSizeField = new CIntField(type.getCIntegerField("_extra_data_size"), 0);
    dataSizeField = new CIntField(type.getCIntegerField("_data_size"), 0);
    stateField = new CIntField(type.getCIntegerField("_state"), 0);
    sizeofMethodDataOopDesc = (int)db.lookupType("MethodData").getSize();;
  }

  private static AddressField origField;
  private static CIntField currentMileageField;
  private static CIntField argReturnedField;
  private static CIntField argStackField;
  private static CIntField argLocalField;
  private static CIntField eflagsField;
  private static CIntField hintDiField;
  private static AddressField dataField;
  private static CIntField extraDataSizeField;
  private static CIntField dataSizeField;
  private static CIntField stateField;
  private static int sizeofMethodDataOopDesc;

  public ciMethodData(Address addr) {
    super(addr);
  }

  private byte[] fetchDataAt(Address base, long size) {
    byte[] result = new byte[(int)size];
    for (int i = 0; i < size; i++) {
      result[i] = base.getJByteAt(i);
    }
    return result;
  }

  public byte[] orig() {
    // fetch the orig MethodData data between header and dataSize
    Address base = getAddress().addOffsetTo(origField.getOffset());
    byte[] result = new byte[MethodData.sizeofMethodDataOopDesc];
    for (int i = 0; i < MethodData.sizeofMethodDataOopDesc; i++) {
      result[i] = base.getJByteAt(i);
    }
    return result;
  }

  public  long[] data() {
    // Read the data as an array of intptr_t elements
    Address base = dataField.getValue(getAddress());
    int elements = dataSize() / MethodData.cellSize;
    long[] result = new long[elements];
    for (int i = 0; i < elements; i++) {
      Address value = base.getAddressAt(i * MethodData.cellSize);
      if (value != null) {
        result[i] = value.minus(null);
      }
    }
    return result;
  }

  int dataSize() {
    return (int)dataSizeField.getValue(getAddress());
  }

  int state() {
    return (int)stateField.getValue(getAddress());
  }

  int currentMileage() {
    return (int)currentMileageField.getValue(getAddress());
  }

  boolean outOfBounds(int dataIndex) {
    return dataIndex >= dataSize();
  }

  ProfileData dataAt(int dataIndex) {
    if (outOfBounds(dataIndex)) {
      return null;
    }
    DataLayout dataLayout = new DataLayout(dataField.getValue(getAddress()), dataIndex);

    switch (dataLayout.tag()) {
    case DataLayout.noTag:
    default:
      throw new InternalError();
    case DataLayout.bitDataTag:
      return new BitData(dataLayout);
    case DataLayout.counterDataTag:
      return new CounterData(dataLayout);
    case DataLayout.jumpDataTag:
      return new JumpData(dataLayout);
    case DataLayout.receiverTypeDataTag:
      return new ciReceiverTypeData(dataLayout);
    case DataLayout.virtualCallDataTag:
      return new ciVirtualCallData(dataLayout);
    case DataLayout.retDataTag:
      return new RetData(dataLayout);
    case DataLayout.branchDataTag:
      return new BranchData(dataLayout);
    case DataLayout.multiBranchDataTag:
      return new MultiBranchData(dataLayout);
    }
  }

  int dpToDi(int dp) {
    return dp;
  }

  int firstDi() { return 0; }
  ProfileData firstData() { return dataAt(firstDi()); }
  ProfileData nextData(ProfileData current) {
    int currentIndex = dpToDi(current.dp());
    int nextIndex = currentIndex + current.sizeInBytes();
    return dataAt(nextIndex);
  }
  boolean isValid(ProfileData current) { return current != null; }

  public void printDataOn(PrintStream st) {
    ProfileData data = firstData();
    for ( ; isValid(data); data = nextData(data)) {
      st.print(dpToDi(data.dp()));
      st.print(" ");
      // st->fillTo(6);
      data.printDataOn(st);
    }
  }

  public void dumpReplayData(PrintStream out) {
    MethodData mdo = (MethodData)getMetadata();
    Method method = mdo.getMethod();
    Klass holder = method.getMethodHolder();
    out.print("ciMethodData " +
              holder.getName().asString() + " " +
              OopUtilities.escapeString(method.getName().asString()) + " " +
              method.getSignature().asString() + " " +
              state() + " " + currentMileage());
    byte[] orig = orig();
    out.print(" orig " + orig.length);
    for (int i = 0; i < orig.length; i++) {
      out.print(" " + (orig[i] & 0xff));
    }

    long[] data = data();
    out.print(" data " +  data.length);
    for (int i = 0; i < data.length; i++) {
      out.print(" 0x" + Long.toHexString(data[i]));
    }
    int count = 0;
    for (int round = 0; round < 2; round++) {
      if (round == 1) out.print(" oops " + count);
      ProfileData pdata = firstData();
      for ( ; isValid(pdata); pdata = nextData(pdata)) {
        if (pdata instanceof ciReceiverTypeData) {
          ciReceiverTypeData vdata = (ciReceiverTypeData)pdata;
          for (int i = 0; i < vdata.rowLimit(); i++) {
            ciKlass k = vdata.receiverAt(i);
            if (k != null) {
              if (round == 0) count++;
              else out.print(" " + ((vdata.dp() + vdata.cellOffset(vdata.receiverCellIndex(i))) / MethodData.cellSize) + " " + k.name());
            }
          }
        } else if (pdata instanceof ciVirtualCallData) {
          ciVirtualCallData vdata = (ciVirtualCallData)pdata;
          for (int i = 0; i < vdata.rowLimit(); i++) {
            ciKlass k = vdata.receiverAt(i);
            if (k != null) {
              if (round == 0) count++;
              else out.print(" " + ((vdata.dp() + vdata.cellOffset(vdata.receiverCellIndex(i))) / MethodData.cellSize + " " + k.name()));
            }
          }
        }
      }
    }
    out.println();
  }
}


text:
package org.uberfire.annotations.processors.facades;

import java.util.Map;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;

import org.uberfire.annotations.processors.GeneratorUtils;

/**
 * A collection of type names in the UberFire Client API module.
 * Due to a bug in Eclipse annotation processor dependencies, we refer to all UberFire type names using Strings,
 * Elements, and TypeMirrors. We cannot refer to the annotation types as types themselves.
 */
public class ClientAPIModule {

    public static final String IDENTIFIER = "identifier";
    public static final String OWNING_PERSPECTIVE = "owningPerspective";
    public static final String IS_DEFAULT = "isDefault";
    public static final String IS_TRANSIENT = "isTransient";
    public static final String IS_TEMPLATE = "isTemplate";
    public static final String IS_ENABLED = "isEnabled";
    public static final String VALUE = "value";

    private ClientAPIModule() {
    }

    public static final String workbenchSplashScreen = "org.uberfire.client.annotations.WorkbenchSplashScreen";
    public static final String workbenchPerspective = "org.uberfire.client.annotations.WorkbenchPerspective";
    public static final String workbenchPopup = "org.uberfire.client.annotations.WorkbenchPopup";
    public static final String workbenchScreen = "org.uberfire.client.annotations.WorkbenchScreen";
    public static final String workbenchContext = "org.uberfire.client.annotations.WorkbenchContext";
    public static final String workbenchEditor = "org.uberfire.client.annotations.WorkbenchEditor";
    public static final String defaultPosition = "org.uberfire.client.annotations.DefaultPosition";
    public static final String workbenchPartTitle = "org.uberfire.client.annotations.WorkbenchPartTitle";
    public static final String workbenchContextId = "org.uberfire.client.annotations.WorkbenchContextId";
    public static final String workbenchPartTitleDecoration = "org.uberfire.client.annotations.WorkbenchPartTitleDecoration";
    public static final String workbenchPartView = "org.uberfire.client.annotations.WorkbenchPartView";
    public static final String workbenchMenu = "org.uberfire.client.annotations.WorkbenchMenu";
    public static final String workbenchToolBar = "org.uberfire.client.annotations.WorkbenchToolBar";
    public static final String perspective = "org.uberfire.client.annotations.Perspective";
    public static final String splashFilter = "org.uberfire.client.annotations.SplashFilter";
    public static final String splashBodyHeight = "org.uberfire.client.annotations.SplashBodyHeight";
    public static final String intercept = "org.uberfire.client.annotations.Intercept";
    public static final String workbenchPanel = "org.uberfire.client.annotations.WorkbenchPanel";

    public static String getWorkbenchScreenClass() {
        return workbenchScreen;
    }

    public static String getSplashFilterClass() {
        return splashFilter;
    }

    public static String getSplashBodyHeightClass() {
        return splashBodyHeight;
    }

    public static String getInterceptClass() {
        return intercept;
    }

    public static String getPerspectiveClass() {
        return perspective;
    }

    public static String getWorkbenchToolBarClass() {
        return workbenchToolBar;
    }

    public static String getWorkbenchMenuClass() {
        return workbenchMenu;
    }

    public static String getWorkbenchPartViewClass() {
        return workbenchPartView;
    }

    public static String getWorkbenchPartTitleDecorationsClass() {
        return workbenchPartTitleDecoration;
    }

    public static String getWorkbenchContextIdClass() {
        return workbenchContextId;
    }

    public static String getWorkbenchPartTitleClass() {
        return workbenchPartTitle;
    }

    public static String getDefaultPositionClass() {
        return defaultPosition;
    }

    public static String getWorkbenchContextClass() {
        return workbenchContext;
    }

    public static String getWorkbenchEditorClass() {
        return workbenchEditor;
    }

    public static String getWorkbenchPopupClass() {
        return workbenchPopup;
    }

    public static String getWorkbenchSplashScreenClass() {
        return workbenchSplashScreen;
    }

    public static String getWorkbenchPerspectiveClass() {
        return workbenchPerspective;
    }

    public static String getWorkbenchPanel() {
        return workbenchPanel;
    }

    /**
     * Returns the value of the String-valued Annotation parameter on the given type, ignoring any default value that
     * exists on the annotation. Returns an empty string if the type lacks the given annotation, or if the annotation
     * lacks the given parameter.
     */
    private static String getAnnotationStringParam( TypeElement target,
                                                    String annotationClassName,
                                                    String annotationParamName ) {
        AnnotationValue paramValue = getAnnotationParamValue( target, annotationClassName, annotationParamName );
        if ( paramValue == null ) {
            return "";
        }
        return paramValue.getValue().toString();
    }

    /**
     * Returns the value of the Boolean-valued Annotation parameter on the given type, ignoring any default value that
     * exists on the annotation. Returns false if the type lacks the given annotation, or if the annotation
     * lacks the given parameter.
     */
    private static Boolean getAnnotationBooleanParam( TypeElement target,
                                                      String annotationClassName,
                                                      String annotationParamName ) {
        AnnotationValue paramValue = getAnnotationParamValue( target, annotationClassName, annotationParamName );
        if ( paramValue == null ) {
            return null;
        }
        return Boolean.parseBoolean( paramValue.getValue().toString() );
    }

    /**
     * Returns the value associated with the given parameter of the given annotation on the given class element,
     * ignoring any default value that exists on the annotation. Returns null if the type lacks the given annotation, or
     * if the annotation lacks the given parameter.
     */
    private static AnnotationValue getAnnotationParamValue( TypeElement target,
                                                            String annotationClassName,
                                                            String annotationName ) {
        for ( final AnnotationMirror am : target.getAnnotationMirrors() ) {
            if ( annotationClassName.equals( am.getAnnotationType().toString() ) ) {
                for ( Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : am.getElementValues().entrySet() ) {
                    if ( annotationName.equals( entry.getKey().getSimpleName().toString() ) ) {
                        return entry.getValue();
                    }
                }
            }
        }
        return null;
    }

    public static Boolean getWbPerspectiveScreenIsDefaultValueOnClass( TypeElement classElement ) {
        String bool = ( getAnnotationStringParam( classElement, workbenchPerspective, IS_DEFAULT ) );
        return Boolean.valueOf( bool );
    }

    public static Boolean getWbPerspectiveScreenIsTransientValueOnClass( TypeElement classElement ) {
        String bool = ( getAnnotationStringParam( classElement, workbenchPerspective, IS_TRANSIENT ) );

        // XXX this is non-ideal because it restates the default of the isTransient property
        // we should use the getAnnotationValueWithDefaults method in this entire class so
        // we aren't redundantly declaring defaults here
        if ( bool.isEmpty() ) {
            return true;
        }

        return Boolean.valueOf( bool );
    }

    public static String getWbPerspectiveScreenIdentifierValueOnClass( TypeElement classElement ) {
        return getAnnotationStringParam( classElement, workbenchPerspective, IDENTIFIER );
    }

    public static String getWbPopupScreenIdentifierValueOnClass( TypeElement classElement ) {
        return getAnnotationStringParam( classElement, workbenchPopup, IDENTIFIER );
    }

    public static String getWbSplashScreenIdentifierValueOnClass( TypeElement classElement ) {
        return getAnnotationStringParam( classElement, workbenchSplashScreen, IDENTIFIER );
    }

    public static boolean getWbSplashScreenIsEnabledValueOnClass( TypeElement classElement ) {
        final Boolean bool = getAnnotationBooleanParam( classElement, workbenchSplashScreen, IS_ENABLED );
        return bool == null || bool;
    }

    public static String getWbScreenIdentifierValueOnClass( TypeElement classElement ) {
        return getAnnotationStringParam( classElement, workbenchScreen, IDENTIFIER );
    }

    public static String getWbContextIdentifierValueOnClass( TypeElement classElement ) {
        return getAnnotationStringParam( classElement, workbenchContext, IDENTIFIER );
    }

    public static boolean isATemplate( Elements elementUtils,
                                       Element element ) {
        return GeneratorUtils.getAnnotation( elementUtils, element, workbenchPanel ) != null;
    }
}


text:
using Scalider.Security.Password;
using PVR = Microsoft.AspNetCore.Identity.PasswordVerificationResult;

namespace Scalider.AspNetCore.Identity
{

    internal class PasswordHasherImpl<TUser> : Microsoft.AspNetCore.Identity.IPasswordHasher<TUser>
        where TUser : class
    {

        private readonly IPasswordHasher _innerPasswordHasher;

        /// <summary>
        /// Initializes a new instance of the <see cref="PasswordHasherImpl{TUser}"/> class.
        /// </summary>
        /// <param name="innerPasswordHasher"></param>
        public PasswordHasherImpl(IPasswordHasher innerPasswordHasher)
        {
            _innerPasswordHasher = innerPasswordHasher;
        }

        /// <inheritdoc />
        public string HashPassword(TUser user, string password)
        {
            Check.NotNull(password, nameof(password));
            return _innerPasswordHasher is IPasswordHasher<TUser> genericPasswordHasher
                ? genericPasswordHasher.HashPassword(user, password)
                : _innerPasswordHasher.HashPassword(password);
        }

        /// <inheritdoc />
        public PVR VerifyHashedPassword(TUser user, string hashedPassword,
            string providedPassword)
        {
            Check.NotNull(providedPassword, nameof(providedPassword));
            Check.NotNull(hashedPassword, nameof(hashedPassword));

            // Validate the provided password
            var result = _innerPasswordHasher is IPasswordHasher<TUser> genericPasswordHasher
                ? genericPasswordHasher.VerifyHashedPassword(user, providedPassword, hashedPassword)
                : _innerPasswordHasher.VerifyHashedPassword(providedPassword, hashedPassword);

            // Done
            return result switch
            {
                PasswordVerificationResult.Failed              => PVR.Failed,
                PasswordVerificationResult.Success             => PVR.Success,
                PasswordVerificationResult.SuccessRehashNeeded => PVR.SuccessRehashNeeded,
                _                                              => PVR.Failed
            };
        }

    }

}


text:
<?php
require_once "vendor/autoload.php";

use PHPUnit\Framework\TestCase;
use Gru\Processamento;

/**
*
*/
class ProcessamentoTest extends TestCase
{

	public function testUnidadeGestora()
	{
		$processamento = new Processamento('158150');
		$pagamento = $processamento->pagamento();
		$this->assertEquals($pagamento->unidade_gestora, '158150');

	}

	public function testData()
	{
		$processamento = new Processamento('7777777777720161018I201610171581502642621581502642628900181020160000000000009552300000000007120000291141020160000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000100104331120161410201610000526615320200000000000000000001E514F872F46D09C4');
		$pagamento = $processamento->pagamento();
		$this->assertEquals($pagamento->registro, '777777777');
		$this->assertEquals($pagamento->data, '14102016');
		$this->assertEquals($pagamento->valor, '2000');
		$this->assertEquals($pagamento->cpf, '05266153202');

	}

}


text:
require_relative '../../spec_helper'
require_relative 'fixtures/classes'

describe "Kernel.throw" do
  it "transfers control to the end of the active catch block waiting for symbol" do
    catch(:blah) do
      :value
      throw :blah
      fail("throw didn't transfer the control")
    end.should be_nil
  end

  it "transfers control to the innermost catch block waiting for the same symbol" do
    one = two = three = 0
    catch :duplicate do
      catch :duplicate do
        catch :duplicate do
          one = 1
          throw :duplicate
        end
        two = 2
        throw :duplicate
      end
      three = 3
      throw :duplicate
    end
    [one, two, three].should == [1, 2, 3]
  end

  it "sets the return value of the catch block to nil by default" do
    res = catch :blah do
      throw :blah
    end
    res.should == nil
  end

  it "sets the return value of the catch block to a value specified as second parameter" do
    res = catch :blah do
      throw :blah, :return_value
    end
    res.should == :return_value
  end

  it "raises an ArgumentError if there is no catch block for the symbol" do
    lambda { throw :blah }.should raise_error(ArgumentError)
  end

  it "raises an UncaughtThrowError if there is no catch block for the symbol" do
    lambda { throw :blah }.should raise_error(UncaughtThrowError)
  end

  it "raises ArgumentError if 3 or more arguments provided" do
    lambda {
      catch :blah do
        throw :blah, :return_value, 2
      end
    }.should raise_error(ArgumentError)

    lambda {
      catch :blah do
        throw :blah, :return_value, 2, 3, 4, 5
      end
    }.should raise_error(ArgumentError)
  end

  it "can throw an object" do
    lambda {
      obj = Object.new
      catch obj do
        throw obj
      end
    }.should_not raise_error(NameError)
  end
end

describe "Kernel#throw" do
  it "is a private method" do
    Kernel.should have_private_instance_method(:throw)
  end
end


text:
  import _ from 'lodash';

  function component() {
    var element = document.createElement('div');
    var button = document.createElement('button');
    var br = document.createElement('br');

    button.innerHTML = 'Click me and look at the console!';
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    element.appendChild(br);
    element.appendChild(button);

    // Note that because a network request is involved, some indication
    // of loading would need to be shown in a production-level site/app.
    button.onclick = e => import(/* webpackChunkName: "print" */ './print').then(module => {
      var print = module.default;

      print();
    });

    return element;
  }

  document.body.appendChild(component());


text:
@interface MCLVerifyLoginView ()

@property (strong, nonatomic) MCLThemeManager *themeManager;

@end

@implementation MCLVerifyLoginView

#pragma mark - Initializers

- (instancetype)initWithThemeManager:(MCLThemeManager *)themeManager
{
    self.themeManager = themeManager;
    self.frame = CGRectMake(0, 0, 200, 44);

    self = [super init];
    if (!self) return nil;

    [self configureSubviews];

    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)configureSubviews
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(themeChanged:)
                                                 name:MCLThemeChangedNotification
                                               object:nil];

    self.titleLabel.font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
    self.backgroundColor = [UIColor clearColor];
    self.enabled = NO;
    [self themeChanged:nil];
}

#pragma mark - Public

- (void)loginStatusWithUsername:(NSString *)username
{
    self.enabled = NO;
    [self setTitle:[NSString stringWithFormat:NSLocalizedString(@"Welcome %@", nil), username] forState:UIControlStateNormal];
    [self themeChanged:nil];
}

- (void)loginStatusNoLogin
{
    self.enabled = NO;
    [self setTitle:NSLocalizedString(@"You are not logged in", nil) forState:UIControlStateNormal];
    [self themeChanged:nil];
}

- (void)setNumberOfDrafts:(NSNumber *)numberOfDrafts
{
    if ([numberOfDrafts intValue] == 0) {
        return;
    }

    self.enabled = YES;
    NSString *title = [numberOfDrafts intValue] > 1
        ? NSLocalizedString(@"multiple_drafts", nil)
        : NSLocalizedString(@"one_draft", nil);
    [self setTitle:[NSString stringWithFormat:title, numberOfDrafts] forState:UIControlStateNormal];
    [self themeChanged:nil];
}

- (void)setNumberOfDrafts:(NSNumber *)numberOfDrafts withDelay:(double)delayInSeconds
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
        [self setNumberOfDrafts:numberOfDrafts];
    });
}

#pragma mark - Notifications

- (void)themeChanged:(NSNotification *)notification
{
    UIColor *titleColor = self.enabled
        ? [self.themeManager.currentTheme tintColor]
        : [self.themeManager.currentTheme textColor];
    [self setTitleColor:titleColor forState:UIControlStateNormal];
    [self sizeToFit];
}

@end


text:
/****************************************************************************
 * DNS resolver code header file.
 *
 *   Copyright (C) 2007-2009, 2011-2012, 2014-2015 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Inspired by/based on uIP logic by Adam Dunkels:
 *
 *   Copyright (c) 2002-2003, Adam Dunkels. All rights reserved.
 *   Author Adam Dunkels <adam@dunkels.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @defgroup DNS_ADD_NAMESERVER dns_add_nameserver
 * @ingroup DNS
 * @{
 */

/**
 * @file dns.h
 * @brief DNS client API
 */

#ifndef __INCLUDE_NET_DNS_H
#define __INCLUDE_NET_DNS_H

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#include <sys/socket.h>
#include <netinet/in.h>

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/
/* DNS classes */

#define DNS_CLASS_IN                1	/* RFC 1035 Internet */
#define DNS_CLASS CH                3	/* N/A      Chaos */
#define DNS_CLASS_HS                4	/* N/A      Hesiod */
#define DNS_CLASS_QNONE           254	/* RFC 2136 QCLASS NONE */
#define DNS_CLASS_QANY            255	/* RFC 1035 QCLASS ANY */

/* DNS resource record types */

#define DNS_RECTYPE_A                1	/* RFC 1035 IPv4 ddress record */
#define DNS_RECTYPE_AAAA            28	/* RFC 3596 IPv6 address record */
#define DNS_RECTYPE_AFSDB           18	/* RFC 1183 AFS database record */
#define DNS_RECTYPE_APL             42	/* RFC 3123 Address Prefix List */
#define DNS_RECTYPE_CAA            257	/* RFC 6844 Certification Authority Authorization */
#define DNS_RECTYPE_CDNSKEY         60	/* RFC 7344 Child DNSKEY */
#define DNS_RECTYPE_CDS             59	/* RFC 7344 Child DS */
#define DNS_RECTYPE_CERT            37	/* RFC 4398 Certificate record */
#define DNS_RECTYPE_CNAME            5	/* RFC 1035 Canonical name record */
#define DNS_RECTYPE_DHCID           49	/* RFC 4701 DHCP identifier */
#define DNS_RECTYPE_DLV          32769	/* RFC 4431 DNSSEC Lookaside Validation record */
#define DNS_RECTYPE_DNAME           39	/* RFC 2672 Delegation Name */
#define DNS_RECTYPE_DNSKEY          48	/* RFC 4034 DNS Key record */
#define DNS_RECTYPE_DS              43	/* RFC 4034 Delegation signer */
#define DNS_RECTYPE_HIP             55	/* RFC 5205 Host Identity Protocol */
#define DNS_RECTYPE_IPSECKEY        45	/* RFC 4025 IPsec Key */
#define DNS_RECTYPE_KEY             25	/* RFC 2535 and RFC 2930 Key record */
#define DNS_RECTYPE_KX              36	/* RFC 2230 Key eXchanger record */
#define DNS_RECTYPE_LOC             29	/* RFC 1876 Location record */
#define DNS_RECTYPE_MX              15	/* RFC 1035 Mail exchange record */
#define DNS_RECTYPE_NAPTR           35	/* RFC 3403 Naming Authority Pointer */
#define DNS_RECTYPE_NS               2	/* RFC 1035 Name server record */
#define DNS_RECTYPE_NSEC            47	/* RFC 4034 Next-Secure record */
#define DNS_RECTYPE_NSEC3           50	/* RFC 5155 NSEC record version 3 */
#define DNS_RECTYPE_NSEC3PARAM      51	/* RFC 5155 NSEC3 parameters */
#define DNS_RECTYPE_PTR             12	/* RFC 1035 Pointer record */
#define DNS_RECTYPE_RRSIG           46	/* RFC 4034 DNSSEC signature */
#define DNS_RECTYPE_RP              17	/* RFC 1183 Responsible person */
#define DNS_RECTYPE_SIG             24	/* RFC 2535 Signature */
#define DNS_RECTYPE_SOA              6	/* RFC 1035 and RFC 2308 Start of [a zone of] authority record */
#define DNS_RECTYPE_SRV             33	/* RFC 2782 Service locator */
#define DNS_RECTYPE_SSHFP           44	/* RFC 4255 SSH Public Key Fingerprint */
#define DNS_RECTYPE_TA           32768	/* N/A DNSSEC Trust Authorities */
#define DNS_RECTYPE_TKEY           249	/* RFC 2930 Secret key record */
#define DNS_RECTYPE_TLSA            52	/* RFC 6698 TLSA certificate association */
#define DNS_RECTYPE_TSIG           250	/* RFC 2845 Transaction Signature */
#define DNS_RECTYPE_TXT             16	/* RFC 1035[1] Text record */

#define DNS_RECTYPE_ALL            255	/* RFC 1035 All cached records */
#define DNS_RECTYPE_AXFR           252	/* RFC 1035 Authoritative Zone Transfer */
#define DNS_RECTYPE_IXFR           251	/* RFC 1996 Incremental Zone Transfer */
#define DNS_RECTYPE_OPT             41	/* RFC 6891 Option  */

/* Flag1 bit definitions */

#define DNS_FLAG1_RESPONSE        0x80
#define DNS_FLAG1_OPCODE_STATUS   0x10
#define DNS_FLAG1_OPCODE_INVERSE  0x08
#define DNS_FLAG1_OPCODE_STANDARD 0x00
#define DNS_FLAG1_AUTHORATIVE     0x04
#define DNS_FLAG1_TRUNC           0x02
#define DNS_FLAG1_RD              0x01

/* Flag2 bit definitions */

#define DNS_FLAG2_RA              0x80
#define DNS_FLAG2_ERR_MASK        0x0f
#define DNS_FLAG2_ERR_NONE        0x00
#define DNS_FLAG2_ERR_NAME        0x03

/** Default DNS server port number */

#define DNS_DEFAULT_PORT          53

/****************************************************************************
 * Public Type Definitions
 ****************************************************************************/

/** The DNS message header */

struct dns_header_s {
	uint16_t id;
	uint8_t flags1;
	uint8_t flags2;
	uint16_t numquestions;
	uint16_t numanswers;
	uint16_t numauthrr;
	uint16_t numextrarr;
};

/** The DNS answer message structure */

struct dns_answer_s {
	uint16_t type;
	uint16_t class;
	uint16_t ttl[2];
	uint16_t len;

	union {
#ifdef CONFIG_NET_IPv4
		struct in_addr ipv4;
#endif
#ifdef CONFIG_NET_IPv6
		struct in6_addr ipv6;
#endif
	} u;
};

/** The type of the callback from dns_foreach_nameserver() */

typedef CODE int (*dns_callback_t)(FAR void *arg, FAR struct sockaddr *addr, FAR socklen_t addrlen);

/****************************************************************************
 * Public Function Prototypes
 ****************************************************************************/

#undef EXTERN
#if defined(__cplusplus)
#define EXTERN extern "C"
extern "C" {
#else
#define EXTERN extern
#endif

/****************************************************************************
 * Name: dns_add_nameserver
 *
 * Description:
 *   Configure a DNS server to use for queries.  Set the port number to zero
 *   to use the default DNS server port.
 *
 ****************************************************************************/
/**
 * @brief Configure a DNS server to use for queries.  Set the port number to zero  to use the default DNS server port.
 * @param[in] addr struct sockaddr, socket address
 * @param[in] addrlen length of socket structure
 * @return On success, OK is returned. On failures, returns error according to errno.h
*/
int dns_add_nameserver(FAR const struct sockaddr *addr, socklen_t addrlen);

/****************************************************************************
 * Name: dns_del_nameserver
 *
 * Description:
 *   Remove a DNS server so it is no longer available for further use.
 *
 ****************************************************************************/
/* REVISIT: Not implemented */

/****************************************************************************
 * Name: dns_foreach_nameserver
 *
 * Description:
 *   Traverse each nameserver entry in the resolv.conf file and perform the
 *   the provided callback.
 *
 ****************************************************************************/

int dns_foreach_nameserver(dns_callback_t callback, FAR void *arg);

#undef EXTERN
#if defined(__cplusplus)
}
#endif

#endif							/* __INCLUDE_NET_DNS_H */
/** @} */


text:
var util = require('./util')
var ClientComm = require('./clientcomm')

module.exports = Comm

// Local emit function
var debug = util.debug
var emit = util.emit
var send = util.send

// Comm definition
function Comm(socket, opts) {
    if (!(this instanceof Comm))
        return new Comm(socket)

    opts = opts || {}

    var self = this
    var clients = this.clients = {}
    var handles = this.handles = {}
    this.socket = socket

    var fallback = this.fallback = opts.fallback || true

    socket.on('connection',
    handles.open = function(socket) {
        var comm = new ClientComm(socket)
        clients[comm.id] = comm

        socket.on('message', handles.message.bind(null, comm))
        socket.on('close', handles.close.bind(null, comm))

        emit.call(self, 'connect', comm)
    })

    handles.connect = function(comm, info) {
        info.fallback = fallback
        comm.info = info

        for (var id in clients) {
            if (id != comm.id) {
                send.call(clients[id].socket, 'connect', comm.id, info)
                send.call(comm.socket, 'connect', id, clients[id].info)
            }
        }
    }

    handles.message = function(comm, data) {
        debug('recv %s', data)
        var args = JSON.parse(data)
        var handler = handles[args[0]]
        args[0] = comm

        handler.apply(null, args)
    }

    handles['data:server'] = function(comm, args) {
        emit.apply(comm, args)
    }

    handles.data = function(comm, ids, args) {
        var name = 'data:' + comm.id

        for (var i = 0; i < ids.length; i++) {
            send.call(clients[ids[i]].socket, name, args)
        }
    }

    handles.close = function(comm) {
        delete clients[comm.id]

        for (var k in clients)
            send.call(clients[k].socket, 'disconnect', comm.id)
    }

    socket.on('error', emit.bind(this, 'error'))
}

// Inherit from Emitter
Comm.prototype = Object.create(util.Emitter.prototype)

Comm.prototype.emit = function() {
    var clients = this.clients
    var args = Array.prototype.slice.call(arguments)

    for (var k in clients) {
        send.call(clients[k].socket, 'data:server', args)
    }
}


text:
#ifndef _MItGeometry
#define _MItGeometry
//-
// ===========================================================================
// Copyright 2016 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
// ===========================================================================
//+
//
// CLASS:    MItGeometry
//
// ****************************************************************************

#if defined __cplusplus

// ****************************************************************************
// INCLUDED HEADER FILES

#include <maya/MObject.h>

// ****************************************************************************
// DECLARATIONS

class MPoint;
class MDataHandle;
class MDagPath;
class MWeight;
class MPointArray;
class MVector;

// ****************************************************************************
// CLASS DECLARATION (MItGeometry)

//! \ingroup OpenMaya
//! \brief Iterator class for geometry data.
/*!
This class is the iterator class for geometry data, and can be used to
loop over the CVs of NURBS, the points of subds & lattices, and the vertices of
polygonal meshes.

\par Examples:
Simple traversal.

\code
    MItGeometry iter( dagPath );
    for ( ; !iter.isDone(); iter.next() )
    {
        MPoint pt = iter.position();

        // do something with it
    }
\endcode

Traversal of a geometry group within a compute() method.

\code
    MStatus
    exampleIterator::compute(const MPlug& plug, MDataBlock& dataBlock)
    {
        MStatus status;

        if (plug.attribute() == oOutputGeometry) {
            // get the input geometry and input groupId
            MDataHandle hInputGeom = dataBlock.inputValue(inputGeomAttr);
            MDataHandle hGroupId = dataBlock.inputValue(inputGroupIdAttr);

            unsigned int groupId = hGroup.asLong();
            MDataHandle hOutput = dataBlock.outputValue(plug);
            hOutput.copy(hInputGeom);

            // do an iteration where we get each point and set it to a new value
            MItGeometry iter(hOutput,groupId,false);
            for ( ; !iter.isDone(); iter.next()) {
                MPoint pt = iter.position();

                // do something here to modify the point ...

                iter.setPosition(pt);
            }
        } else {
            status = MStatus::kUnknownParameter;
        }

        return status;
    }
\endcode
*/
class OPENMAYA_EXPORT MItGeometry
{
public:
	MItGeometry( const MDagPath& dagPath,
				 MStatus * ReturnStatus = NULL);
    MItGeometry( const MDagPath& dagPath,
                 MObject & component,
                 MStatus * ReturnStatus = NULL );
    MItGeometry( MObject& dagObject,
                 MStatus * ReturnStatus = NULL );
    MItGeometry( MDataHandle& dataHandle,
                 unsigned int groupId,
                 bool readOnly = true,
                 MStatus * ReturnStatus = NULL );
    MItGeometry( MDataHandle& dataHandle,
                 bool readOnly = true,
                 MStatus * ReturnStatus = NULL );
    MItGeometry( MDataHandle& dataHandle,
                 MObject & component,
                 bool readOnly = true,
                 MStatus * ReturnStatus = NULL );
    virtual ~MItGeometry();
    bool        isDone( MStatus * ReturnStatus = NULL ) const;
    MStatus     next();
    MPoint      position( MSpace::Space space = MSpace::kObject,
                          MStatus * ReturnStatus = NULL ) const;
    MVector     normal( MSpace::Space space = MSpace::kObject,
                          MStatus * ReturnStatus = NULL ) const;
    MStatus     setPosition( const MPoint& point,
                             MSpace::Space space = MSpace::kObject  );
	MWeight		weight( MStatus * ReturnStatus = NULL ) const;
    int	    index( MStatus * ReturnStatus = NULL ) const;
	// obsolete
	MObject		component( MStatus * ReturnStatus = NULL ) const;
	MObject		currentItem( MStatus * ReturnStatus = NULL ) const;
	int		count( MStatus * ReturnStatus = NULL ) const;
	int		exactCount( MStatus * ReturnStatus = NULL );
	MStatus		reset( );

	MStatus		allPositions( MPointArray& points,
							  MSpace::Space space = MSpace::kObject  ) const;
	MStatus		setAllPositions( const MPointArray& points,
								 MSpace::Space space = MSpace::kObject  );

    static const char* className();

protected:
// No protected members

private:
	// internal : called by the dataHandle constructors to set up the iterator
	//
	void 		createIterator(MDataHandle& dataHandle,
							   bool useComponents,
							   void* comps,
							   unsigned int groupId,
							   bool readOnly,
							   MStatus* status);

private:
	void *      f_it;
    void *      f_path;
    void *      f_matrix;
    void *      f_clist;
	bool        f_readOnly;
	bool        f_own;

	MItGeometry( void * ptr );
};

#endif /* __cplusplus */
#endif /* _MItGeometry */


text:
The powerdns plugin gathers metrics about PowerDNS using unix socket.

## Global configuration options <!-- @/docs/includes/plugin_config.md -->

In addition to the plugin-specific configuration settings, plugins support
additional global and plugin configuration settings. These settings are used to
modify metrics, tags, and field or create aliases and configure ordering, etc.
See the [CONFIGURATION.md][CONFIGURATION.md] for more details.

[CONFIGURATION.md]: ../../../docs/CONFIGURATION.md

## Configuration

```toml @sample.conf
# Read metrics from one or many PowerDNS servers
[[inputs.powerdns]]
  # An array of sockets to gather stats about.
  # Specify a path to unix socket.
  #
  # If no servers are specified, then '/var/run/pdns.controlsocket' is used as the path.
  unix_sockets = ["/var/run/pdns.controlsocket"]
```

### Permissions

Telegraf will need read access to the powerdns control socket.

On many systems this can be accomplished by adding the `telegraf` user to the
`pdns` group:

```sh
usermod telegraf -a -G pdns
```

## Measurements & Fields

- powerdns
  - corrupt-packets
  - deferred-cache-inserts
  - deferred-cache-lookup
  - dnsupdate-answers
  - dnsupdate-changes
  - dnsupdate-queries
  - dnsupdate-refused
  - packetcache-hit
  - packetcache-miss
  - packetcache-size
  - query-cache-hit
  - query-cache-miss
  - rd-queries
  - recursing-answers
  - recursing-questions
  - recursion-unanswered
  - security-status
  - servfail-packets
  - signatures
  - tcp-answers
  - tcp-queries
  - timedout-packets
  - udp-answers
  - udp-answers-bytes
  - udp-do-queries
  - udp-queries
  - udp4-answers
  - udp4-queries
  - udp6-answers
  - udp6-queries
  - key-cache-size
  - latency
  - meta-cache-size
  - qsize-q
  - signature-cache-size
  - sys-msec
  - uptime
  - user-msec

## Tags

- tags: `server=socket`

## Example Output

```sh
$ ./telegraf --config telegraf.conf --input-filter powerdns --test
> powerdns,server=/var/run/pdns.controlsocket corrupt-packets=0i,deferred-cache-inserts=0i,deferred-cache-lookup=0i,dnsupdate-answers=0i,dnsupdate-changes=0i,dnsupdate-queries=0i,dnsupdate-refused=0i,key-cache-size=0i,latency=26i,meta-cache-size=0i,packetcache-hit=0i,packetcache-miss=1i,packetcache-size=0i,qsize-q=0i,query-cache-hit=0i,query-cache-miss=6i,rd-queries=1i,recursing-answers=0i,recursing-questions=0i,recursion-unanswered=0i,security-status=3i,servfail-packets=0i,signature-cache-size=0i,signatures=0i,sys-msec=4349i,tcp-answers=0i,tcp-queries=0i,timedout-packets=0i,udp-answers=1i,udp-answers-bytes=50i,udp-do-queries=0i,udp-queries=0i,udp4-answers=1i,udp4-queries=1i,udp6-answers=0i,udp6-queries=0i,uptime=166738i,user-msec=3036i 1454078624932715706
```


text:
module.exports = function (schema) {

};


text:
package sun.management.snmp.jvminstr;

// java imports
//
import java.io.Serializable;

// jmx imports
//
import javax.management.MBeanServer;
import com.sun.jmx.snmp.SnmpCounter;
import com.sun.jmx.snmp.SnmpCounter64;
import com.sun.jmx.snmp.SnmpGauge;
import com.sun.jmx.snmp.SnmpInt;
import com.sun.jmx.snmp.SnmpUnsignedInt;
import com.sun.jmx.snmp.SnmpIpAddress;
import com.sun.jmx.snmp.SnmpTimeticks;
import com.sun.jmx.snmp.SnmpOpaque;
import com.sun.jmx.snmp.SnmpString;
import com.sun.jmx.snmp.SnmpStringFixed;
import com.sun.jmx.snmp.SnmpOid;
import com.sun.jmx.snmp.SnmpNull;
import com.sun.jmx.snmp.SnmpValue;
import com.sun.jmx.snmp.SnmpVarBind;
import com.sun.jmx.snmp.SnmpStatusException;

// jdmk imports
//
import com.sun.jmx.snmp.agent.SnmpMib;
import com.sun.jmx.snmp.agent.SnmpMibGroup;
import com.sun.jmx.snmp.agent.SnmpStandardObjectServer;
import com.sun.jmx.snmp.agent.SnmpStandardMetaServer;
import com.sun.jmx.snmp.agent.SnmpMibSubRequest;
import com.sun.jmx.snmp.agent.SnmpMibTable;
import com.sun.jmx.snmp.EnumRowStatus;

import sun.management.snmp.jvmmib.JvmThreadingMeta;
import sun.management.snmp.jvmmib.JvmThreadInstanceTableMeta;

/**
 * The class is used for representing SNMP metadata for the "JvmThreading"
 * group.
 */
public class JvmThreadingMetaImpl extends JvmThreadingMeta {

    static final long serialVersionUID = -2104788458393251457L;

    /**
     * Constructor for the metadata associated to "JvmThreading".
     */
    public JvmThreadingMetaImpl(SnmpMib myMib,
                                SnmpStandardObjectServer objserv) {
        super(myMib, objserv);
    }

    /**
     * Factory method for "JvmThreadInstanceTable" table metadata class.
     *
     * You can redefine this method if you need to replace the default
     * generated metadata class with your own customized class.
     *
     * @param tableName Name of the table object ("JvmThreadInstanceTable")
     * @param groupName Name of the group to which this table belong
     *        ("JvmThreading")
     * @param mib The SnmpMib object in which this table is registered
     * @param server MBeanServer for this table entries (may be null)
     *
     * @return An instance of the metadata class generated for the
     *         "JvmThreadInstanceTable" table (JvmThreadInstanceTableMeta)
     *
     **/
    protected JvmThreadInstanceTableMeta
        createJvmThreadInstanceTableMetaNode(String tableName,
                                             String groupName,
                                             SnmpMib mib,
                                             MBeanServer server)  {
        return new JvmThreadInstanceTableMetaImpl(mib, objectserver);
    }
}


text:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';

import { ProfileService } from '../profile.service';
import { ChangeNameModel } from './';
import { PageHeadingComponent } from '../../shared/directives';

@Component({
    selector: 'appc-change-name',
    templateUrl: './change-name.component.html'
})
export class ChangeNameComponent implements OnInit {
    userNameModel: ChangeNameModel = new ChangeNameModel('', '');
    @Output() notification = new EventEmitter<string>();

    constructor(private profileService: ProfileService) {
    }

    ngOnInit() {
        this.profileService.userName()
            .subscribe((res: any) => {
                this.userNameModel.firstName = res.firstName;
                this.userNameModel.lastName = res.lastName;
            },
            (errors: any) => this.notification.emit(errors[0])
            );
    }

    save(): void {
        this.profileService.userName(this.userNameModel)
            .subscribe((res: any) => {
                this.userNameModel.firstName = res.firstName;
                this.userNameModel.lastName = res.lastName;
                this.notification.emit(`Profile name changed to ${res.firstName} ${res.lastName}`);
            },
            (errors: any) => this.notification.emit(errors[0])
            );

    }

}


text:
.class public LHelloWorld;

.super Ljava/lang/Object;

.method public static main([Ljava/lang/String;)V
    .registers 2

    sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream;

    const/high16 v1, 0x7f020000

    invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V

    return-void
.end method


text:
import sys

sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
from tests.pyunit_utils import CustomMaeFunc, CustomRmseFunc,\
    assert_correct_custom_metric, regression_model, multinomial_model, binomial_model
from h2o.estimators.gbm import H2OGradientBoostingEstimator

# Custom model metrics fixture
def custom_mae_mm():
    return h2o.upload_custom_metric(CustomMaeFunc, func_name="mae", func_file="mm_mae.py")

def custom_rmse_mm():
    return h2o.upload_custom_metric(CustomRmseFunc, func_name="rmse", func_file="mm_rmse.py")

# Test that the custom model metric is computed
# and compare them with implicit custom metric
def test_custom_metric_computation_regression():
    (model, f_test) = regression_model(H2OGradientBoostingEstimator, custom_mae_mm())
    assert_correct_custom_metric(model, f_test, "mae", "Regression on prostate")

def test_custom_metric_computation_binomial():
    (model, f_test) = binomial_model(H2OGradientBoostingEstimator, custom_rmse_mm())
    assert_correct_custom_metric(model, f_test, "rmse", "Binomial on prostate")

def test_custom_metric_computation_multinomial():
    (model, f_test) = multinomial_model(H2OGradientBoostingEstimator, custom_rmse_mm())
    assert_correct_custom_metric(model, f_test, "rmse", "Multinomial on iris")

# Tests to invoke in this suite
__TESTS__ = [
    test_custom_metric_computation_binomial,
    test_custom_metric_computation_regression,
    test_custom_metric_computation_multinomial
]

if __name__ == "__main__":
    for func in __TESTS__:
        pyunit_utils.standalone_test(func)
else:
    for func in __TESTS__:
        func()