text:
package org.springframework.boot.actuate.metrics.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import org.springframework.boot.actuate.metrics.util.SimpleInMemoryRepository.Callback;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * @author Dave Syer
 */
public class InMemoryRepositoryTests {

	private final SimpleInMemoryRepository<String> repository = new SimpleInMemoryRepository<String>();

	@Test
	public void setAndGet() {
		this.repository.set("foo", "bar");
		assertEquals("bar", this.repository.findOne("foo"));
	}

	@Test
	public void updateExisting() {
		this.repository.set("foo", "spam");
		this.repository.update("foo", new Callback<String>() {
			@Override
			public String modify(String current) {
				return "bar";
			}
		});
		assertEquals("bar", this.repository.findOne("foo"));
	}

	@Test
	public void updateNonexistent() {
		this.repository.update("foo", new Callback<String>() {
			@Override
			public String modify(String current) {
				return "bar";
			}
		});
		assertEquals("bar", this.repository.findOne("foo"));
	}

	@Test
	public void findWithPrefix() {
		this.repository.set("foo", "bar");
		this.repository.set("foo.bar", "one");
		this.repository.set("foo.min", "two");
		this.repository.set("foo.max", "three");
		assertEquals(3,
				((Collection<?>) this.repository.findAllWithPrefix("foo")).size());
	}

	@Test
	public void patternsAcceptedForRegisteredPrefix() {
		this.repository.set("foo.bar", "spam");
		Iterator<String> iterator = this.repository.findAllWithPrefix("foo.*").iterator();
		assertEquals("spam", iterator.next());
		assertFalse(iterator.hasNext());
	}

	@Test
	public void updateConcurrent() throws Exception {
		final SimpleInMemoryRepository<Integer> repository = new SimpleInMemoryRepository<Integer>();
		Collection<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
		for (int i = 0; i < 1000; i++) {
			tasks.add(new Callable<Boolean>() {
				@Override
				public Boolean call() throws Exception {
					repository.update("foo", new Callback<Integer>() {
						@Override
						public Integer modify(Integer current) {
							if (current == null) {
								return 1;
							}
							return current + 1;
						}
					});
					return true;
				}
			});
			tasks.add(new Callable<Boolean>() {
				@Override
				public Boolean call() throws Exception {
					repository.update("foo", new Callback<Integer>() {
						@Override
						public Integer modify(Integer current) {
							if (current == null) {
								return -1;
							}
							return current - 1;
						}
					});
					return true;
				}
			});
		}
		List<Future<Boolean>> all = Executors.newFixedThreadPool(10).invokeAll(tasks);
		for (Future<Boolean> future : all) {
			assertTrue(future.get(1, TimeUnit.SECONDS));
		}
		assertEquals(new Integer(0), repository.findOne("foo"));
	}

}


text:
"""Support for Plex media server monitoring."""
import logging

from homeassistant.helpers.debounce import Debouncer
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity

from .const import (
    CONF_SERVER_IDENTIFIER,
    DISPATCHERS,
    DOMAIN as PLEX_DOMAIN,
    NAME_FORMAT,
    PLEX_UPDATE_SENSOR_SIGNAL,
    SERVERS,
)

_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up Plex sensor from a config entry."""
    server_id = config_entry.data[CONF_SERVER_IDENTIFIER]
    plexserver = hass.data[PLEX_DOMAIN][SERVERS][server_id]
    sensor = PlexSensor(hass, plexserver)
    async_add_entities([sensor])

class PlexSensor(Entity):
    """Representation of a Plex now playing sensor."""

    def __init__(self, hass, plex_server):
        """Initialize the sensor."""
        self._state = None
        self._server = plex_server
        self._name = NAME_FORMAT.format(plex_server.friendly_name)
        self._unique_id = f"sensor-{plex_server.machine_identifier}"
        self.async_refresh_sensor = Debouncer(
            hass,
            _LOGGER,
            cooldown=3,
            immediate=False,
            function=self._async_refresh_sensor,
        ).async_call

    async def async_added_to_hass(self):
        """Run when about to be added to hass."""
        server_id = self._server.machine_identifier
        unsub = async_dispatcher_connect(
            self.hass,
            PLEX_UPDATE_SENSOR_SIGNAL.format(server_id),
            self.async_refresh_sensor,
        )
        self.hass.data[PLEX_DOMAIN][DISPATCHERS][server_id].append(unsub)

    async def _async_refresh_sensor(self):
        """Set instance object and trigger an entity state update."""
        _LOGGER.debug("Refreshing sensor [%s]", self.unique_id)
        self._state = len(self._server.sensor_attributes)
        self.async_write_ha_state()

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def unique_id(self):
        """Return the id of this plex client."""
        return self._unique_id

    @property
    def should_poll(self):
        """Return True if entity has to be polled for state."""
        return False

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def unit_of_measurement(self):
        """Return the unit this state is expressed in."""
        return "Watching"

    @property
    def icon(self):
        """Return the icon of the sensor."""
        return "mdi:plex"

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return self._server.sensor_attributes

    @property
    def device_info(self):
        """Return a device description for device registry."""
        if self.unique_id is None:
            return None

        return {
            "identifiers": {(PLEX_DOMAIN, self._server.machine_identifier)},
            "manufacturer": "Plex",
            "model": "Plex Media Server",
            "name": "Activity Sensor",
            "sw_version": self._server.version,
        }

redpajama_set_name: RedPajamaGithub


text:
#include "tests/lib.h"

#define BUFFER_SIZE 60

int main() {
  usr_sem_t *wait0, *wait1, *read_write_lock;
  char line[BUFFER_SIZE];

  puts("[sem_barrier_p0] Open the semaphores.\n");
  wait0 = syscall_sem_open("wait0", -1);
  wait1 = syscall_sem_open("wait1", -1);
  read_write_lock = syscall_sem_open("rwlock", -1);

  puts("[sem_barrier_p0] Do work before barrier.\n");
  syscall_sem_p(read_write_lock);
  readline(line, BUFFER_SIZE);
  printf("[sem_barrier_p0] You wrote: %s\n", line);
  syscall_sem_v(read_write_lock);

  puts("[sem_barrier_p0] Wait for the other process.\n");
  syscall_sem_p(wait1); /* DIFFERENT THAN IN sem_barrier_prog1 */
  syscall_sem_v(wait0); /* DIFFERENT THAN IN sem_barrier_prog1 */

  puts("[sem_barrier_p0] Do work after barrier.\n");

  return 10;
}


text:
module Stupidedi
  module Versions
    module ThirtyForty
      module SegmentDefs
        s = Schema
        e = ElementDefs
        r = ElementReqs

        G69 = s::SegmentDef.build(:G69, "Line Item Detail - Description",
          "To describe an item in free-form format",
          e::E369 .simple_use(r::Mandatory,  s::RepeatCount.bounded(1)))
      end
    end
  end
end


text:
<?php

use sweelix\yii1\web\helpers\Html;
use sweelix\yii1\admin\core\models\Content;

$class = $data->contentStatus;
if($data->isPublishable(false) === false) {
	$class = $class." unpublished";
}

$model = new Content();
$model->tagId = $tagId;
$model->contentId = $data->contentId;
$model->selected = false;

if($data->hasTag($tagId) === true) {
	$class = $class . ' selected';
	$model->selected = true;
}

?>
<?php echo Html::openTag('tr', array(
		'class' => $class,
		'data-target' => '#'.$widget->getId(),
		'data-mode' => 'replace',
		'data-url-update' => Html::normalizeUrl(array('updateContentTag', 'contentId' => $data->contentId, 'tagId' => $tagId, 'page' => $widget->dataProvider->pagination->currentPage))
)); ?>

		<?php echo Html::activeCheckbox($model, '['.$index.']selected'); ?>
		<?php echo Html::activeHiddenField($model, '['.$index.']tagId'); ?>
		<?php echo Html::activeHiddenField($model, '['.$index.']contentId'); ?>

		<?php
			if (Yii::app()->user->checkAccess('structure') === true) {
				echo Html::link(
					$data->contentId,
					array('/sweeft/structure/content/', 'contentId' => $data->contentId ),
					array('title' => Yii::t('cloud', 'ID'))
				);
			} else {
				echo Html::tag('span', array('id' => $data->contentId), $data->contentId);
			}
		?>

		<?php
			if($data->contentStatus === 'offline') {
				echo Html::tag('span', array('class' => 'icon-circle-block', 'title' => Yii::t('cloud', $data->contentStatus)), $data->contentStatus);
			} else {
				if (Yii::app()->user->checkAccess('structure') === true) {
					echo Html::link(Yii::t('cloud', 'offline'),
						array('changeContentStatus', 'tagId' => $tagId, 'contentId' => $data->contentId, 'nodeId' => $data->nodeId, 'mode' => 'offline'),
						array(
							'class' => 'icon-circle-block light inverse ajaxRefresh', 'title' => Yii::t('cloud', 'offline'),
							'data-target' => '#'.$widget->getId(),
							'data-mode' => 'replace'
						)
					);
				} else {
					echo Html::label(Yii::t('cloud', 'offline'), null,
							array(
								'class' => 'icon-circle-block light inverse', 'title' => Yii::t('cloud', 'offline'),
							)
					);
				}
			}
		?>
		<?php
			if($data->contentStatus === 'draft') {
				echo Html::tag('span', array('class' => 'icon-file-lines', 'title' => Yii::t('cloud', $data->contentStatus)), $data->contentStatus);
			} else {
				if (Yii::app()->user->checkAccess('structure') === true) {
					echo Html::link(Yii::t('cloud', 'draft'),
							array('changeContentStatus', 'tagId' => $tagId, 'contentId' => $data->contentId, 'nodeId' => $data->nodeId, 'mode' => 'draft'),
							array(
									'class' => 'icon-file-lines light inverse ajaxRefresh', 'title' => Yii::t('cloud', 'draft'),
									'data-target' => '#'.$widget->getId(),
									'data-mode' => 'replace'
							)
					);
				} else {
					echo Html::label(Yii::t('cloud', 'draft'), null,
							array(
								'class' => 'icon-file-lines light inverse', 'title' => Yii::t('cloud', 'draft'),
							)
					);
				}
			}
		?>
		<?php
			if($data->contentStatus === 'online') {
				echo Html::tag('span', array('class' => 'icon-circle-check', 'title' => Yii::t('cloud', $data->contentStatus)), $data->contentStatus);
			} else {
				if (Yii::app()->user->checkAccess('structure') === true) {
					echo Html::link(Yii::t('cloud', 'online'),
							array('changeContentStatus', 'tagId' => $tagId, 'contentId' => $data->contentId, 'nodeId' => $data->nodeId, 'mode' => 'online'),
							array(
									'class' => 'icon-circle-check light inverse ajaxRefresh', 'title' => Yii::t('cloud', 'online'),
									'data-target' => '#'.$widget->getId(),
									'data-mode' => 'replace'
							)
					);
				} else {
					echo Html::label(Yii::t('cloud', 'online'), null,
							array(
								'class' => 'icon-circle-check light inverse', 'title' => Yii::t('cloud', 'online'),
							)
					);
				}
			}
		?>

		<?php
			if (Yii::app()->user->checkAccess('structure') === true) {
				echo Html::link(
					$data->contentTitle,
					array('/sweeft/structure/content/', 'contentId' => $data->contentId ),
					array('title' => $data->contentTitle)
				);
			} else {
				echo Html::tag('span', array('id' => $data->contentTitle), $data->contentTitle);
			}
		?>

		<?php echo $data->author->authorFirstname.' '.$data->author->authorLastname?>

<?php echo Html::closeTag('tr')?>


text:
import SpinnerCard from "components/spinners/SpinnerCard";
import connectData from "restlay/connectData";
import type { Translate } from "data/types";
import { translate } from "react-i18next";
import HelpLink from "components/HelpLink";
import React, { Component } from "react";
import { connect } from "react-redux";
import { compose } from "redux";
import queryString from "query-string";
import formatError from "formatters/error";
import OrganizationQuery from "api/queries/OrganizationQuery";
import createDevice, {
  U2F_TIMEOUT,
  U2F_PATH,
  APPID_VAULT_ADMINISTRATOR
} from "device";
import DeviceLogin from "./DeviceLogin";
import {
  login,
  logout,
  setTokenToLocalStorage,
  removeLocalStorageToken
} from "redux/modules/auth";
import { addMessage } from "redux/modules/alerts";
import network from "network";
import { withStyles } from "@material-ui/core/styles";
import Logo from "components/Logo";
import type { Organization } from "data/types";

const mapStateToProps = ({ auth, onboarding }) => ({
  isAuthenticated: auth.isAuthenticated,
  onboarding: onboarding
});

const mapDispatchToProps = (dispatch: *) => ({
  onLogin: token => dispatch(login(token)),
  onLogout: () => dispatch(logout()),
  addAlertMessage: (...props) => dispatch(addMessage(...props))
});

type Props = {
  isAuthenticated: boolean,
  t: Translate,
  history: Object,
  match: Object,
  location: Object,
  organization: Organization,
  onLogout: () => void,
  onStartAuth: () => void,
  onCloseTeamError: () => void,
  onResetTeam: () => void,
  classes: Object,
  addAlertMessage: Function,
  onLogin: Function
};

const styles = {
  base: {
    display: "table",
    width: "100vw",
    height: "100vh"
  },
  wrapper: {
    display: "table-cell",
    textAlign: "center",
    verticalAlign: "middle"
  },
  banner: {
    width: "400px",
    margin: "auto",
    marginBottom: "20px",
    position: "relative",
    textAlign: "left"
  },
  help: {
    width: 63,
    cursor: "pointer",
    marginRight: "0",
    position: "absolute",
    fontSize: 11,
    fontWeight: "600",
    textTransform: "uppercase",
    opacity: "0.5",
    transition: "opacity 0.2s ease",
    verticalAlign: "super",
    lineHeight: "1em",
    top: "5px",
    right: "0;"
  }
};

type State = {
  domain: string,
  isChecking: boolean,
  error: ?Error,
  domainValidated: boolean
};

let _isMounted = false;

export class Login extends Component<Props, State> {
  state = {
    domain: "",
    error: null,
    domainValidated: false,
    isChecking: false
  };

  UNSAFE_componentWillMount() {
    const { isAuthenticated, history, location } = this.props;
    if (isAuthenticated) {
      const { redirectTo } = queryString.parse(
        (location.search || "").slice(1)
      );
      history.replace(redirectTo || "/");
    }
  }

  componentDidMount() {
    this.checkDomain();
    _isMounted = true;
    this.onStartOnBoardingStatus();
  }

  componentWillUnmount() {
    _isMounted = false;
  }

  checkDomain = async () => {
    const { history, addAlertMessage } = this.props;
    try {
      await network(`/organization/exists`, "GET");
      this.setState({ domainValidated: true });
    } catch (e) {
      console.error(e);
      this.setState({ domainValidated: false });
      history.push("/");
      addAlertMessage("Error", "Team domain unknown", "error");
    }
  };

  UNSAFE_componentWillUpdate(nextProps: Props) {
    const { history, location } = nextProps;
    if (nextProps.isAuthenticated) {
      const { redirectTo } = queryString.parse(
        (location.search || "").slice(1)
      );
      history.push(redirectTo || "/");
    }
  }

  onStartOnBoardingStatus = async () => {
    const { history, match } = this.props;
    try {
      const { state } = await network(`/onboarding/state`, "GET");
      if (state !== "COMPLETE") {
        history.push(`/${match.params.orga_name}/onboarding`);
      } else {
        this.onStartAuth();
      }
    } catch (e) {
      console.error(e);
    }
  };

  onStartAuth = async () => {
    if (_isMounted) {
      const { organization, addAlertMessage, onLogin } = this.props;
      this.setState({ isChecking: true });
      try {
        const device = await await createDevice();
        const { pubKey } = await device.getPublicKey(U2F_PATH, false);
        const { token, key_handle } = await network(
          `/authentications/${pubKey}/challenge`,
          "GET"
        );
        this.setState({
          error: null
        });

        const application = APPID_VAULT_ADMINISTRATOR;
        const auth = await device.authenticate(
          Buffer.from(token, "base64"),
          application,
          Buffer.from(key_handle, "hex"),
          organization.name,
          organization.workspace,
          organization.domain_name,
          "Administrator"
        );

        setTokenToLocalStorage(token);
        await network("/authentications/authenticate", "POST", {
          authentication: auth.rawResponse.slice(0, auth.rawResponse.length - 4)
        });
        this.setState({ isChecking: false });
        onLogin(token);
        addAlertMessage(
          "Welcome",
          "Hello. Welcome on Ledger Vault Application"
        );
      } catch (error) {
        console.error(error);
        if (error && error.id === U2F_TIMEOUT) {
          // timeout we retry
          this.onStartAuth();
        } else {
          removeLocalStorageToken();
          this.setState({ error, isChecking: false });
          addAlertMessage(
            "Failed to authenticate",
            formatError(error),
            "error"
          );
        }
      }
    }
  };

  onCloseTeamError = () => {
    this.setState({ error: null });
  };

  onCancelDeviceLogin = () => {
    this.setState({ domainValidated: false });
    this.props.history.push("/");
  };

  render() {
    const { isChecking, domainValidated } = this.state;
    const { classes, match, t } = this.props;

    if (!domainValidated) {
      return (

          <SpinnerCard />

      );
    }
    return (

            <Logo />
            <HelpLink className={classes.help}>{t("welcome:help")}</HelpLink>

          <DeviceLogin
            domain={`${match.params.orga_name}`}
            isChecking={isChecking}
            onCancel={this.onCancelDeviceLogin}
            onRestart={this.onStartAuth}
          />

    );
  }
}

export default compose(
  connect(mapStateToProps, mapDispatchToProps),
  withStyles(styles)
)(
  connectData(translate()(Login), {
    queries: {
      organization: OrganizationQuery
    }
  })
);


text:
/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                                   Extrae                                  *
 *              Instrumentation package for parallel applications            *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in hope that it will be      *
 *   \  \__         useful but WITHOUT ANY WARRANTY; without even the        *
 *    \___          implied warranty of MERCHANTABILITY or FITNESS FOR A     *
 *                  PARTICULAR PURPOSE. See the GNU LGPL for more details.   *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public License  *
 * along with this library; if not, write to the Free Software Foundation,   *
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL: https://svn.bsc.es/repos/ptools/extrae/branches/2.4/src/tracer/taskid.c $
 | @last_commit: $Date: 2012-03-30 10:06:18 +0200 (Fri, 30 Mar 2012) $
 | @version:     $Revision: 1045 $
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

#include "common.h"

static char UNUSED rcsid[] = "$Id: threadid.c 1311 2012-10-25 11:05:07Z harald $";

#ifdef HAVE_STDIO_H
# include <stdio.h>
#endif
#ifdef HAVE_STRING_H
# include <string.h>
#endif

#include "extrae-cmd.h"
#include "extrae-cmd-init.h"
#include "extrae-cmd-emit.h"
#include "extrae-cmd-fini.h"

int main (int argc, char *argv[])
{
	int i = 1;

	while (i < argc)
	{
		int advance = 0;

		if (!strncasecmp (argv[i], CMD_INIT, strlen (CMD_INIT)))
			advance = Extrae_CMD_Init (i+1, argc, argv);
		else if (!strncasecmp (argv[i], CMD_EMIT, strlen(CMD_EMIT)))
			advance = Extrae_CMD_Emit (i+1, argc, argv);
		else if (!strncasecmp (argv[i], CMD_FINI, strlen(CMD_FINI)))
			advance = Extrae_CMD_Fini (i+1, argc, argv);
		else
			fprintf (stderr, "Unknown option %s\n", argv[i]);

		i += advance+1;
	}

	return 0;
}


text:
require "notifications/client/version"
require "notifications/client/speaker"
require "notifications/client/notification"
require "notifications/client/response_notification"
require "notifications/client/notifications_collection"
require 'active_support/core_ext/module/delegation'

module Notifications
  class Client
    attr_reader :speaker

    PRODUCTION_BASE_URL = "https://api.notifications.service.gov.uk".freeze

    delegate :base_url,
             :base_url=,
             to: :speaker

    ##
    # @see Notifications::Client::Speaker#initialize
    def initialize(*args)
      @speaker = Speaker.new(*args)
    end

    ##
    # @see Notifications::Client::Speaker#post
    # @return [ResponseNotification]
    def send_email(args)
      ResponseNotification.new(
        speaker.send(:post, "email", args)
      )
    end

    ##
    # @see Notifications::Client::Speaker#post
    # @return [ResponseNotification]
    def send_sms(args)
      ResponseNotification.new(
        speaker.send(:post, "sms", args)
      )
    end

    ##
    # @param id [Integer]
    # @see Notifications::Client::Speaker#get
    # @return [Notification]
    def get_notification(id)
      Notification.new(
        speaker.send(:get, id)["notification"]
      )
    end

    ##
    # @param options [Hash]
    # @option options [String] :template_type
    #   sms or email
    # @option options [String] :status
    #   sending, delivered, permanently failed,
    #   temporarily failed, or technical failure
    # @option options [String] :page
    # @option options [String] :page_size
    # @option options [String] :limit_days
    # @see Notifications::Client::Speaker#get
    # @return [NotificationsCollection]
    def get_notifications(options = {})
      NotificationsCollection.new(
        speaker.send(:get, nil, options)
      )
    end
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="A complete example of Cropper.">
  <meta name="keywords" content="HTML, CSS, JS, JavaScript, jQuery, PHP, image cropping, web development">
  <meta name="author" content="Fengyuan Chen">
  <title>Crop Avatar - Cropper</title>
  <link href="../../assets/css/bootstrap.min.css" rel="stylesheet">
  <link href="../../dist/cropper.min.css" rel="stylesheet">
  <link href="css/main.css" rel="stylesheet">

          <form class="avatar-form" action="crop.php" enctype="multipart/form-data" method="post">

              <button class="close" data-dismiss="modal" type="button">×</button>

Change Avatar

                  <input class="avatar-src" name="avatar_src" type="hidden">
                  <input class="avatar-data" name="avatar_data" type="hidden">
                  Local upload
                  <input class="avatar-input" id="avatarInput" name="avatar_file" type="file">

                      <button class="btn btn-primary" data-method="rotate" data-option="-90" type="button" title="Rotate -90 degrees">Rotate Left</button>
                      <button class="btn btn-primary" data-method="rotate" data-option="-15" type="button">-15deg</button>
                      <button class="btn btn-primary" data-method="rotate" data-option="-30" type="button">-30deg</button>
                      <button class="btn btn-primary" data-method="rotate" data-option="-45" type="button">-45deg</button>

                      <button class="btn btn-primary" data-method="rotate" data-option="90" type="button" title="Rotate 90 degrees">Rotate Right</button>
                      <button class="btn btn-primary" data-method="rotate" data-option="15" type="button">15deg</button>
                      <button class="btn btn-primary" data-method="rotate" data-option="30" type="button">30deg</button>
                      <button class="btn btn-primary" data-method="rotate" data-option="45" type="button">45deg</button>

                    <button class="btn btn-primary btn-block avatar-save" type="submit">Done</button>

          </form>


text:
<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * First Entity.
 *
 * @property int $id
 */
class First extends Entity
{

}


text:
package org.rsna.ctp.servlets;

import org.apache.log4j.Logger;
import org.rsna.ctp.Configuration;
import org.rsna.ctp.objects.DicomObject;
import org.rsna.ctp.pipeline.AbstractImportService;
import org.rsna.ctp.pipeline.AbstractQueuedExportService;
import org.rsna.ctp.pipeline.Pipeline;
import org.rsna.ctp.pipeline.PipelineStage;
import org.rsna.ctp.pipeline.Quarantine;
import org.rsna.ctp.pipeline.QueueManager;
import org.rsna.server.HttpRequest;
import org.rsna.server.HttpResponse;
import org.rsna.servlets.Servlet;
import org.rsna.util.FileUtil;
import org.rsna.util.HtmlUtil;
import org.rsna.util.StringUtil;

import java.io.File;
import java.util.List;

/**
 * The QuarantineServlet. This implementation provides access
 * to the contents of the quarantines.
 */
public class QuarantineServlet extends Servlet {

	static final Logger logger = Logger.getLogger(QuarantineServlet.class);
	String home = "/";
	String suppress = "";

	/**
	 * Construct a QuarantineServlet.
	 * @param root the root directory of the server.
	 * @param context the path identifying the servlet.
	 */
	public QuarantineServlet(File root, String context) {
		super(root, context);
	}

	/**
	 * The GET handler: return a page showing the quarantines.
	 * There are several possible query strings:
	 *

	 *
no query string:
	 *      return a page listing of the sizes of the quarantines for all pipelines.

	 *
?p=[p]:
	 *      return a listing of the sizes of the quarantines for pipeline p.
	 *
?p=[p]&s=[s]:
	 *      return a listing of the contents of the quarantine for pipeline p, stage s.
	 *
?p=[p]&s=[s]&file=[filename]:
	 *      return a listing of the file if one is available; otherwise,
	 *      return the identified file.
	 *
?p=[p]&s=[s]&file=[filename]&list=no:
	 *      force return of the file, even if a listing page is available.
	 *

	 * The queue and delete query parameters cause files to be queued or deleted.
	 * @param req the request object
	 * @param res the response object
	 */
	@Override
  public void doGet(HttpRequest req, HttpResponse res) {

		//Require that the user have the qadmin or admin role
		boolean admin = req.userHasRole("qadmin") || req.userHasRole("admin");
		if (!admin) {
			res.setResponseCode(HttpResponse.forbidden);
			res.send();
			return;
		}

		if (req.hasParameter("suppress")) {
			home = "";
			suppress = "&suppress";
		}

		//Check the path information
		int pInt = StringUtil.getInt(req.getParameter("p", "-1"), -1);
		int sInt = StringUtil.getInt(req.getParameter("s", "-1"), -1);
		String file = req.getParameter("file", "");
		boolean list = req.getParameter("list", "yes").equals("yes");
		boolean display = (req.getParameter("display") != null);
		boolean queue = (req.getParameter("queue") != null);
		boolean delete = (req.getParameter("delete") != null);
		if (pInt == -1) sizesPage(res, home);
		else if (sInt == -1) sizesPage(res, pInt, home);
		else if (file.equals("")) {
			if (admin && queue) queueAll(pInt, sInt);
			if (admin && delete) deleteAll(pInt, sInt);
			contentsPage(req, res, pInt, sInt, admin);
		}
		else {
			if (admin && (queue || delete)) {
				if (queue) queueFile(pInt, sInt, file);
				if (delete) deleteFile(pInt, sInt, file);
				contentsPage(req, res, pInt, sInt, admin);
			}
			else downloadFile(res, pInt, sInt, file, list, display, admin, home);
		}
	}

	//Get a page listing the sizes of all the quarantines
	void sizesPage(HttpResponse res, String home) {
		StringBuffer sb = new StringBuffer();
		sb.append("<title>Quarantine</title>"+getStyles()+"");
		if (!home.equals("")) sb.append(HtmlUtil.getCloseBox(home));
		sb.append("
All Quarantines
");
		sb.append("
");
		Configuration config = Configuration.getInstance();
		List<Pipeline> pipelines = config.getPipelines();
		if (pipelines.size() != 0) {
			for (int i=0; i<pipelines.size(); i++) {
				getSizes(sb, pipelines.get(i), i);
			}
		}
		sb.append("
");
		sb.append("");
		//Send the response;
		res.disableCaching();
		res.write(sb.toString());
		res.setContentType("html");
		res.send();
	}

	//Get a page listing the sizes of the quarantines for a single pipeline
	void sizesPage(HttpResponse res, int pipelineIndex, String home) {
		//Make sure the index is valid
		Pipeline pipeline;
		try { pipeline = Configuration.getInstance().getPipelines().get(pipelineIndex); }
		catch (Exception quit) {
			res.setResponseCode(HttpResponse.notfound);
			res.send();
			return;
		}
		StringBuffer sb = new StringBuffer();

		sb.append("<title>Quarantine</title>"+getStyles()+"");
		if (!home.equals("")) sb.append(HtmlUtil.getCloseBox(home));
		sb.append("
"+pipeline.getPipelineName()+" Quarantines
");
		sb.append("
");
		getSizes(sb, pipeline, pipelineIndex);
		sb.append("
");
		sb.append("");
		//Send the response;
		res.disableCaching();
		res.write(sb.toString());
		res.setContentType("html");
		res.send();
	}

	//List the sizes of the quarantines for a single pipeline
	void getSizes(StringBuffer sb, Pipeline pipeline, int pipelineIndex) {
		List<PipelineStage> stages = pipeline.getStages();
		boolean first = true;
		for (int i=0; i<stages.size(); i++) {
			first &= !getSize(sb, pipeline, stages.get(i), first, pipelineIndex, i);
		}
	}

	//List the size of the quarantine for a single PipelineStage.
	boolean getSize(StringBuffer sb,
					Pipeline pipeline,
					PipelineStage stage,
					boolean first,
					int pipelineIndex,
					int stageIndex) {
		Quarantine quarantine = stage.getQuarantine();
		if (quarantine == null) return false;
		sb.append("
");
		if (first) {
			sb.append(""+pipeline.getPipelineName()+"");
			first = false;
		}
		sb.append("	");
		sb.append(""+stage.getName()+"");
		sb.append("	"+quarantine.getSize()+"
");
		return true;
	}

	//Delete all the objects in a quarantine
	void deleteAll(int pipelineIndex, int stageIndex) {
		Pipeline pipeline;
		PipelineStage stage;
		try { pipeline = Configuration.getInstance().getPipelines().get(pipelineIndex); }
		catch (Exception quit) { return; }
		try { stage = pipeline.getStages().get(stageIndex); }
		catch (Exception quit) { return; }
		Quarantine quarantine = stage.getQuarantine();
		if (quarantine == null) return;
		quarantine.deleteAll();
	}

	//Queue all the objects in a quarantine to the closest QueueManager available.
	void queueAll(int pipelineIndex, int stageIndex) {
		//First find the pipeline and the stage.
		Pipeline pipeline;
		PipelineStage stage;
		try { pipeline = Configuration.getInstance().getPipelines().get(pipelineIndex); }
		catch (Exception quit) { return; }
		try { stage = pipeline.getStages().get(stageIndex); }
		catch (Exception quit) { return; }
		//Next, get the stage's quarantine.
		Quarantine quarantine = stage.getQuarantine();
		if (quarantine == null) return;
		//Now find the closest QueueManager.
		//If the stage is an ExportService with a queue, then use the stage's QueueManager.
		//If the stage is not an ExportService, then use the QueueManager of the pipeline's ImportService.
		//If the ImportService does not have a QueueManager, do nothing.
		QueueManager queueManager = null;
		if (stage instanceof AbstractQueuedExportService) {
			queueManager = ((AbstractQueuedExportService)stage).getQueueManager();
		}
		else {
			//Get the ImportService
			PipelineStage head = pipeline.getStages().get(0);
			if (head instanceof AbstractImportService) {
				queueManager = ((AbstractImportService)head).getQueueManager();
			}
		}
		if (queueManager == null) return;
		//Okay, now get all the files from the quarantine and enqueue them.
		quarantine.queueAll(queueManager);
	}

	//List the contents of a quarantine
	void contentsPage(HttpRequest req, HttpResponse res, int pipelineIndex, int stageIndex, boolean admin) {
		Pipeline pipeline;
		PipelineStage stage;
		try { pipeline = Configuration.getInstance().getPipelines().get(pipelineIndex); }
		catch (Exception quit) {
			res.setResponseCode(HttpResponse.notfound);
			res.send();
			return;
		}
		try { stage = pipeline.getStages().get(stageIndex); }
		catch (Exception quit) {
			res.setResponseCode(HttpResponse.notfound);
			res.send();
			return;
		}
		StringBuffer sb = new StringBuffer();
		sb.append("<title>Quarantine</title>"+getStyles()+"");
		if (!home.equals("")) sb.append(HtmlUtil.getCloseBox(home));
		sb.append("

"+pipeline.getPipelineName()
					+"
"+stage.getName()+" Quarantine
");
		Quarantine quarantine = stage.getQuarantine();
		if (quarantine == null) {
			sb.append("
No quarantine is defined.
");
		}
		else {
			File[] files = quarantine.getFiles();
			if (files.length > 0) {
				if (admin) {
					sb.append("<input type=\"button\"");
					sb.append(" onclick=\"window.open('?p="+pipelineIndex+"&s="+stageIndex+suppress+"&queue','_self')\"");
					sb.append(" value=\"Queue All\"/>");
					sb.append("   ");
					sb.append("<input type=\"button\"");
					sb.append(" onclick=\"window.open('?p="+pipelineIndex+"&s="+stageIndex+suppress+"&delete','_self')\"");
					sb.append(" value=\"Delete All\"/>");
					sb.append("

");
				}
				sb.append("
");
				for (int i=0; i<files.length; i++) {
					sb.append("
");
					sb.append("");
					sb.append(""+files[i].getName()+"");
					sb.append("	");
					sb.append("");
					sb.append(StringUtil.getDateTime(files[i].lastModified(),"   "));
					sb.append("	");
					if (admin) {
						sb.append("");
						sb.append("queue");
						sb.append("	");
						sb.append("");
						sb.append("delete");
						sb.append("	");
						sb.append("");
						sb.append("display");
						sb.append("	");
					}
					sb.append("
");
				}
				sb.append("
");
			}
			else sb.append("
The quarantine is empty.
");
		}
		sb.append("");
		//Send the response;
		res.disableCaching();
		res.write(sb.toString());
		res.setContentType("html");
		res.send();
	}

	//Delete a single object from a quarantine
	void deleteFile(int pipelineIndex, int stageIndex, String filename) {
		Pipeline pipeline;
		PipelineStage stage;
		try { pipeline = Configuration.getInstance().getPipelines().get(pipelineIndex); }
		catch (Exception quit) { return; }
		try { stage = pipeline.getStages().get(stageIndex); }
		catch (Exception quit) { return; }
		Quarantine quarantine = stage.getQuarantine();
		if (quarantine == null) return;
		quarantine.deleteFile(filename);
	}

	//Queue a single object in a quarantine to the closest QueueManager available.
	void queueFile(int pipelineIndex, int stageIndex, String filename) {
		Pipeline pipeline;
		PipelineStage stage;
		try { pipeline = Configuration.getInstance().getPipelines().get(pipelineIndex); }
		catch (Exception quit) { return; }
		try { stage = pipeline.getStages().get(stageIndex); }
		catch (Exception quit) { return; }
		Quarantine quarantine = stage.getQuarantine();
		if (quarantine == null) return;
		QueueManager queueManager = null;
		if (stage instanceof AbstractQueuedExportService) {
			queueManager = ((AbstractQueuedExportService)stage).getQueueManager();
		}
		else {
			//Get the ImportService
			PipelineStage head = pipeline.getStages().get(0);
			if (head instanceof AbstractImportService) {
				queueManager = ((AbstractImportService)head).getQueueManager();
			}
		}
		if (queueManager == null) return;
		//Okay, now get all the files from the quarantine and enqueue them.
		quarantine.queueFile(filename, queueManager);
	}

	//Download a file
	void downloadFile(HttpResponse res,
					  int pipelineIndex,
					  int stageIndex,
					  String filename,
					  boolean list,
					  boolean display,
					  boolean admin,
					  String home) {
		Pipeline pipeline;
		PipelineStage stage;
		try { pipeline = Configuration.getInstance().getPipelines().get(pipelineIndex); }
		catch (Exception quit) {
			res.setResponseCode(HttpResponse.notfound);
			res.send();
			return;
		}
		try { stage = pipeline.getStages().get(stageIndex); }
		catch (Exception quit) {
			res.setResponseCode(HttpResponse.notfound);
			res.send();
			return;
		}
		res.disableCaching();
		StringBuffer sb = new StringBuffer();
		Quarantine quarantine = stage.getQuarantine();
		if (quarantine == null) {
			sb.append(getPageStart(pipeline, stage, false, null, home));
			sb.append("
No quarantine is defined.
");
			sb.append("");
			res.write(sb.toString());
			res.setContentType("html");
			res.send();
			return;
		}
		File file = quarantine.getFile(filename);
		if (!file.exists()) {
			sb.append(getPageStart(pipeline, stage, false, null, home));
			sb.append("
The requested file is not in the quarantine.
");
			sb.append("");
			res.write(sb.toString());
			res.setContentType("html");
			res.send();
			return;
		}
		//Okay, we finally have the file to download.
		//First, parse it to see if it is a DicomObject.
		DicomObject dicomObject = null;
		try { dicomObject = new DicomObject(file); }
		catch (Exception ignore) { dicomObject = null; }

		if ((dicomObject == null) || (!list && !display)) {
			//Just download the file with a standard
			//Content-Type as defined by its extension.
			res.write(file);
			res.setContentType(file);
			res.setHeader("Content-Disposition","attachment; filename=\"" + file.getName() + "\"");
			res.send();
			return;
		}

		//See if this is a display request
		if (display) {
			if (dicomObject.isImage()) {
				try {
					File temp = File.createTempFile("Image-", ".jpeg");
					dicomObject.saveAsJPEG(temp, 0, 1500, 256, -1);
					res.write(temp);
					res.setContentType(temp);
					res.send();
					temp.delete();
					return;
				}
				catch (Exception unable) { }
			}
		}

		//If we get here, then it was not a display
		//or the display request failed. The only thing
		//to do is download a page containing an element
		//listing and a button allowing downloading of the file.
		sb.append(getPageStart(pipeline, stage, admin, file, home));
		sb.append("");
		sb.append(dicomObject.getElementTable(admin));
		sb.append("
");
		sb.append("Download the file");
		sb.append("
");
		sb.append("");
		res.write(sb.toString());
		res.setContentType("html");
		res.send();
	}

	//Get the head part of the page.
	private String getPageStart(Pipeline pipeline, PipelineStage stage, boolean admin, File file, String home) {
		StringBuffer sb = new StringBuffer();
		sb.append("<title>Quarantine</title>");
		sb.append(getStyles());
		sb.append("\n");
		if (admin) {
			String filepath = "";
			if (file != null) filepath = file.getAbsolutePath();
			filepath = filepath.replaceAll("\\\\","/");
			sb.append("\n");
		}
		sb.append("");
		sb.append("");
		if (!home.equals("")) sb.append(HtmlUtil.getCloseBox(home));
		sb.append("
"+pipeline.getPipelineName()
					+"
"+stage.getName()+" Quarantine
");
		return sb.toString();
	}

	//Set up a standard set of styles for these pages.
	private String getStyles() {
		StringBuffer sb = new StringBuffer();
		sb.append("<link rel=\"Stylesheet\" type=\"text/css\" media=\"all\" href=\"/BaseStyles.css\"></link>");
		sb.append("\n\n");
		return sb.toString();
	}

}


text:
package com.vmware.vim25;

/**
 * @author Steve Jin (http://www.doublecloud.org)
 * @version 5.1
 */

public class ArrayOfVirtualMachineDatastoreVolumeOption {
    public VirtualMachineDatastoreVolumeOption[] VirtualMachineDatastoreVolumeOption;

    public VirtualMachineDatastoreVolumeOption[] getVirtualMachineDatastoreVolumeOption() {
        return this.VirtualMachineDatastoreVolumeOption;
    }

    public VirtualMachineDatastoreVolumeOption getVirtualMachineDatastoreVolumeOption(int i) {
        return this.VirtualMachineDatastoreVolumeOption[i];
    }

    public void setVirtualMachineDatastoreVolumeOption(VirtualMachineDatastoreVolumeOption[] VirtualMachineDatastoreVolumeOption) {
        this.VirtualMachineDatastoreVolumeOption = VirtualMachineDatastoreVolumeOption;
    }
}


text:
package main

import "fmt"

//START OMIT
func main() {
	answer := getAnswer()
	fmt.Println(*answer)
}

func getAnswer() *int {
	i := 42
	return &i
}

//END OMIT


text:
(function() {
    'use strict';
    angular
        .module('simpleWebrtcServerApp')
        .factory('AnnotationAsPictureFile', AnnotationAsPictureFile);

    AnnotationAsPictureFile.$inject = ['$http'];

    function AnnotationAsPictureFile($http) {
        var resourceUrl = 'api/annotation-as-pictures/file';

        var factory = {
            uploadFile: uploadFile
        }
        return factory;

        function uploadFile(formData, onSuccess, onError) {
            $http.post(resourceUrl, formData, {
                    transformRequest: angular.identity,
                    headers: {
                        'Content-Type': undefined
                    }
                })
                .then(
                    onSuccess, onError
                );
        };
    }
})();


text:
<?php

namespace Webuni\CommonMark\TableExtension;

use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\ContextInterface;
use League\CommonMark\Cursor;

class Table extends AbstractBlock
{
    private $parser;

    public function __construct(\Closure $parser)
    {
        parent::__construct();
        $this->appendChild(new TableRows(TableRows::TYPE_HEAD));
        $this->appendChild(new TableRows(TableRows::TYPE_BODY));
        $this->parser = $parser;
    }

    public function canContain(AbstractBlock $block)
    {
        return $block instanceof TableRows;
    }

    public function acceptsLines()
    {
        return true;
    }

    public function isCode()
    {
        return false;
    }

    public function getHead()
    {
        foreach ($this->children() as $child) {
            if ($child instanceof TableRows && $child->isHead()) {
                return $child;
            }
        }
    }

    public function getBody()
    {
        foreach ($this->children() as $child) {
            if ($child instanceof TableRows && $child->isBody()) {
                return $child;
            }
        }
    }

    public function matchesNextLine(Cursor $cursor)
    {
        return call_user_func($this->parser, $cursor);
    }

    public function handleRemainingContents(ContextInterface $context, Cursor $cursor)
    {
    }
}


text:
void export_collector();
void export_negotiator();
void export_schedd();
void export_credd();
void export_dc_tool();
void export_daemon_and_ad_types();
void export_daemon_location();
void export_config();
void export_secman();
void export_event_log();
void export_event_reader();
void export_log_reader();
void enable_classad_extensions();
void enable_deprecation_warnings();
void export_claim();
void export_startd();
void export_query_iterator();
void export_classad();


text:
'use strict';

module.exports = function ({data}) {
    return {
        getHome(req, res) {
            data.getAllFactsWithoutPaging()
                .then(result => {
                    let randomFact = result[Math.floor(Math.random() * Object.keys(result).length)];
                    res.status(200).json(randomFact);
                });
        },
        homepage(req,res){
            res.sendFile('index.html');
        }
    };
};


text:
<?php

/**
 *
 * @author Hudhaifa Shatnawi <hudhaifa.shatnawi@gmail.com>
 * @version 1.0, Aug 27, 2016 - 1:05:45 PM
 */
class BookCategory
        extends DataObject
        implements ManageableDataObject, SearchableDataObject, SociableDataObject {

    private static $db = array(
        'Title' => 'Varchar(255)',
        'Description' => 'Text'
    );
    private static $has_one = array(
    );
    private static $has_many = array(
    );
    private static $belongs_many_many = array(
        'Books' => 'Book',
    );
    private static $searchable_fields = array(
        'Title',
    );
    private static $summary_fields = array(
        'Title',
        'Books.Count',
    );

    public function fieldLabels($includerelations = true) {
        $labels = parent::fieldLabels($includerelations);

        $labels['Title'] = _t('Librarian.TITLE', 'Title');
        $labels['Books.Count'] = _t('Librarian.NUMBER_OF_BOOKS', 'Number Of Books');

        return $labels;
    }

    public function canView($member = null) {
        return true;
    }

    function Link($action = null) {
        $page = BookCategoriesPage::get()->first();

        return $page ? $page->Link($action) : null;
    }

    /**
     * Show this DataObejct in the sitemap.xml
     */
    function AbsoluteLink($action = null) {
        return Director::absoluteURL($this->Link("show/$this->ID"));
    }

    //////// ManageableDataObject ////////
    public function getObjectDefaultImage() {
        return null;
    }

    public function getObjectEditLink() {
        return $this->Link("edit/$this->ID");
    }

    public function getObjectEditableImageName() {

    }

    public function getObjectImage() {
        return null;
    }

    public function getObjectItem() {
        return $this->renderWith('Imageless_Item');
    }

    public function getObjectLink() {
        return $this->Link("show/$this->ID");
    }

    public function getObjectNav() {

    }

    public function getObjectRelated() {
        return BookCategory::get()->sort('RAND()');
    }

    public function getObjectSummary() {
        $lists = array();

        if ($this->Description) {
            $lists[] = array(
                'Title' => _t('Librarian.DESCRIPTION', 'Description'),
                'Value' => '<br />' . $this->Description
            );
        }

        return new ArrayList($lists);
    }

    public function getObjectTabs() {
        $lists = array();

        $books = $this->Books();
        if ($books->Count()) {
            $lists[] = array(
                'Title' => _t("Librarian.BOOKS", "Books") . " ({$books->Count()})",
                'Content' => $this
                        ->customise(array(
                            'Results' => $books
                        ))
                        ->renderWith('List_Grid')
            );
        }

        $this->extend('extraTabs', $lists);

        return new ArrayList($lists);
    }

    public function getObjectTitle() {
        return $this->Title;
    }

    public function canPublicView() {
        return $this->canView();
    }

    //////// SearchableDataObject ////////
    public function getObjectRichSnippets() {

    }

    //////// SociableDataObject ////////
    public function getSocialDescription() {
        if ($this->Description) {
            return strip_tags($this->Description);
        }

        return $this->getObjectTitle();
    }

    public function getRandomBooks($num = 2) {
        $books = array();
        foreach ($this->Books()->sort('RAND()') as $book) {
            $books[] = $book;
        }

        return (new ArrayList($books))->limit($num);
    }

    public function getRandomVolumes() {
        $volumes = array();

        foreach ($this->Books()->sort('RAND()') as $book) {
            foreach ($this->BookCopies()->sort('RAND()') as $copy) {
                foreach ($copy->BookVolumes() as $volume) {
                    if ($includeReferences || !$volume->IsReference()) {
                        $volumes[] = $volume;
                    }
                }
            }
        }
        foreach ($this->BookVolumes()->sort('RAND()') as $volume) {
            if ($includeReferences || !$volume->IsReference()) {
                $volumes[] = $volume;
            }
        }

        return new ArrayList($volumes);
    }

}


text:
const _privateKey = typeof(Proxy) !== 'undefined' ? '_private' : Symbol('_private');
export { _privateKey as default };


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*============================================================
**
** Source: CreateMutexW_ReleaseMutex/test2/CreateMutexW.c
**
** Purpose: This test case tests the following things
**          - Creation of named Mutexes
**          - Creating multiple handles to a single named Mutex
**          - Ensuring that these handles work interchangeably
**          - Setting bInitialOwnerFlag to TRUE will cause the
**            initial call to a Wait function on the same Mutex
**            to actually wait.
**          - Waiting on a Mutex that a thread already owns does
**            not block.
**          - Create Named mutex with empty string ("")
**          - Create Named mutex with string of MAX_LONGPATH length
**          - Calling RelaseMutex with invalid Mutex handles and
**            valid but unowned Mutexes.
**
** Dependencies: CreateThread
**               ReleaseMutex
**               WaitForSingleObject
**               CloseHandle
**               Sleep
**               memset
**

**
**=========================================================*/

#define UNICODE
#include <palsuite.h>

const char *szMutex = "MyMutex";
const char *szEmpty = "";

/* Function Prototypes */
BOOL TestNamedMutex(const char *szMutexName);
DWORD NamedMutexThread(LPVOID lpParam);
BOOL NegativeReleaseMutexTests();

struct ThreadData
{
    HANDLE hMutex;
    BOOL bReturnCode;
};
typedef struct ThreadData THREADDATA;

int __cdecl main (int argc, char **argv)
{
    BOOL bFailures = FALSE;
    char *szMaxPath;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return ( FAIL );
    }

    /*
     * Test named Mutexes with ordinary string
     */

    if (!TestNamedMutex(szMutex))
    {
        bFailures = TRUE;
    }

    /*
     * Test named Mutexes with empty ("") string
     */

    if (!TestNamedMutex(szEmpty))
    {
        bFailures = TRUE;
    }

    /*
     * Test named Mutexes with string of length MAX_LONGPATH
     */

    szMaxPath = (char *)malloc(MAX_LONGPATH+2);
    memset(szMaxPath, 'A', MAX_LONGPATH-60);
    szMaxPath[MAX_LONGPATH-60] = 0;

    if (!TestNamedMutex(szMaxPath))
    {
        bFailures = TRUE;
    }

    free(szMaxPath);

    /*
     * Run some negative tests on ReleaseMutex
     */

    if (!NegativeReleaseMutexTests())
    {
        bFailures = TRUE;
    }

    /*
     * If there were any failures, then abort with a call to Fail
     */

    if (bFailures == TRUE)
    {
        Fail("ERROR: There some failures in the Mutex tests.\n");
    }

    PAL_Terminate();
    return ( PASS );
}

/*
 * Testing Function
 *
 * Try to get multiple handles to a named Mutex and test
 * to make sure they actually refer to same Mutex object.
 */
BOOL TestNamedMutex(const char *szMutexName)
{
    DWORD dwData;
    HANDLE hMutex1;
    HANDLE hMutex2;
    HANDLE hThread;
    WCHAR *swzMutexName;
    THREADDATA threadData;

    /* Convert the Mutex name to wide characters */
    swzMutexName = convert((char *)szMutexName);

    /* Create a mutex and take ownership immediately */
    hMutex1 = CreateMutexW (NULL, TRUE, swzMutexName);

    if (NULL == hMutex1)
    {
        Trace("ERROR: CreateMutex #1 failed. GetLastError returned %u\n",
              GetLastError());
        free(swzMutexName);
        return FALSE;
    }

    /* Try to wait on the Mutex we just created. We should not block. */
    if (WaitForSingleObject(hMutex1, 1000) == WAIT_TIMEOUT)
    {
        Trace("WaitForSingleObject blocked on a Mutex that we owned.\n");
        free(swzMutexName);
        return FALSE;
    }
    /* We have to call ReleaseMutex here because of the Wait */
    if (ReleaseMutex(hMutex1) == FALSE)
    {
        Trace("ReleaseMutex Failed.\n");
        return FALSE;
    }

    /* Get a second handle to the same mutex */
    hMutex2 = CreateMutexW (NULL, FALSE, swzMutexName);

    if (NULL == hMutex2)
    {
        Trace("ERROR: CreateMutex #2 failed. GetLastError returned %u\n",
              GetLastError());
        free(swzMutexName);
        return FALSE;
    }

    /* Get rid of the wide character string */
    free(swzMutexName);

    /*
     * Create a thread that will Wait on the second handle.
     */
    threadData.hMutex = hMutex2;
    hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)NamedMutexThread,
                          (LPVOID)&threadData, 0, &dwData);

    if (NULL == hThread)
    {
        Trace("ERROR: CreateThread failed. GetLastError returned %u\n",
              GetLastError());
        return FALSE;
    }

    /* Give the thread a little time to execute & wait*/
    Sleep(500);

    /* Signal the the first handle */
    if (ReleaseMutex(hMutex1) == FALSE)
    {
        Trace("ReleaseMutex Failed.\n");
        return FALSE;
    }

    /* Give the thread some time to finish */
    Sleep(2000);

    /* Clean Up */
    if (CloseHandle(hMutex1) == FALSE ||
        CloseHandle(hMutex2) == FALSE ||
        CloseHandle(hThread) == FALSE)
    {
        Trace("ERROR: CloseHandle failed.\n");
        return FALSE;
    }

    /* Check the return code to see if signalling the first */
    /* Mutex handle woke up the thread which was Waiting on */
    /* the second handle.                                   */
    if (threadData.bReturnCode != FALSE)
    {
        Trace("ERROR: The handles did not refer to the same Mutex object.\n");
        return FALSE;
    }

    return TRUE;
}

/*
 * Thread function used with above testing function.
 */
DWORD NamedMutexThread(LPVOID lpParam)
{
    BOOL bTimedOut =  FALSE;
    THREADDATA *lpThreadData = (THREADDATA *)lpParam;

    /* Wait on the Mutex that was passed to us */
    if (WaitForSingleObject(lpThreadData->hMutex, 10000) == WAIT_TIMEOUT)
    {
        /* The Mutex was not signaled in the allotted time */
        bTimedOut = TRUE;
    }
    if (ReleaseMutex(lpThreadData->hMutex) == FALSE)
    {
        Trace("ERROR: ReleaseMutex failed.\n");
        lpThreadData->bReturnCode = FALSE;
        return  0;
    }

    /* Indicate whether we timed out Waiting on the Mutex */
    lpThreadData->bReturnCode = bTimedOut;

    return 0;
}

/*
 * Testing Function
 *
 * Try some negative tests on ReleaseMutex
 */
BOOL NegativeReleaseMutexTests()
{
    HANDLE hMutex;
    BOOL bRet;
    BOOL bResults = TRUE;

    /*
     * Try calling ReleaseMutex on a null handle
     */
    hMutex = 0;
    bRet = ReleaseMutex(hMutex);

    if (bRet != 0)
    {
        Trace("Error: ReleaseMutex accepted null handle.\n");
        bResults =  FALSE;
    }

    /*
     * Try calling ReleaseMutex on an handle that we don't own
     */
    hMutex = CreateMutexW (NULL, TRUE, NULL);
    if (hMutex == 0)
    {
        Trace("Error: CreateMutex failed.\n");
        bResults =  FALSE;
    }

    bRet = ReleaseMutex(hMutex);
    bRet = ReleaseMutex(hMutex);

    if (bRet != FALSE)
    {
        Trace("Error: ReleaseMutex accepted unowned handle.\n");
        bResults =  FALSE;
    }

    if (CloseHandle(hMutex) == FALSE)
    {
        Trace("Error: CloseHandle failed.\n");
        bResults =  FALSE;
    }

    /*
     * Try calling ReleaseMutex on an handle that has been closed
     */
    hMutex = CreateMutexW (NULL, TRUE, NULL);
    if (hMutex == 0)
    {
        Trace("Error: CreateMutex failed.\n");
        bResults =  FALSE;
    }

    if (ReleaseMutex(hMutex) == FALSE)
    {
        Trace("Error: ReleaseMutex failed.\n");
        bResults =  FALSE;
    }
    if (CloseHandle(hMutex) == FALSE)
    {
        Trace("Error: CloseHandle failed.\n");
        bResults =  FALSE;
    }

    bRet = ReleaseMutex(hMutex);

    if (bRet != FALSE)
    {
        Trace("Error: ReleaseMutex accepted invalid handle.\n");
        bResults =  FALSE;
    }

    return bResults;
}


text:
package com.adamcrume.jmxmon.telemetry;

import static com.adamcrume.jmxmon.JMXMon.bundle;
import gov.nasa.arc.mct.components.AbstractComponent;
import gov.nasa.arc.mct.components.JAXBModelStatePersistence;
import gov.nasa.arc.mct.components.ModelStatePersistence;
import gov.nasa.arc.mct.components.PropertyDescriptor;
import gov.nasa.arc.mct.components.PropertyDescriptor.VisualControlDescriptor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import com.adamcrume.jmxmon.view.StringPropertyEditor;

public class JVMComponent extends AbstractComponent {
    private AtomicReference<JVM> model = new AtomicReference<JVM>(new JVM());

    @Override
    public boolean isLeaf() {
        return true;
    }

    @Override
    protected <T> T handleGetCapability(Class<T> capability) {
        if(ModelStatePersistence.class.isAssignableFrom(capability)) {
            JAXBModelStatePersistence<JVM> persistence = new JAXBModelStatePersistence<JVM>() {
                @Override
                protected JVM getStateToPersist() {
                    return model.get();
                }

                @Override
                protected void setPersistentState(JVM modelState) {
                    model.set(modelState);
                }

                @Override
                protected Class<JVM> getJAXBClass() {
                    return JVM.class;
                }
            };
            return capability.cast(persistence);
        }
        return null;
    }

    public JVM getModel() {
        return model.get();
    }

    @Override
    public List<PropertyDescriptor> getFieldDescriptors() {
        List<PropertyDescriptor> fields = new ArrayList<PropertyDescriptor>();
        JVM model = getModel();

        // TODO: Add validation
        PropertyDescriptor jmxURL = new PropertyDescriptor(bundle.getString("jvm.jmxURL.label"),
                new StringPropertyEditor(model, "jmxURL"), VisualControlDescriptor.TextField);
        jmxURL.setFieldMutable(true);
        fields.add(jmxURL);

        return fields;
    }
}


text:
class MoreDigits < ActiveRecord::Migration
  def up
    change_column :numbers, :digits, :bigint, null: false
  end

  def down
    change_column :numbers, :digits, :integer
  end
end


text:
'use strict';

var path = require('path');
var testHelpers = require('yeoman-generator').test;
var assert = require('yeoman-generator').assert;
var fs = require('fs');
var codeSt = require('./code-strings.js');

describe('yo pg-node with EcmaScript6 option', function(){

	before(function(done) {
		testHelpers.run(path.join(__dirname, '../app'))
		.inDir(path.join(__dirname, './tmp'))
		.withArguments(['test pg-Node es 6'])
		.withPrompts({
			language:'EcmaScript6',
			npmMods: 'lodash mocha'
		})
		.on('end', done);
	});

	it('creates expected files', function () {
		var expectedFiles = [
			'../testPgNodeEs6',
			'package.json',
			'gulpfile.js',
			'scripts/main.js',
			'jsconfig.json'
		];
    	assert.file(expectedFiles);
  	});
	// package.json
	it('should render main field in package.json as "scripts/main.js"', function(){
		assert.fileContent('package.json', /\"main\"\s*:\s*\"scripts\/main\.js\"/);
	});
	it('should contain version field with some valid value', function(){
		assert.fileContent('package.json', /\"version\"\s*:\s*\"\d\.\d\.\d\"/);
	});
	it('should render name field as "testPgNodeEs6" in package.json', function(){
		assert.fileContent('package.json', /\"name\"\s*:\s*\"testPgNodeEs6\"/);
	});
	// gulpfile
	it('should render files to watch correctly in gulpfile' , function(){;
		var filesToWatchDec = fs.readFileSync('gulpfile.js', 'utf8')
		.match(/var\sfilesToWatch\s=\s.*;/);
		var filesTowatch = filesToWatchDec[0].match(/\[.*\]/)[0];
		// quoting is important here. "['modname']" !== '["modname"]'
		assert.textEqual('["scripts/main.js"]', filesTowatch);
	});
	it('should contain a node process handling task', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpEs.node);
	});
	it('should contain a watching task', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpEs.watchScripts);
	});
	it('should contain a clean task', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpEs.clean);
	});
	it('should contain an empty process scripts task', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpEs.processJsFiles);
	});
	it('should contain an exit event handler for gulp', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpEs.nodeExitEventHandler);
	});
	it('should not render typescript code in gulpfile', function(){
		assert.noFileContent('gulpfile.js', 'var ts = require(\'gulp-typescript\');');
		assert.noFileContent('gulpfile.js', 'var merge = require(\'merge2\');');
		assert.fileContent('gulpfile.js', codeSt.gulpEs.processJsFiles);
	});
	// jsconfig.json
	it('should containe spected compiler options', function(){
		assert.fileContent('jsconfig.json', codeSt.jsconfigEs.compilerOptions);
	});
	it('should containe initial js files in "field" files', function(){
		assert.fileContent('jsconfig.json', codeSt.jsconfigEs.files);
	});
	// scripts/main.js
	it('should declare main.js script as strict mode', function(){
		assert.fileContent('scripts/main.js', codeSt.mainEs.strict);
	});// TODO: regexp requires in main.js
	it('should import modules we asked for in prompt', function(){
		assert.fileContent('scripts/main.js', codeSt.mainEs.imports);
	});
	// TODO: check gulpfiles acomplishes tasks correctly by testing each task
	// not the content
});

describe('yo pg-node with TypeScript option', function(){

	before(function(done) {
		testHelpers.run(path.join(__dirname, '../app'))
		.inDir(path.join(__dirname, './tmp'))
		.withArguments(['testPgNodeTs'])
		.withPrompts({
			language:'TypeScript',
			tsTypes: 'lodash mocha'
		})
		.on('end', done);
	});

	it('creates expected files', function () {
		var expectedFiles = [
			'../testPgNodeTs',
			'package.json',
			'gulpfile.js',
			'scripts/main.ts',
			'tsd.json',
			'tsconfig.json'
		];

    	assert.file(expectedFiles);
  	});
	// package.json
	it('should render main field in package.json as "scripts/main.js"', function(){
		assert.fileContent('package.json', /\"main\"\s*:\s*\"dist\/scripts\/main\.js\"/);
	});
	it('should contain version field with some valid value', function(){
		assert.fileContent('package.json', /\"version\"\s*:\s*\"\d\.\d\.\d\"/);
	});
	it('should render name field as "testPgNodeEs6" in package.json', function(){
		assert.fileContent('package.json', /\"name\"\s*:\s*\"testPgNodeTs\"/);
	});
	// gulpfile.json
	it('should render files to watch correctly in gulpfile' , function(){;
		var filesToWatchDec = fs.readFileSync('gulpfile.js', 'utf8')
		.match(/var\sfilesToWatch\s=\s.*;/);
		var filesTowatch = filesToWatchDec[0].match(/\[.*\]/)[0];
		// quoting is important here. "['modname']" !== '["modname"]'
		assert.textEqual('["scripts/main.ts"]', filesTowatch);
	});
	it('should contain a node process handling task', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpTs.node);
	});
	it('should contain a watching task', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpTs.watchScripts);
	});
	it('should contain a clean task', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpTs.clean);
	});
	it('should contain a process scripts task', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpTs.processJsFiles);
	});
	it('should contain an exit event handler for gulp', function(){
		assert.fileContent('gulpfile.js', codeSt.gulpTs.nodeExitEventHandler);
	});
	it('should require typescript related modules in gulpfile', function(){
		assert.fileContent('gulpfile.js', 'var ts = require(\'gulp-typescript\');');
		assert.fileContent('gulpfile.js', 'var merge = require(\'merge2\');');
	});
	// scripts/main.ts
	it('should containe reference importing sentence for TypeScript type definitions', function(){
		assert.fileContent('scripts/main.ts', codeSt.mainTs.tdReference);
	});
	it('should import modules we asked for in prompt', function(){
		assert.fileContent('scripts/main.ts', /import\s*\*\s*as\s*lodash\s*from\s*\'lodash\'/);
		assert.fileContent('scripts/main.ts', /import\s*\*\s*as\s*mocha\s*from\s*\'mocha\'/);
	});
	// tsconfig.js
	it('should contain compiler options', function(){
		assert.fileContent('tsconfig.json', codeSt.tsconfig.compilerOptions);
	});
	it('should contine files', function(){
		assert.fileContent('tsconfig.json', codeSt.tsconfig.files);
	});
	// TODO: check gulpfiles acomplishes tasks correctly by testing each taskMmm
	// not the content
});


text:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');

app.set('port', process.env.PORT || 3000);

app.disable('x-powered-by');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(multer());

app.get('/headers', function(req, res) {
    console.log('req.params: ' + JSON.stringify(req.params));
    console.log('req.query: ' + JSON.stringify(req.query));
    console.log('req.ip: ' + req.ip);
    console.log('req.path: ' + req.path);
    res.set('content-type', 'text/plain');
    res.status(201);
    var s ='';
    for(var attr in req.headers) {
        s += attr + ': ' + req.headers[attr] + '\n';
    }
    res.send(s);
});

app.post('/headers', function(req, res) {
    console.log(req.method);
    console.log(req.params);
    console.log(req.body);
    // res.set('content-type', 'text/plain');
    // res.status(201);
    // var s ='';
    // for(var attr in req.headers) {
    //     s += attr + ': ' + req.headers[attr] + '\n';
    // }
    // res.end('POST issued.');
    res.json({who: 'me', me: 'sb'});
});

app.get('/', function(req, res) {
    res.type('text/plain');
    res.send('Meadowlark Travel');
});

app.get('/about', function(req, res) {
    res.type('text/plain');
    res.send('About Meadowlark Travel');
});

app.use(function(req, res) {
    res.type('text/plain');
    res.status(404);
    res.send('404 - Not Found');
});

app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.type('text/plain');
    res.status(500);
    res.send('500 - Server Error');
});

// console.log(app.get('port'));

app.listen(app.get('port'), function() {
    console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl-c to terminate.');
});


text:
<?php

namespace Oro\Bundle\ApiBundle\Tests\Unit\Form\DataTransformer;

use Oro\Bundle\ApiBundle\Form\DataTransformer\NullValueTransformer;
use Symfony\Component\Form\DataTransformerInterface;

class NullValueTransformerTest extends \PHPUnit\Framework\TestCase
{
    /** @var \PHPUnit\Framework\MockObject\MockObject|DataTransformerInterface */
    private $innerTransformer;

    /** @var NullValueTransformer */
    private $nullValueTransformer;

    protected function setUp()
    {
        $this->innerTransformer = $this->createMock(DataTransformerInterface::class);

        $this->nullValueTransformer = new NullValueTransformer($this->innerTransformer);
    }

    public function testInnerTransformerGetterAndSetter()
    {
        self::assertSame($this->innerTransformer, $this->nullValueTransformer->getInnerTransformer());

        $anotherInnerTransformer = $this->createMock(DataTransformerInterface::class);
        $this->nullValueTransformer->setInnerTransformer($anotherInnerTransformer);
        self::assertSame($anotherInnerTransformer, $this->nullValueTransformer->getInnerTransformer());
    }

    public function testTransformForNull()
    {
        $this->innerTransformer->expects(self::never())
            ->method('transform');

        self::assertNull($this->nullValueTransformer->transform(null));
    }

    public function testTransformForNotNull()
    {
        $value = 'test';
        $transformedValue = 'transformed';

        $this->innerTransformer->expects(self::once())
            ->method('transform')
            ->with($value)
            ->willReturn($transformedValue);

        self::assertEquals($transformedValue, $this->nullValueTransformer->transform($value));
    }

    public function testReverseTransformForNull()
    {
        $transformedValue = 'transformed';

        $this->innerTransformer->expects(self::once())
            ->method('reverseTransform')
            ->with(self::identicalTo(''))
            ->willReturn($transformedValue);

        self::assertEquals($transformedValue, $this->nullValueTransformer->reverseTransform(null));
    }

    public function testReverseTransformForEmptyString()
    {
        $transformedValue = 'transformed';

        $this->innerTransformer->expects(self::once())
            ->method('reverseTransform')
            ->with(self::identicalTo(''))
            ->willReturn($transformedValue);

        self::assertEquals($transformedValue, $this->nullValueTransformer->reverseTransform(''));
    }

    public function testReverseTransformWhenInnerTransformerReturnsNullAndInputValueIsEmptyString()
    {
        $this->innerTransformer->expects(self::once())
            ->method('reverseTransform')
            ->with(self::identicalTo(''))
            ->willReturn(null);

        self::assertSame('', $this->nullValueTransformer->reverseTransform(''));
    }

    public function testReverseTransformWhenInnerTransformerReturnsNullButInputValueIsNotEmptyString()
    {
        $value = 'test';

        $this->innerTransformer->expects(self::once())
            ->method('reverseTransform')
            ->with($value)
            ->willReturn(null);

        self::assertNull($this->nullValueTransformer->reverseTransform($value));
    }

    public function testReverseTransformForNotNullAndNotEmptyString()
    {
        $value = 'test';
        $transformedValue = 'transformed';

        $this->innerTransformer->expects(self::once())
            ->method('reverseTransform')
            ->with($value)
            ->willReturn($transformedValue);

        self::assertEquals($transformedValue, $this->nullValueTransformer->reverseTransform($value));
    }
}