text:
import dedent from 'dedent';
import moment from 'moment-timezone';
import { Observable } from 'rx';
import debugFactory from 'debug';
import emoji from 'node-emoji';

import {
  frontEndChallengeId,
  dataVisChallengeId,
  backEndChallengeId
} from '../utils/constantStrings.json';
import certTypes from '../utils/certTypes.json';
import {
  ifNoUser401,
  ifNoUserRedirectTo
} from '../utils/middleware';
import { observeQuery } from '../utils/rx';
import {
  prepUniqueDays,
  calcCurrentStreak,
  calcLongestStreak
} from '../utils/user-stats';
import supportedLanguages from '../../common/utils/supported-languages';
import createNameIdMap from '../../common/utils/create-name-id-map';
import { cachedMap } from '../utils/map';

const debug = debugFactory('fcc:boot:user');
const sendNonUserToMap = ifNoUserRedirectTo('/map');
const certIds = {
  [certTypes.frontEnd]: frontEndChallengeId,
  [certTypes.dataVis]: dataVisChallengeId,
  [certTypes.backEnd]: backEndChallengeId
};

const certViews = {
  [certTypes.frontEnd]: 'certificate/front-end.jade',
  [certTypes.dataVis]: 'certificate/data-vis.jade',
  [certTypes.backEnd]: 'certificate/back-end.jade',
  [certTypes.fullStack]: 'certificate/full-stack.jade'
};

const certText = {
  [certTypes.frontEnd]: 'Front End certified',
  [certTypes.dataVis]: 'Data Vis Certified',
  [certTypes.backEnd]: 'Back End Certified',
  [certTypes.fullStack]: 'Full Stack Certified'
};

const dateFormat = 'MMM DD, YYYY';

function replaceScriptTags(value) {
  return value
    .replace(/<script>/gi, 'fccss')
    .replace(/<\/script>/gi, 'fcces');
}

function replaceFormAction(value) {
  return value.replace(/<form[^>]*>/, function(val) {
    return val.replace(/action(\s*?)=/, 'fccfaa$1=');
  });
}

function encodeFcc(value = '') {
  return replaceScriptTags(replaceFormAction(value));
}

function isAlgorithm(challenge) {
  // test if name starts with hike/waypoint/basejump/zipline
  // fix for bug that saved different challenges with incorrect
  // challenge types
  return !(/^(waypoint|hike|zipline|basejump)/i).test(challenge.name) &&
    +challenge.challengeType === 5;
}

function isProject(challenge) {
  return +challenge.challengeType === 3 ||
    +challenge.challengeType === 4;
}

function getChallengeGroup(challenge) {
  if (isProject(challenge)) {
    return 'projects';
  } else if (isAlgorithm(challenge)) {
    return 'algorithms';
  }
  return 'challenges';
}

// buildDisplayChallenges(
//   entities: { challenge: Object, challengeIdToName: Object },
//   challengeMap: Object,
//   tz: String
// ) => Observable[{
//   algorithms: Array,
//   projects: Array,
//   challenges: Array
// }]
function buildDisplayChallenges(
  { challenge: challengeMap = {}, challengeIdToName },
  userChallengeMap = {},
  timezone
) {
  return Observable.from(Object.keys(userChallengeMap))
    .map(challengeId => userChallengeMap[challengeId])
    .map(userChallenge => {
      const challengeId = userChallenge.id;
      const challenge = challengeMap[ challengeIdToName[challengeId] ];
      let finalChallenge = { ...userChallenge, ...challenge };
      if (userChallenge.completedDate) {
        finalChallenge.completedDate = moment
          .tz(userChallenge.completedDate, timezone)
          .format(dateFormat);
      }

      if (userChallenge.lastUpdated) {
        finalChallenge.lastUpdated = moment
          .tz(userChallenge.lastUpdated, timezone)
          .format(dateFormat);
      }

      return finalChallenge;
    })
    .filter(({ challengeType }) => challengeType !== 6)
    .groupBy(getChallengeGroup)
    .flatMap(group$ => {
      return group$.toArray().map(challenges => ({
        [getChallengeGroup(challenges[0])]: challenges
      }));
    })
    .reduce((output, group) => ({ ...output, ...group}), {})
    .map(groups => ({
      algorithms: groups.algorithms || [],
      projects: groups.projects ? groups.projects.reverse() : [],
      challenges: groups.challenges ? groups.challenges.reverse() : []
    }));
}

module.exports = function(app) {
  const router = app.loopback.Router();
  const api = app.loopback.Router();
  const User = app.models.User;
  const Block = app.models.Block;
  const map$ = cachedMap(Block);
  function findUserByUsername$(username, fields) {
    return observeQuery(
      User,
      'findOne',
      {
        where: { username },
        fields
      }
    );
  }

  router.get('/login', function(req, res) {
    res.redirect(301, '/signin');
  });
  router.get('/logout', function(req, res) {
    res.redirect(301, '/signout');
  });
  router.get('/signup', getEmailSignup);
  router.get('/signin', getSignin);
  router.get('/signout', signout);
  router.get('/forgot', getForgot);
  api.post('/forgot', postForgot);
  router.get('/reset-password', getReset);
  api.post('/reset-password', postReset);
  router.get('/email-signup', getEmailSignup);
  router.get('/email-signin', getEmailSignin);
  router.get('/deprecated-signin', getDepSignin);
  router.get('/update-email', getUpdateEmail);
  router.get(
    '/delete-my-account',
    sendNonUserToMap,
    showDelete
  );
  api.post(
    '/account/delete',
    ifNoUser401,
    postDeleteAccount
  );
  api.get(
    '/account',
    sendNonUserToMap,
    getAccount
  );
  router.get(
    '/reset-my-progress',
    sendNonUserToMap,
    showResetProgress
  );
  api.post(
    '/account/resetprogress',
    ifNoUser401,
    postResetProgress
  );

  api.get(
    '/account/unlink/:social',
    sendNonUserToMap,
    getUnlinkSocial
  );

  // Ensure these are the last routes!
  api.get(
    '/:username/front-end-certification',
    showCert.bind(null, certTypes.frontEnd)
  );

  api.get(
    '/:username/data-visualization-certification',
    showCert.bind(null, certTypes.dataVis)
  );

  api.get(
    '/:username/back-end-certification',
    showCert.bind(null, certTypes.backEnd)
  );

  api.get(
    '/:username/full-stack-certification',
    (req, res) => res.redirect(req.url.replace('full-stack', 'back-end'))
  );

  router.get('/:username', showUserProfile);

  app.use('/:lang', router);
  app.use(api);

  function getSignin(req, res) {
    if (req.user) {
      return res.redirect('/');
    }
    return res.render('account/signin', {
      title: 'Sign in to freeCodeCamp'
    });
  }

  function signout(req, res) {
    req.logout();
    res.redirect('/');
  }

  function getDepSignin(req, res) {
    if (req.user) {
      return res.redirect('/');
    }
    return res.render('account/deprecated-signin', {
      title: 'Sign in to freeCodeCamp using a Deprecated Login'
    });
  }

  function getUpdateEmail(req, res) {
    if (!req.user) {
      return res.redirect('/');
    }
    return res.render('account/update-email', {
      title: 'Update your Email'
    });
  }

  function getEmailSignin(req, res) {
    if (req.user) {
      return res.redirect('/');
    }
    return res.render('account/email-signin', {
      title: 'Sign in to freeCodeCamp using your Email Address'
    });
  }

  function getEmailSignup(req, res) {
    if (req.user) {
      return res.redirect('/');
    }
    return res.render('account/email-signup', {
      title: 'Sign up for freeCodeCamp using your Email Address'
    });
  }

  function getAccount(req, res) {
    const { username } = req.user;
    return res.redirect('/' + username);
  }

  function getUnlinkSocial(req, res, next) {
    const { user } = req;
    const { username } = user;

    let social = req.params.social;
    if (!social) {
      req.flash('errors', {
        msg: 'No social account found'
      });
      return res.redirect('/' + username);
    }

    social = social.toLowerCase();
    const validSocialAccounts = ['twitter', 'linkedin'];
    if (validSocialAccounts.indexOf(social) === -1) {
      req.flash('errors', {
        msg: 'Invalid social account'
      });
      return res.redirect('/' + username);
    }

    if (!user[social]) {
      req.flash('errors', {
        msg: `No ${social} account associated`
      });
      return res.redirect('/' + username);
    }

    const query = {
      where: {
        provider: social
      }
    };

    return user.identities(query, function(err, identities) {
      if (err) { return next(err); }

      // assumed user identity is unique by provider
      let identity = identities.shift();
      if (!identity) {
        req.flash('errors', {
          msg: 'No social account found'
        });
        return res.redirect('/' + username);
      }

      return identity.destroy(function(err) {
        if (err) { return next(err); }

        const updateData = { [social]: null };

        return user.update$(updateData)
          .subscribe(() => {
            debug(`${social} has been unlinked successfully`);

            req.flash('info', {
              msg: `You\'ve successfully unlinked your ${social}.`
            });
            return res.redirect('/' + username);
          }, next);
      });
    });
  }

  function showUserProfile(req, res, next) {
    const username = req.params.username.toLowerCase();
    const { user } = req;

    // timezone of signed-in account
    // to show all date related components
    // using signed-in account's timezone
    // not of the profile she is viewing
    const timezone = user && user.timezone ?
      user.timezone :
      'UTC';

    const query = {
      where: { username },
      include: 'pledge'
    };

    return User.findOne$(query)
      .filter(userPortfolio => {
        if (!userPortfolio) {
          next();
        }
        return !!userPortfolio;
      })
      .flatMap(userPortfolio => {
        userPortfolio = userPortfolio.toJSON();

        const timestamps = userPortfolio
          .progressTimestamps
          .map(objOrNum => {
            return typeof objOrNum === 'number' ?
              objOrNum :
              objOrNum.timestamp;
          });

        const uniqueDays = prepUniqueDays(timestamps, timezone);

        userPortfolio.currentStreak = calcCurrentStreak(uniqueDays, timezone);
        userPortfolio.longestStreak = calcLongestStreak(uniqueDays, timezone);

        const calender = userPortfolio
          .progressTimestamps
          .map((objOrNum) => {
            return typeof objOrNum === 'number' ?
              objOrNum :
              objOrNum.timestamp;
          })
          .filter((timestamp) => {
            return !!timestamp;
          })
          .reduce((data, timeStamp) => {
            data[(timeStamp / 1000)] = 1;
            return data;
          }, {});

        if (userPortfolio.isCheater && !user) {
          req.flash('errors', {
            msg: dedent`
              Upon review, this account has been flagged for academic
              dishonesty. If you're the owner of this account contact
              team@freecodecamp.com for details.
            `
          });
        }

        if (userPortfolio.bio) {
          userPortfolio.bio = emoji.emojify(userPortfolio.bio);
        }

        return map$.map(({ entities }) => createNameIdMap(entities))
          .flatMap(entities => buildDisplayChallenges(
            entities,
            userPortfolio.challengeMap,
            timezone
          ))
          .map(displayChallenges => ({
            ...userPortfolio,
            ...displayChallenges,
            title: 'Camper ' + userPortfolio.username + '\'s Code Portfolio',
            calender,
            github: userPortfolio.githubURL,
            moment,
            encodeFcc,
            supportedLanguages
          }));
      })
      .doOnNext(data => {
        return res.render('account/show', data);
      })
      .subscribe(
        () => {},
        next
      );
  }

  function showCert(certType, req, res, next) {
    const username = req.params.username.toLowerCase();
    const certId = certIds[certType];
    return findUserByUsername$(username, {
          isGithubCool: true,
          isCheater: true,
          isLocked: true,
          isFrontEndCert: true,
          isDataVisCert: true,
          isBackEndCert: true,
          isFullStackCert: true,
          isHonest: true,
          username: true,
          name: true,
          challengeMap: true
      })
      .subscribe(
        user => {
          if (!user) {
            req.flash('errors', {
              msg: `We couldn't find a user with the username ${username}`
            });
            return res.redirect('/');
          }
          if (!user.isGithubCool) {
            req.flash('errors', {
              msg: dedent`
                This user needs to link GitHub with their account
                in order for others to be able to view their certificate.
              `
            });
            return res.redirect('back');
          }

          if (user.isCheater) {
            return res.redirect(`/${user.username}`);
          }

          if (user.isLocked) {
            req.flash('errors', {
              msg: dedent`
                ${username} has chosen to make their profile
                  private. They will need to make their profile public
                  in order for others to be able to view their certificate.
              `
            });
            return res.redirect('back');
          }
          if (!user.isHonest) {
            req.flash('errors', {
              msg: dedent`
                ${username} has not yet agreed to our Academic Honesty Pledge.
              `
            });
            return res.redirect('back');
          }

          if (user[certType]) {

            const { challengeMap = {} } = user;
            const { completedDate = new Date() } = challengeMap[certId] || {};

            return res.render(
              certViews[certType],
              {
                username: user.username,
                date: moment(new Date(completedDate)).format('MMMM D, YYYY'),
                name: user.name
              }
            );
          }
          req.flash('errors', {
            msg: `Looks like user ${username} is not ${certText[certType]}`
          });
          return res.redirect('back');
        },
        next
      );
  }

  function showDelete(req, res) {
    return res.render('account/delete', { title: 'Delete My Account!' });
  }

  function postDeleteAccount(req, res, next) {
    User.destroyById(req.user.id, function(err) {
      if (err) { return next(err); }
      req.logout();
      req.flash('info', { msg: 'You\'ve successfully deleted your account.' });
      return res.redirect('/');
    });
  }

  function showResetProgress(req, res) {
    return res.render('account/reset-progress', { title: 'Reset My Progress!'
    });
  }

  function postResetProgress(req, res, next) {
    User.findById(req.user.id, function(err, user) {
      if (err) { return next(err); }
      return user.updateAttributes({
        progressTimestamps: [{
          timestamp: Date.now()
        }],
        currentStreak: 0,
        longestStreak: 0,
        currentChallengeId: '',
        isBackEndCert: false,
        isFullStackCert: false,
        isDataVisCert: false,
        isFrontEndCert: false,
        challengeMap: {},
        challegesCompleted: []
      }, function(err) {
        if (err) { return next(err); }
        req.flash('info', { msg: 'You\'ve successfully reset your progress.' });
        return res.redirect('/');
      });
    });
  }

  function getReset(req, res) {
    if (!req.accessToken) {
      req.flash('errors', { msg: 'access token invalid' });
      return res.render('account/forgot');
    }
    return res.render('account/reset', {
      title: 'Reset your Password',
      accessToken: req.accessToken.id
    });
  }

  function postReset(req, res, next) {
    const errors = req.validationErrors();
    const { password } = req.body;

    if (errors) {
      req.flash('errors', errors);
      return res.redirect('back');
    }

    return User.findById(req.accessToken.userId, function(err, user) {
      if (err) { return next(err); }
      return user.updateAttribute('password', password, function(err) {
        if (err) { return next(err); }

        debug('password reset processed successfully');
        req.flash('info', { msg: 'You\'ve successfully reset your password.' });
        return res.redirect('/');
      });
    });
  }

  function getForgot(req, res) {
    if (req.isAuthenticated()) {
      return res.redirect('/');
    }
    return res.render('account/forgot', {
      title: 'Forgot Password'
    });
  }

  function postForgot(req, res) {
    req.validate('email', 'Email format is not valid').isEmail();
    const errors = req.validationErrors();
    const email = req.body.email.toLowerCase();

    if (errors) {
      req.flash('errors', errors);
      return res.redirect('/forgot');
    }

    return User.resetPassword({
      email: email
    }, function(err) {
      if (err) {
        req.flash('errors', err.message);
        return res.redirect('/forgot');
      }

      req.flash('info', {
        msg: 'An e-mail has been sent to ' +
        email +
        ' with further instructions.'
      });
      return res.render('account/forgot');
    });
  }
};


text:
/*
  Copyright 2013  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaims all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *  \brief USB device standard request management.
 *
 *  This file contains the function prototypes necessary for the processing of incoming standard control requests
 *  when the library is in USB device mode.
 *
 *  \note This file should not be included directly. It is automatically included as needed by the USB driver
 *        dispatch header located in LUFA/Drivers/USB/USB.h.
 */

#ifndef __DEVICESTDREQ_H__
#define __DEVICESTDREQ_H__

	/* Includes: */
		#include "Common.h"
		#include "USBMode.h"
		#include "StdDescriptors.h"
		#include "Events.h"
		#include "StdRequestType.h"
		#include "USBTask.h"
		#include "USBController.h"

	/* Enable C linkage for C++ Compilers: */
		#if defined(__cplusplus)
			extern "C" {
		#endif

	/* Preprocessor Checks: */
		#if !defined(__INCLUDE_FROM_USB_DRIVER)
			#error Do not include this file directly. Include LUFA/Drivers/USB/USB.h instead.
		#endif

	/* Public Interface - May be used in end-application: */
		/* Enums: */
			#if defined(ARCH_HAS_MULTI_ADDRESS_SPACE) || defined(__DOXYGEN__)
				/** Enum for the possible descriptor memory spaces, for the \c MemoryAddressSpace parameter of the
				 *  \ref CALLBACK_USB_GetDescriptor() function. This can be used when none of the \c USE_*_DESCRIPTORS
				 *  compile time options are used, to indicate in which memory space the descriptor is stored.
				 *
				 *  \ingroup Group_Device
				 */
				enum USB_DescriptorMemorySpaces_t
				{
					#if defined(ARCH_HAS_FLASH_ADDRESS_SPACE) || defined(__DOXYGEN__)
					MEMSPACE_FLASH    = 0, /**< Indicates the requested descriptor is located in FLASH memory. */
					#endif
					#if defined(ARCH_HAS_EEPROM_ADDRESS_SPACE) || defined(__DOXYGEN__)
					MEMSPACE_EEPROM   = 1, /**< Indicates the requested descriptor is located in EEPROM memory. */
					#endif
					MEMSPACE_RAM      = 2, /**< Indicates the requested descriptor is located in RAM memory. */
				};
			#endif

		/* Global Variables: */
			/** Indicates the currently set configuration number of the device. USB devices may have several
			 *  different configurations which the host can select between; this indicates the currently selected
			 *  value, or 0 if no configuration has been selected.
			 *
			 *  \attention This variable should be treated as read-only in the user application, and never manually
			 *             changed in value.
			 *
			 *  \ingroup Group_Device
			 */
			extern uint8_t USB_Device_ConfigurationNumber;

			#if !defined(NO_DEVICE_REMOTE_WAKEUP)
				/** Indicates if the host is currently allowing the device to issue remote wakeup events. If this
				 *  flag is cleared, the device should not issue remote wakeup events to the host.
				 *
				 *  \attention This variable should be treated as read-only in the user application, and never manually
				 *             changed in value.
				 *
				 *  \note To reduce FLASH usage of the compiled applications where Remote Wakeup is not supported,
				 *        this global and the underlying management code can be disabled by defining the
				 *        \c NO_DEVICE_REMOTE_WAKEUP token in the project makefile and passing it to the compiler via
				 *        the -D switch.
				 *
				 *  \ingroup Group_Device
				 */
				extern bool USB_Device_RemoteWakeupEnabled;
			#endif

			#if !defined(NO_DEVICE_SELF_POWER)
				/** Indicates if the device is currently being powered by its own power supply, rather than being
				 *  powered by the host's USB supply. This flag should remain cleared if the device does not
				 *  support self powered mode, as indicated in the device descriptors.
				 *
				 *  \ingroup Group_Device
				 */
				extern bool USB_Device_CurrentlySelfPowered;
			#endif

	/* Private Interface - For use in library only: */
	#if !defined(__DOXYGEN__)
		#if defined(USE_RAM_DESCRIPTORS) && defined(USE_EEPROM_DESCRIPTORS)
			#error USE_RAM_DESCRIPTORS and USE_EEPROM_DESCRIPTORS are mutually exclusive.
		#elif defined(USE_RAM_DESCRIPTORS) && defined(USE_FLASH_DESCRIPTORS)
			#error USE_RAM_DESCRIPTORS and USE_FLASH_DESCRIPTORS are mutually exclusive.
		#elif defined(USE_FLASH_DESCRIPTORS) && defined(USE_EEPROM_DESCRIPTORS)
			#error USE_FLASH_DESCRIPTORS and USE_EEPROM_DESCRIPTORS are mutually exclusive.
		#elif defined(USE_FLASH_DESCRIPTORS) && defined(USE_EEPROM_DESCRIPTORS) && defined(USE_RAM_DESCRIPTORS)
			#error Only one of the USE_*_DESCRIPTORS modes should be selected.
		#endif

		/* Function Prototypes: */
			void USB_Device_ProcessControlRequest(void);

			#if defined(__INCLUDE_FROM_DEVICESTDREQ_C)
				static void USB_Device_SetAddress(void);
				static void USB_Device_SetConfiguration(void);
				static void USB_Device_GetConfiguration(void);
				static void USB_Device_GetDescriptor(void);
				static void USB_Device_GetStatus(void);
				static void USB_Device_ClearSetFeature(void);

				#if !defined(NO_INTERNAL_SERIAL) && (USE_INTERNAL_SERIAL != NO_DESCRIPTOR)
					static void USB_Device_GetInternalSerialDescriptor(void);
				#endif
			#endif
	#endif

	/* Disable C linkage for C++ Compilers: */
		#if defined(__cplusplus)
			}
		#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
"""
Request Body validating middleware.

"""

import functools
import webob

from tacker.api.validation import validators
from tacker.common import exceptions

def schema(request_body_schema):
    """Register a schema to validate request body.

    Registered schema will be used for validating request body just before
    API method executing.

    :param dict request_body_schema: a schema to validate request body

    """

    def add_validator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            schema_validator = validators._SchemaValidator(
                request_body_schema)
            try:
                schema_validator.validate(kwargs['body'])
            except KeyError:
                raise webob.exc.HTTPBadRequest(
                    explanation=_("Malformed request body"))

            return func(*args, **kwargs)
        return wrapper

    return add_validator

def query_schema(query_params_schema):
    """Register a schema to validate request query parameters.

    Registered schema will be used for validating request query params just
    before API method executing.

    :param query_params_schema: A dict, the JSON-Schema for validating the
                                query parameters.
    """

    def add_validator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # NOTE(tpatil): The second argument of the method
            # calling this method should always be 'request'.
            if 'request' in kwargs:
                req = kwargs['request']
            else:
                req = args[1]

            try:
                req.GET.dict_of_lists()
            except UnicodeDecodeError:
                msg = _('Query string is not UTF-8 encoded')
                raise exceptions.ValidationError(msg)

            query_opts = {}
            query_opts.update(req.GET)
            schema_validator = validators._SchemaValidator(
                query_params_schema)
            schema_validator.validate(query_opts)

            return func(*args, **kwargs)

        return wrapper

    return add_validator


text: C lib for personal use:)


text:
layout: post
title: Shrook 2 Goes Final!
date: '2004-03-22 08:56:02 -0700'
mt_id: 716
blog_id: 1
post_id: 716
basename: shrook-2-goes-final
categories:
- mac-os-x
---

The long-awaited (by me, at least) successor to Shrook has gotten out of the beta stage and hit final today. I've been eagerly awaiting this event because the preview/beta looked really good, but had some chokepoints that I figured the final release would solve. I'll update with my thoughts on this new release.


text:
using NUnit.Framework;

namespace Vtex.SemanticVersioning.Tests
{
    [TestFixture]
    class VersionTests
    {
        [Test]
        public void Parse_strict_full_version()
        {
            // Act
            var version = Version.Parse("1.2.3-beta.4+release.55");

            // Assert
            Assert.That(version.Major, Is.EqualTo(1));
            Assert.That(version.Minor, Is.EqualTo(2));
            Assert.That(version.Patch, Is.EqualTo(3));
            Assert.That(version.Prerelease, Is.EqualTo(new VersionIdentifier[] { "beta", 4 }));
            Assert.That(version.Build, Is.EqualTo(new[] {"release", "55"}));
        }

        [Test]
        public void Parse_loose_version()
        {
            // Act
            var version = Version.Parse("=1.2.3beta.4", true);

            // Assert
            Assert.That(version.Major, Is.EqualTo(1));
            Assert.That(version.Minor, Is.EqualTo(2));
            Assert.That(version.Patch, Is.EqualTo(3));
            Assert.That(version.Prerelease, Is.EqualTo(new VersionIdentifier[] { "beta", 4 }));
        }

        [Test]
        public void Should_accept_leading_v_character()
        {
            // Act
            var version = Version.Parse("v1.2.3-beta.4+release.55");

            // Assert
            Assert.That(version.Major, Is.EqualTo(1));
            Assert.That(version.Minor, Is.EqualTo(2));
            Assert.That(version.Patch, Is.EqualTo(3));
            Assert.That(version.Prerelease, Is.EqualTo(new VersionIdentifier[] { "beta", 4 }));
            Assert.That(version.Build, Is.EqualTo(new[] { "release", "55" }));
        }

        [Test]
        public void Should_throw_error_for_invalid_version()
        {
            // Act & Assert
            Assert.That(() => Version.Parse("a.b.c"),
                Throws.Exception);
        }

        class ComparePre
        {
            [Test]
            public void Equal_prereleases()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta", 3 } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta", 3 } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(0));
            }

            [Test]
            public void Greater_prerelease_string()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta" } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { "alpha" } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(1));
            }

            [Test]
            public void Extra_prerelease_number()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta", 1 } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta" } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(1));
            }

            [Test]
            public void Greater_prerelease_number()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta", 5 } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta", 4 } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(1));
            }

            [Test]
            public void Smaller_prerelease_string()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta" } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { "delta" } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(-1));
            }

            [Test]
            public void Less_prerelease_number()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta" } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta", 1 } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(-1));
            }

            [Test]
            public void Smaller_prerelease_number()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta", 4 } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta", 5 } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(-1));
            }

            [Test]
            public void Release_should_be_greater_than_prerelease()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta" } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(1));
            }

            [Test]
            public void Prerelease_should_be_smaller_than_release()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { "beta" } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(-1));
            }

            [Test]
            public void Should_equal_without_prerelease()
            {
                // Arrange
                var version = new TestableVersion { Prerelease = new VersionIdentifier[] { } };
                var other = new TestableVersion { Prerelease = new VersionIdentifier[] { } };

                // Act
                var result = version.ComparePre(other);

                // Assert
                Assert.That(result, Is.EqualTo(0));
            }
        }

        class CompareMain
        {
            [Test]
            public void Greater_due_to_major()
            {
                // Arrange
                var version = new TestableVersion {Major = 2};
                var other = new TestableVersion {Major = 1};

                // Act
                var result = version.CompareMain(other);

                // Assert
                Assert.That(result, Is.EqualTo(1));
            }

            [Test]
            public void Smaller_due_to_major()
            {
                // Arrange
                var version = new TestableVersion {Major = 2};
                var other = new TestableVersion {Major = 3};

                // Act
                var result = version.CompareMain(other);

                // Assert
                Assert.That(result, Is.EqualTo(-1));
            }

            [Test]
            public void Greater_due_to_minor()
            {
                // Arrange
                var version = new TestableVersion { Major = 1, Minor = 2};
                var other = new TestableVersion { Major = 1, Minor = 1};

                // Act
                var result = version.CompareMain(other);

                // Assert
                Assert.That(result, Is.EqualTo(1));
            }

            [Test]
            public void Smaller_due_to_minor()
            {
                // Arrange
                var version = new TestableVersion { Major = 1, Minor = 2};
                var other = new TestableVersion { Major = 1, Minor = 3};

                // Act
                var result = version.CompareMain(other);

                // Assert
                Assert.That(result, Is.EqualTo(-1));
            }

            [Test]
            public void Greater_due_to_patch()
            {
                // Arrange
                var version = new TestableVersion { Major = 1, Minor = 2, Patch = 3};
                var other = new TestableVersion { Major = 1, Minor = 2, Patch = 2};

                // Act
                var result = version.CompareMain(other);

                // Assert
                Assert.That(result, Is.EqualTo(1));
            }

            [Test]
            public void Smaller_due_to_patch()
            {
                // Arrange
                var version = new TestableVersion { Major = 1, Minor = 2, Patch = 3};
                var other = new TestableVersion { Major = 1, Minor = 2, Patch = 4};

                // Act
                var result = version.CompareMain(other);

                // Assert
                Assert.That(result, Is.EqualTo(-1));
            }

            [Test]
            public void Equal_main_versions()
            {
                // Arrange
                var version = new TestableVersion { Major = 1, Minor = 2, Patch = 3};
                var other = new TestableVersion { Major = 1, Minor = 2, Patch = 3};

                // Act
                var result = version.CompareMain(other);

                // Assert
                Assert.That(result, Is.EqualTo(0));
            }
        }

        class Operators
        {
            [TestCase("1.2.3", "1.2.3", true)]
            [TestCase("1.2.3", "1.2.4", false)]
            [TestCase("1.2.3", "1.2.3-beta", false)]
            public void Equals(string v1, string v2, bool shouldEqual)
            {
                // Arrange
                var version = Version.Parse(v1);
                var other = Version.Parse(v2);

                // Act & Assert
                Assert.That(version == other, Is.EqualTo(shouldEqual));
                Assert.That(version == v2, Is.EqualTo(shouldEqual));
                Assert.That(v1 == other, Is.EqualTo(shouldEqual));
            }

            [TestCase("1.2.3", "1.2.3", false)]
            [TestCase("1.2.3", "1.2.4", true)]
            [TestCase("1.2.3", "1.2.3-beta", true)]
            public void Not_equals(string v1, string v2, bool shouldEqual)
            {
                // Arrange
                var version = Version.Parse(v1);
                var other = Version.Parse(v2);

                // Act & Assert
                Assert.That(version != other, Is.EqualTo(shouldEqual));
                Assert.That(version != v2, Is.EqualTo(shouldEqual));
                Assert.That(v1 != other, Is.EqualTo(shouldEqual));
            }

            [TestCase("1.2.3-beta", "1.2.3-beta.0", true)]
            [TestCase("1.2.3", "1.2.4", true)]
            [TestCase("1.2.3", "1.3.0", true)]
            [TestCase("1.2.3", "2.0.0", true)]
            [TestCase("1.2.3-beta", "1.2.3", true)]
            [TestCase("1.2.3-beta", "1.2.3-alpha", false)]
            [TestCase("1.2.3", "1.2.3", false)]
            public void Less_than(string v1, string v2, bool shouldEqual)
            {
                // Arrange
                var version = Version.Parse(v1);
                var other = Version.Parse(v2);

                // Act & Assert
                Assert.That(version < other, Is.EqualTo(shouldEqual));
                Assert.That(version < v2, Is.EqualTo(shouldEqual));
                Assert.That(v1 < other, Is.EqualTo(shouldEqual));
            }

            [TestCase("1.2.3-beta.0", "1.2.3-beta", true)]
            [TestCase("1.2.4", "1.2.3", true)]
            [TestCase("1.3.0", "1.2.3", true)]
            [TestCase("2.0.0", "1.2.3", true)]
            [TestCase("1.2.3", "1.2.3-beta", true)]
            [TestCase("1.2.3-alpha", "1.2.3-beta", false)]
            [TestCase("1.2.3", "1.2.3", false)]
            public void Greater_than(string v1, string v2, bool shouldEqual)
            {
                // Arrange
                var version = Version.Parse(v1);
                var other = Version.Parse(v2);

                // Act & Assert
                Assert.That(version > other, Is.EqualTo(shouldEqual));
                Assert.That(version > v2, Is.EqualTo(shouldEqual));
                Assert.That(v1 > other, Is.EqualTo(shouldEqual));
            }

            [TestCase("1.2.3-beta", "1.2.3-beta.0", true)]
            [TestCase("1.2.3", "1.2.4", true)]
            [TestCase("1.2.3", "1.3.0", true)]
            [TestCase("1.2.3", "2.0.0", true)]
            [TestCase("1.2.3-beta", "1.2.3", true)]
            [TestCase("1.2.3", "1.2.3", true)]
            [TestCase("1.2.3-beta", "1.2.3-alpha", false)]
            public void Less_than_or_equal(string v1, string v2, bool shouldEqual)
            {
                // Arrange
                var version = Version.Parse(v1);
                var other = Version.Parse(v2);

                // Act & Assert
                Assert.That(version <= other, Is.EqualTo(shouldEqual));
                Assert.That(version <= v2, Is.EqualTo(shouldEqual));
                Assert.That(v1 <= other, Is.EqualTo(shouldEqual));
            }

            [TestCase("1.2.3-beta.0", "1.2.3-beta", true)]
            [TestCase("1.2.4", "1.2.3", true)]
            [TestCase("1.3.0", "1.2.3", true)]
            [TestCase("2.0.0", "1.2.3", true)]
            [TestCase("1.2.3", "1.2.3-beta", true)]
            [TestCase("1.2.3", "1.2.3", true)]
            [TestCase("1.2.3-alpha", "1.2.3-beta", false)]
            public void Greater_than_or_equal(string v1, string v2, bool shouldEqual)
            {
                // Arrange
                var version = Version.Parse(v1);
                var other = Version.Parse(v2);

                // Act & Assert
                Assert.That(version >= other, Is.EqualTo(shouldEqual));
                Assert.That(version >= v2, Is.EqualTo(shouldEqual));
                Assert.That(v1 >= other, Is.EqualTo(shouldEqual));
            }
        }

        class Increment
        {
            [TestCase("1.2.3", "1.2.3-0")]
            [TestCase("1.2.3-beta", "1.2.3-beta.0")]
            [TestCase("1.2.3-beta.0", "1.2.3-beta.1")]
            [TestCase("1.2.3-beta.19", "1.2.3-beta.20")]
            [TestCase("1.2.3-some.1.thing.3.else", "1.2.3-some.1.thing.4.else")]
            public void Prerelease(string initial, string expected)
            {
                // Arrange
                var version = Version.Parse(initial);

                // Act
                version.Increment(VersionSegment.Prerelease);

                // Assert
                Assert.That(version.ToString(), Is.EqualTo(expected));
            }

            [TestCase("1.2.3", "1.2.4")]
            [TestCase("1.2.3-beta.4", "1.2.4")]
            public void Patch(string initial, string expected)
            {
                // Arrange
                var version = Version.Parse(initial);

                // Act
                version.Increment(VersionSegment.Patch);

                // Assert
                Assert.That(version.ToString(), Is.EqualTo(expected));
            }

            [TestCase("1.2.3", "1.3.0")]
            [TestCase("1.2.3-beta.4", "1.3.0")]
            public void Minor(string initial, string expected)
            {
                // Arrange
                var version = Version.Parse(initial);

                // Act
                version.Increment(VersionSegment.Minor);

                // Assert
                Assert.That(version.ToString(), Is.EqualTo(expected));
            }

            [TestCase("1.2.3", "2.0.0")]
            [TestCase("1.2.3-beta.4", "2.0.0")]
            public void Major(string initial, string expected)
            {
                // Arrange
                var version = Version.Parse(initial);

                // Act
                version.Increment(VersionSegment.Major);

                // Assert
                Assert.That(version.ToString(), Is.EqualTo(expected));
            }
        }
    }

    public class TestableVersion : Version
    {
        public new int ComparePre(Version other)
        {
            return base.ComparePre(other);
        }

        public new int CompareMain(Version other)
        {
            return base.CompareMain(other);
        }
    }
}


text:
package edu.cmu.lti.oaqa.cse.configuration

import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor._

object yamlTest {
import edu.cmu.lti.oaqa.cse.configuration.test.FooBar;import org.scalaide.worksheet.runtime.library.WorksheetSupport._; def main(args: Array[String])=$execute{;$skip(215);
val yaml =
"""foo: ahaaa""";System.out.println("""yaml  : String = """ + $show(yaml ));$skip(55); val res$0 =

new Yaml(new Constructor(FooBar.getClass)).load(yaml);System.out.println("""res0: <error> = """ + $show(res$0))}

}


text:
import unittest

import IECore

import Gaffer
import GafferTest

class GraphComponentPathTest( GafferTest.TestCase ) :

	def testRelative( self ) :

		r = Gaffer.GraphComponent()
		r["d"] = Gaffer.GraphComponent()
		r["d"]["e"] = Gaffer.GraphComponent()

		p = Gaffer.GraphComponentPath( r, "d" )
		self.assertEqual( str( p ), "d" )
		self.assertEqual( p.root(), "" )
		self.assertEqual( [ str( c ) for c in p.children() ], [ "d/e" ] )

		p2 = p.copy()
		self.assertEqual( str( p2 ), "d" )
		self.assertEqual( p2.root(), "" )
		self.assertEqual( [ str( c ) for c in p2.children() ], [ "d/e" ] )

	def testProperties( self ) :

		r = Gaffer.GraphComponent()
		r["d"] = Gaffer.GraphComponent()

		p = Gaffer.GraphComponentPath( r, "/d" )
		self.assertEqual( p.propertyNames(), [ "name", "fullName" ] )
		self.assertEqual( p.property( "name" ), "d" )
		self.assertEqual( p.property( "fullName" ), "/d" )

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


text:
(function() {
  var ArchiveEditor, File, Serializable, allowUnsafeNewFunction, archive, fs, path, url,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  path = require('path');

  url = require('url');

  allowUnsafeNewFunction = require('loophole').allowUnsafeNewFunction;

  archive = allowUnsafeNewFunction(function() {
    return require('ls-archive');
  });

  File = require('pathwatcher').File;

  fs = require('fs-plus');

  Serializable = require('serializable');

  module.exports = ArchiveEditor = (function(_super) {
    __extends(ArchiveEditor, _super);

    atom.deserializers.add(ArchiveEditor);

    ArchiveEditor.activate = function() {
      return atom.workspace.registerOpener(function(filePath) {
        if (filePath == null) {
          filePath = '';
        }
        if (!url.parse(filePath).protocol && archive.isPathSupported(filePath)) {
          return new ArchiveEditor({
            path: filePath
          });
        }
      });
    };

    function ArchiveEditor(_arg) {
      var path;
      path = _arg.path;
      this.file = new File(path);
    }

    ArchiveEditor.prototype.serializeParams = function() {
      return {
        path: this.getPath()
      };
    };

    ArchiveEditor.prototype.deserializeParams = function(params) {
      if (params == null) {
        params = {};
      }
      if (fs.isFileSync(params.path)) {
        return params;
      } else {
        return console.warn("Could not build archive editor for path '" + params.path + "' because that file no longer exists");
      }
    };

    ArchiveEditor.prototype.getPath = function() {
      return this.file.getPath();
    };

    ArchiveEditor.prototype.destroy = function() {
      var _ref;
      return (_ref = this.file) != null ? _ref.off() : void 0;
    };

    ArchiveEditor.prototype.getViewClass = function() {
      return require('./archive-editor-view');
    };

    ArchiveEditor.prototype.getTitle = function() {
      if (this.getPath() != null) {
        return path.basename(this.getPath());
      } else {
        return 'untitled';
      }
    };

    ArchiveEditor.prototype.getUri = function() {
      return this.getPath();
    };

    ArchiveEditor.prototype.isEqual = function(other) {
      return other instanceof ArchiveEditor && this.getUri() === other.getUri();
    };

    return ArchiveEditor;

  })(Serializable);

}).call(this);


text:
{-# OPTIONS_GHC -Wall #-}
module Language.Haskell.Exts.Desugar  where

import qualified Prelude
import Control.Applicative  ((<$>),(<*>))
import Language.Haskell.Exts.Unique

class Desugar a where
  desugar :: a -> Unique a

-- Applicative style of applying desugaring

infixl 4 **,$$
(**) :: Desugar a => Unique (a -> b) -> a -> Unique b
x ** y = x <*> desugar y

($$) :: Desugar a => (a -> b) -> a -> Unique b
x $$ y = x <$> desugar y


text:
bc-haskell
==========
See also; https://github.com/HaskellForCats/HaskellForCats


text:
package org.onosproject.bmv2.demo.app.ecmp;

import com.google.common.collect.ImmutableMap;
import org.onlab.util.ImmutableByteSequence;
import org.onosproject.bmv2.api.context.Bmv2HeaderTypeModel;
import org.onosproject.bmv2.api.runtime.Bmv2ExactMatchParam;
import org.onosproject.bmv2.api.runtime.Bmv2ExtensionSelector;
import org.onosproject.bmv2.api.utils.Bmv2TranslatorUtils;
import org.onosproject.net.flow.criteria.ExtensionSelector;

import static org.onosproject.bmv2.api.utils.Bmv2TranslatorUtils.fitByteSequence;
import static org.onosproject.bmv2.demo.app.ecmp.EcmpFabricApp.ECMP_CONTEXT;
import static org.onosproject.bmv2.demo.app.ecmp.EcmpInterpreter.*;

/**
 * Builder of ECMP group table extension selector.
 */
public class EcmpGroupTableSelectorBuilder {

    private int groupId;
    private int selector;

    /**
     * Sets the ECMP group ID.
     *
     * @param groupId an integer value
     * @return this
     */
    public EcmpGroupTableSelectorBuilder withGroupId(int groupId) {
        this.groupId = groupId;
        return this;
    }

    /**
     * Sets the ECMP selector.
     *
     * @param selector an integer value
     * @return this
     */
    public EcmpGroupTableSelectorBuilder withSelector(int selector) {
        this.selector = selector;
        return this;
    }

    /**
     * Returns a new extension selector.
     *
     * @return an extension selector
     */
    public ExtensionSelector build() {
        Bmv2HeaderTypeModel headerTypeModel = ECMP_CONTEXT.configuration().headerType(ECMP_METADATA_T);
        int groupIdBitWidth = headerTypeModel.field(GROUP_ID).bitWidth();
        int selectorBitWidth = headerTypeModel.field(SELECTOR).bitWidth();

        try {
            ImmutableByteSequence groupIdBs = fitByteSequence(ImmutableByteSequence.copyFrom(groupId),
                                                              groupIdBitWidth);
            ImmutableByteSequence selectorBs = fitByteSequence(ImmutableByteSequence.copyFrom(selector),
                                                               selectorBitWidth);

            Bmv2ExactMatchParam groupIdMatch = new Bmv2ExactMatchParam(groupIdBs);
            Bmv2ExactMatchParam hashMatch = new Bmv2ExactMatchParam(selectorBs);

            return new Bmv2ExtensionSelector(ImmutableMap.of(
                    ECMP_METADATA + "." + GROUP_ID, groupIdMatch,
                    ECMP_METADATA + "." + SELECTOR, hashMatch));

        } catch (Bmv2TranslatorUtils.ByteSequenceFitException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Office365UnifiedAPIFromAddinWeb.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}


text:
"""Contrib operations."""
from __future__ import absolute_import as _abs
from . import _make

def adaptive_max_pool2d(data,
                        output_size=None,
                        layout="NCHW"):
    r"""2D adaptive max pooling operator. This operator is experimental.

    This operator takes data as input and does 2D max value calculation
    across each window represented by WxH.

    In the default case, where the data_layout is `NCHW`
    a data Tensor with shape `(batch_size, in_channels, height, width)`,
    to produce an output Tensor with shape
    (batch_size, in_channels, output_height, output_width).

    The pooling kernel and stride sizes are automatically chosen for
    desired output sizes.

    For output_size:
        If this argument is not provided, input height and width will be used
        as output height and width.

        If a single integer is provided for output_size, the output size is
        (N x C x output_size x output_size) for any input (NCHW).

        If a tuple of integers (height, width) are provided for output_size,
        the output size is (N x C x height x width) for any input (NCHW).

    Parameters
    ----------
    data : tvm.relay.Expr
        The input data to the operator.

    output_size : tuple of int. optional
        Output height and width.

    layout : str, optional
        Layout of the input.

    Returns
    -------
    result : tvm.relay.Expr
        The computed result.
    """
    output_size = [] or output_size
    return _make.adaptive_max_pool2d(data, output_size, layout)

def adaptive_avg_pool2d(data,
                        output_size=None,
                        layout="NCHW"):
    r"""2D adaptive average pooling operator. This operator is experimental.

    This operator takes data as input and does 2D average value calculation
    across each window represented by WxH.

    In the default case, where the data_layout is `NCHW`
    a data Tensor with shape `(batch_size, in_channels, height, width)`,
    to produce an output Tensor with shape
    (batch_size, in_channels, output_height, output_width).

    The pooling kernel and stride sizes are automatically chosen for
    desired output sizes.

    For output_size:
        If this argument is not provided, input height and width will be used
        as output height and width.

        If a single integer is provided for output_size, the output size is
        (N x C x output_size x output_size) for any input (NCHW).

        If a tuple of integers (height, width) are provided for output_size,
        the output size is (N x C x height x width) for any input (NCHW).

    Parameters
    ----------
    data : tvm.relay.Expr
        The input data to the operator.

    output_size : tuple of int. optional
        Output height and width.

    layout : str, optional
        Layout of the input.

    Returns
    -------
    result : tvm.relay.Expr
        The computed result.
    """
    output_size = [] or output_size
    return _make.adaptive_avg_pool2d(data, output_size, layout)


text:
'use strict';
var common = require('../common');
var assert = require('assert');
var vm = require('vm');

assert.throws(function() {
  vm.isContext('string is not supported');
}, TypeError);

assert.strictEqual(vm.isContext({}), false);
assert.strictEqual(vm.isContext([]), false);

assert.strictEqual(vm.isContext(vm.createContext()), true);
assert.strictEqual(vm.isContext(vm.createContext([])), true);

var sandbox = { foo: 'bar' };
vm.createContext(sandbox);
assert.strictEqual(vm.isContext(sandbox), true);


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Assertions;

namespace GhostGen
{

    [RequireComponent(typeof(EventTrigger))]
    public class TapToTrigger : MonoBehaviour
    {
        private EventTrigger _eventTrigger;
        private UIView _view;
        private EventTrigger.Entry _onClickEntry;

        // Use this for initialization
        void Start()
        {
            _eventTrigger = GetComponent<EventTrigger>();
            _view = GetComponent<UIView>();
            Assert.IsNotNull(_eventTrigger);
            Assert.IsNotNull(_view);

            _onClickEntry = _eventTrigger.triggers.Find((x) => x.eventID == EventTriggerType.PointerClick);
            if (_onClickEntry == null)
            {
                _onClickEntry = new EventTrigger.Entry();
                _eventTrigger.triggers.Add(_onClickEntry);
            }
            _onClickEntry.eventID = EventTriggerType.PointerClick;
            _onClickEntry.callback.AddListener(_onClick);
        }

        void OnDestroy()
        {
            if (_onClickEntry != null)
            {
                _onClickEntry.callback.RemoveListener(_onClick);
            }
        }

        private void _onClick(BaseEventData e)
        {
            if (_view != null)
            {
                _view.OnTriggered(e);
            }
        }
    }
}


text:
try:
    from setuptools import setup, find_packages
except ImportError:
    import ez_setup
    ez_setup.use_setuptools()
from setuptools import setup, find_packages

setup(name="ampcrowd_client",
      version="0.0.4",
      description="A python client for using the AMPCrowd service.",
      license="Apache License 2.0",
      author="Daniel Haas",
      author_email="dhaas@cs.berkeley.edu",
      url="http://github.com/amplab/ampcrowd-client-py",
      packages = find_packages(),
      include_package_data = True,
      package_dir = {'ampcrowd_client' : 'ampcrowd_client'},
      scripts = [
      ],
      install_requires = [
        'tornado'
      ],
      keywords= "")


text:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/cpufreq.h>
#include <linux/cpu.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <asm/io.h>
#include "cpu-freq.h"
#include "pmu_dvfs.h"

static struct sun5i_cpu_freq_t  cpu_cur;    /* current cpu frequency configuration */
static unsigned int last_target = ~0;       /* backup last target frequency        */

static struct clk *clk_pll; /* pll clock handler */
static struct clk *clk_cpu; /* cpu clock handler */
static struct clk *clk_axi; /* axi clock handler */
static struct clk *clk_ahb; /* ahb clock handler */
static struct clk *clk_apb; /* apb clock handler */

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_verify
 *
 *Description: check if the cpu frequency policy is valid;
 *
 *Arguments  : policy    cpu frequency policy;
 *
 *Return     : result, return if verify ok, else return -EINVAL;
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static int sun5i_cpufreq_verify(struct cpufreq_policy *policy)
{
	if (policy->cpu != 0)
		return -EINVAL;

	return 0;
}

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_show
 *
 *Description: show cpu frequency information;
 *
 *Arguments  : pfx   name;
 *
 *
 *Return     :
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static void sun5i_cpufreq_show(const char *pfx, struct sun5i_cpu_freq_t *cfg)
{
	CPUFREQ_DBG("%s: pll=%u, cpudiv=%u, axidiv=%u, ahbdiv=%u, apb=%u\n",
        pfx, cfg->pll, cfg->div.cpu_div, cfg->div.axi_div, cfg->div.ahb_div, cfg->div.apb_div);
}

/*
 ***************************************************************************************************
 *                           __set_cpufreq_target
 *
 *Description: set target frequency, the frequency limitation of axi is 450Mhz, the frequency
 *             limitation of ahb is 250Mhz, and the limitation of apb is 150Mhz. for usb connecting,
 *             the frequency of ahb must not lower than 60Mhz.
 *
 *Arguments  : old   cpu/axi/ahb/apb frequency old configuration.
 *             new   cpu/axi/ahb/apb frequency new configuration.
 *
 *Return     : result, 0 - set frequency and voltage successed
 *                    -1 - set voltage failed
 *Notes      :
 *
 ***************************************************************************************************
*/
static int __set_cpufreq_target(struct sun5i_cpu_freq_t *old, struct sun5i_cpu_freq_t *new)
{
    struct sun5i_cpu_freq_t old_freq, new_freq;

    if(!old || !new) {
        return -EINVAL;
    }

    old_freq = *old;
    new_freq = *new;

    //printk("cpu: %dMhz->%dMhz\n", old_freq.pll/1000000, new_freq.pll/1000000);

    /* try to adjust pll frequency */
    clk_set_rate(clk_pll,new_freq.pll);
    /* try to adjust cpu frequency */
    clk_set_rate(clk_cpu, new_freq.pll/new_freq.div.cpu_div);

    /* start dvfs, wait for finish */
    pmu_dvfs_start_to_finish();

    //printk("pending: 0x%x\n", readl(SW_VA_PMU_IO_BASE+0x44));

    /* dvfs voltage change failed */
    if(pmu_dvfs_volt_chg_err()){
        DVFS_ERR("dvfs voltage change failed!\n");
        /* clear pending */
        pmu_dvfs_clear_pending();
        /* start dvfs again, wait for finish */
        pmu_dvfs_start_to_finish();
        printk("pending(volt err): 0x%x\n", readl(SW_VA_PMU_IO_BASE+0x44));
        /* dvfs voltage change failed again */
        if(pmu_dvfs_volt_chg_err()){
            DVFS_ERR("dvfs voltage change failed second!\n");
            /* clear pending */
            pmu_dvfs_clear_pending();
            return -1;
        }
    }

    /* clear pending */
    pmu_dvfs_clear_pending();

    CPUFREQ_DBG("%s: finished\n", __func__);

    return 0;
}

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_settarget
 *
 *Description: adjust cpu frequency;
 *
 *Arguments  : policy    cpu frequency policy, to mark if need notify
 *             cpu_freq  new cpu frequency configuration
 *
 *Return     : return 0 if set successed, otherwise, return -EINVAL
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static int sun5i_cpufreq_settarget(struct cpufreq_policy *policy, struct sun5i_cpu_freq_t *cpu_freq)
{
    struct cpufreq_freqs    freqs;
    struct sun5i_cpu_freq_t cpu_new;

    /* show current cpu frequency configuration, just for debug */
	// sun5i_cpufreq_show("cur", &cpu_cur);

	if(!cpu_freq){
		return -EINVAL;
	}

    /* get new cpu frequency configuration */
	cpu_new = *cpu_freq;
	// sun5i_cpufreq_show("new", &cpu_new);

    /* notify that cpu clock will be adjust if needed */
	if (policy) {
       freqs.cpu = 0;
	    freqs.old = cpu_cur.pll / 1000;
	    freqs.new = cpu_new.pll / 1000;
       cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
	}

    if(__set_cpufreq_target(&cpu_cur, &cpu_new)) {
        /* try to set voltage failed when voltage build up*/
        if(cpu_new.pll > cpu_cur.pll) {
            /* notify everyone that clock transition finish */
            if (policy) {
    	    	freqs.cpu = 0;
                freqs.old = freqs.new;
                freqs.new = cpu_cur.pll / 1000;
    	        cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
	        }
            return -EINVAL;
        }
    }

	/* update our current settings */
	cpu_cur = cpu_new;

	/* notify everyone we've done this */
	if (policy) {
		cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
	}

	CPUFREQ_DBG("%s: finished\n", __func__);

	return 0;
}

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_target
 *
 *Description: adjust the frequency that cpu is currently running;
 *
 *Arguments  : policy    cpu frequency policy;
 *             freq      target frequency to be set, based on khz;
 *             relation  method for selecting the target requency;
 *
 *Return     : result, return 0 if set target frequency successed,
 *                     else, return -EINVAL;
 *
 *Notes      : this function is called by the cpufreq core;
 *
 ***************************************************************************************************
*/
static int sun5i_cpufreq_target(struct cpufreq_policy *policy, __u32 freq, __u32 relation)
{
    int                     ret;
    unsigned int            index;
    struct sun5i_cpu_freq_t freq_cfg;

    DVFS_DBG("target_freq: %d\n", freq);
    DVFS_DBG("last_target: %d\n", last_target);

    /* avoid repeated calls which cause a needless amout of duplicated
	 * logging output (and CPU time as the calculation process is
	 * done) */
	if (freq == last_target) {
        DVFS_DBG("target_freq == last_target\n");
		return 0;
	}

	/* try to look for a valid frequency value from cpu frequency table */
    if (cpufreq_frequency_table_target(policy, sun5i_freq_tbl, freq, relation, &index)) {
        CPUFREQ_ERR("%s: try to look for a valid frequency for %u failed!\n", __func__, freq);
		return -EINVAL;
	}

    DVFS_DBG("table_freq: %d\n", sun5i_freq_tbl[index].frequency);

    /* frequency is same as the value last set, need not adjust */
    if (sun5i_freq_tbl[index].frequency == last_target) {
        DVFS_DBG("table_freq == last_target\n");
		return 0;
	}
    freq = sun5i_freq_tbl[index].frequency;

    /* update the target frequency */
    freq_cfg.pll = sun5i_freq_tbl[index].frequency * 1000;
    freq_cfg.div = *(struct sun5i_clk_div_t *)&sun5i_freq_tbl[index].index;
    CPUFREQ_DBG("%s: target frequency find is %u, entry %u\n", __func__, freq_cfg.pll, index);

	/* try to set target frequency */
	ret = sun5i_cpufreq_settarget(policy, &freq_cfg);
    if(!ret) {
        last_target = freq;
    }

    CPUFREQ_DBG("%s: finished!\n", __func__);

    return ret;
}

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_get
 *
 *Description: get the frequency that cpu currently is running;
 *
 *Arguments  : cpu   cpu number;
 *
 *Return     : cpu frequency, based on khz;
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static unsigned int sun5i_cpufreq_get(unsigned int cpu)
{
	return clk_get_rate(clk_cpu) / 1000;
}

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_init
 *
 *Description: cpu frequency initialise a policy;
 *
 *Arguments  : policy    cpu frequency policy;
 *
 *Return     : result, return 0 if init ok, else, return -EINVAL;
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static int sun5i_cpufreq_init(struct cpufreq_policy *policy)
{
	CPUFREQ_DBG(KERN_INFO "%s: initialising policy %p\n", __func__, policy);

	if (policy->cpu != 0)
		return -EINVAL;

	policy->cur = sun5i_cpufreq_get(0);
	policy->min = policy->cpuinfo.min_freq = SUN5I_CPUFREQ_MIN / 1000;
	policy->max = policy->cpuinfo.max_freq = SUN5I_CPUFREQ_MAX / 1000;
	policy->governor = CPUFREQ_DEFAULT_GOVERNOR;

	/* feed the latency information from the cpu driver */
	policy->cpuinfo.transition_latency = SUN5I_FREQTRANS_LATENCY;

	return 0;
}

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_getcur
 *
 *Description: get current cpu frequency configuration;
 *
 *Arguments  : cfg   cpu frequency cofniguration;
 *
 *Return     : result;
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static int sun5i_cpufreq_getcur(struct sun5i_cpu_freq_t *cfg)
{
    unsigned int    freq, freq0;

    if(!cfg) {
        return -EINVAL;
    }

	cfg->pll = clk_get_rate(clk_pll);
    freq = clk_get_rate(clk_cpu);
    cfg->div.cpu_div = cfg->pll / freq;
    freq0 = clk_get_rate(clk_axi);
    cfg->div.axi_div = freq / freq0;
    freq = clk_get_rate(clk_ahb);
    cfg->div.ahb_div = freq0 / freq;
    freq0 = clk_get_rate(clk_apb);
    cfg->div.apb_div = freq /freq0;

	return 0;
}

#ifdef CONFIG_PM

/* variable for backup cpu frequency configuration */
static struct sun5i_cpu_freq_t suspend_freq;

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_suspend
 *
 *Description: back up cpu frequency configuration for suspend;
 *
 *Arguments  : policy    cpu frequency policy;
 *
 *Return     : return 0,
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static int sun5i_cpufreq_suspend(struct cpufreq_policy *policy)
{
    struct sun5i_cpu_freq_t suspend;

    CPUFREQ_DBG("%s, set cpu frequency to 60Mhz to prepare enter standby\n", __func__);
    sun5i_cpufreq_getcur(&suspend_freq);

    /* set cpu frequency to 60M hz for standby */
    suspend.pll = 60000000;
    suspend.div.cpu_div = 1;
    suspend.div.axi_div = 1;
    suspend.div.ahb_div = 1;
    suspend.div.apb_div = 2;

    /* save cpu frequency configuration */
    __set_cpufreq_target(&suspend_freq, &suspend);

    /* dvfs suspend */
    pmu_dvfs_suspend();

    CPUFREQ_DBG("%s: standby done\n", __func__);

    return 0;
}

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_resume
 *
 *Description: cpu frequency configuration resume;
 *
 *Arguments  : policy    cpu frequency policy;
 *
 *Return     : result;
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static int sun5i_cpufreq_resume(struct cpufreq_policy *policy)
{
    struct sun5i_cpu_freq_t suspend;

    /* dvfs resume */
    pmu_dvfs_resume();

    /* invalidate last_target setting */
	last_target = ~0;

	CPUFREQ_DBG("%s: resuming with policy %p\n", __func__, policy);
    sun5i_cpufreq_getcur(&suspend);

    /* restore cpu frequency configuration */
    __set_cpufreq_target(&suspend, &suspend_freq);

	CPUFREQ_DBG("%s: resuming done\n", __func__);

	return 0;
}

#else /* #ifdef CONFIG_PM */

#define sun5i_cpufreq_suspend   NULL
#define sun5i_cpufreq_resume    NULL

#endif /* #ifdef CONFIG_PM */

static struct cpufreq_driver sun5i_cpufreq_driver = {
	.flags		= CPUFREQ_STICKY,
	.verify		= sun5i_cpufreq_verify,
	.target		= sun5i_cpufreq_target,
	.get		= sun5i_cpufreq_get,
	.init		= sun5i_cpufreq_init,
	.suspend	= sun5i_cpufreq_suspend,
	.resume		= sun5i_cpufreq_resume,
	.name	  	= "sun5i-cpufreq",
};

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_initclks
 *
 *Description: init cpu frequency clock resource;
 *
 *Arguments  : none
 *
 *Return     : result;
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static __init int sun5i_cpufreq_initclks(void)
{
    clk_pll = clk_get(NULL, "core_pll");
    clk_cpu = clk_get(NULL, "cpu");
    clk_axi = clk_get(NULL, "axi");
    clk_ahb = clk_get(NULL, "ahb");
    clk_apb = clk_get(NULL, "apb");

	if (IS_ERR(clk_pll) || IS_ERR(clk_cpu) || IS_ERR(clk_axi) ||
	    IS_ERR(clk_ahb) || IS_ERR(clk_apb)) {
		CPUFREQ_INF(KERN_ERR "%s: could not get clock(s)\n", __func__);
		return -ENOENT;
	}

	CPUFREQ_INF("%s: clocks pll=%lu,cpu=%lu,axi=%lu,ahp=%lu,apb=%lu\n", __func__,
	       clk_get_rate(clk_pll), clk_get_rate(clk_cpu), clk_get_rate(clk_axi),
	       clk_get_rate(clk_ahb), clk_get_rate(clk_apb));

	return 0;
}

/*
 ***************************************************************************************************
 *                           sun5i_cpufreq_initcall
 *
 *Description: cpu frequency driver initcall
 *
 *Arguments  : none
 *
 *Return     : result
 *
 *Notes      :
 *
 ***************************************************************************************************
*/
static int __init sun5i_cpufreq_initcall(void)
{
	int ret = 0;

    /* initialise some clock resource */
    ret = sun5i_cpufreq_initclks();
    if(ret) {
        return ret;
    }

    /* initialise dvfs hardware configuration */
    ret = pmu_dvfs_hw_init();
    if(ret) {
        return ret;
    }

    /* initialise current frequency configuration */
	sun5i_cpufreq_getcur(&cpu_cur);
	sun5i_cpufreq_show("cur", &cpu_cur);

    /* register cpu frequency driver */
    ret = cpufreq_register_driver(&sun5i_cpufreq_driver);
    /* register cpu frequency table to cpufreq core */
    cpufreq_frequency_table_get_attr(sun5i_freq_tbl, 0);
    /* update policy for boot cpu */
    cpufreq_update_policy(0);

	return ret;
}

late_initcall(sun5i_cpufreq_initcall);


text:
package com.tngtech.archunit.junit.internal.testexamples;

public class UnwantedClass {
    public static final Class<?> CLASS_SATISFYING_RULES = Object.class;
    public static final Class<?> CLASS_VIOLATING_RULES = UnwantedClass.class;
}


text:
<?php

namespace app\components\html;

use yii\helpers\Html;

class AdminNavigationHelper {
    /**
     * Навигационное меню раздела Администрирования
     * @var array
     */
    private $_actions = [
        'admin/news' => [
            'title' => 'Новости', 'url' => '/admin/news',
            'sub_actions' => [
                 'admin/news-update'    => [ 'title' => 'Редактирование новости' ],
                 'admin/news-add'       => [ 'title' => 'Добавление новости' ],
                 'admin/news-delete'    => [ 'title' => 'Удаление новости' ]
            ]
        ],
        'admin/categories' => [
            'title' => 'Разделы новостей', 'url' => '/admin/categories',
            'sub_actions' => [
                 'admin/categories-update'    => [ 'title' => 'Редактирование раздела' ],
                 'admin/categories-add'       => [ 'title' => 'Добавление раздела' ],
                 'admin/categories-delete'    => [ 'title' => 'Удаление раздела' ]
            ]
        ],
        'admin/posts' => [
            'title' => 'Комментарии посетителей', 'url' => '/admin/posts',
            'sub_actions' => [
                'admin/posts-delete' => [ 'title' => 'Удаление комментария' ]
            ]
        ],
        'admin/logout' => [ 'title' => 'Выход', 'url' => '/admin/logout']
    ];

    /**
     * Кеш для упрощения создания навигационных элементов
     * @var array
     */
    private $_actions_by_id = [];

    /**
     * @var AdminNavigationHelper
     */
    private static $_instance = null;

    /**
     * Конструктор
     */
    private function __construct() {
        foreach ($this->_actions as $action_id => $action) {
            $this->_actions_by_id[$action_id] = [
                'level' => 0,
                'title' => $action['title'],
                'url'   => $action['url']
            ];
            $sub_actions = isset($action['sub_actions']) ? $action['sub_actions'] : [];
            foreach ($sub_actions as $sub_action_id => $sub_action) {
                $this->_actions_by_id[$sub_action_id] = [
                    'level'     => 1,
                    'parent_id' => $action_id,
                    'title'     => $sub_action['title'],
                ];
            }
        }
    }

    /**
     * Получение доступа к экземпляру класса
     * @return AdminNavigationHelper
     */
    public static function get() {
        if (is_null(self::$_instance)) {
            self::$_instance = new AdminNavigationHelper();
        }

        return self::$_instance;
    }

    /**
     * Генерация пунктов главного меню раздела администрирования
     * @param string $current_action
     * @return array
     */
    public function generateNavItems($current_action = '') {
        $parent_action_id = $current_action && isset($this->_actions_by_id[$current_action]['parent_id']) ?
            $this->_actions_by_id[$current_action]['parent_id'] : null;

        $items = [];
        foreach ($this->_actions as $action_id => $action) {
            $item = [ 'label' => $action['title'], 'url' => [ $action['url'] ] ];

            if ($parent_action_id && ($parent_action_id == $action_id)) {
                $item['options'] = [ 'class' => 'active' ];
            }

            $items[] = $item;
        }

        return $items;
    }

    /**
     * Генерация Breadcrumbs на основе полученного идентификатора действия
     * @param string $action
     * @param string[] $default
     * @return array
     */
    public function generateBreadcrumbs($action = '', $default = []) {
        $breadcrumbs = is_array($default) ? $default : [];
        $action = isset($this->_actions_by_id[$action]) ? $this->_actions_by_id[$action] : null;
        if (!$action) {
            return $breadcrumbs;
        }

        while ($action) {
            array_unshift($breadcrumbs, $breadcrumbs ? [
                'label' => Html::encode($action['title']),
                'url' => $action['url']
            ] : Html::encode($action['title']));
            $parent_id = isset($action['parent_id']) ? $action['parent_id'] : '';
            $action = $parent_id && isset($this->_actions_by_id[$parent_id]) ?
                $this->_actions_by_id[$parent_id] : null;
        }

        if ($breadcrumbs) {
            array_unshift($breadcrumbs, [
                'label' => 'Администрирование',
                'url' => '/admin'
            ]);
        }

        return $breadcrumbs;
    }

    public function getActionName($action) {
        return isset($this->_actions_by_id[$action]['title']) ? $this->_actions_by_id[$action]['title'] : '';
    }

    /**
     * Получение заголовка странице на основании идентификатора действия
     * @param string $action
     * @param string $header
     * @return string
     */
    public function getTitle($action, $header = '') {
        $action_title = isset($this->_actions_by_id[$action]['title']) ?
            $this->_actions_by_id[$action]['title'] : '';

        if ($header) {
            $title[] = $header;
        }
        $title[] = 'Администрирование';
        if ($action_title) {
            $title[] = $action_title;
        }

        return implode(' | ', $title);
    }
}


text:
module Dynflow
  module Testing
    class InThreadExecutor
      def initialize(world)
        @world = world
        @director = Director.new(@world)
        @work_items = Queue.new
      end

      def execute(execution_plan_id, finished = Concurrent::Promises.resolvable_future, _wait_for_acceptance = true)
        feed_queue(@director.start_execution(execution_plan_id, finished))
        process_work_items
        finished
      end

      def process_work_items
        until @work_items.empty?
          feed_queue(handle_work(@work_items.pop))
          clock_tick
        end
      end

      def plan_events(delayed_events)
        delayed_events.each do |event|
          @world.plan_event(event.execution_plan_id, event.step_id, event.event, event.time)
        end
      end

      def handle_work(work_item)
        work_item.execute
        step = work_item.step if work_item.is_a?(Director::StepWorkItem)
        plan_events(step && step.delayed_events) if step && step.delayed_events
        @director.work_finished(work_item)
      end

      def event(execution_plan_id, step_id, event, future = Concurrent::Promises.resolvable_future, optional: false)
        event = (Director::Event[SecureRandom.uuid, execution_plan_id, step_id, event, future, optional])
        @director.handle_event(event).each do |work_item|
          @work_items << work_item
        end
        future
      end

      def delayed_event(director_event)
        @director.handle_event(director_event).each do |work_item|
          @work_items << work_item
        end
        director_event.result
      end

      def clock_tick
        @world.clock.progress_all([:periodic_check_inbox])
      end

      def feed_queue(work_items)
        work_items.each do |work_item|
          work_item.world = @world
          @work_items.push(work_item)
        end
      end

      def terminate(future = Concurrent::Promises.resolvable_future)
        @director.terminate
        future.fulfill true
      rescue => e
        future.reject e
      end
    end
  end
end


text:
package de.mstein.geotracker;

/**
 * Created by Mattes on 04.12.2015.
 */
public class ListItem {
    private String name;
    private int icon;

    public ListItem(String name, int icon) {
        this.name = name;
        this.icon = icon;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getIcon() {
        return icon;
    }

    public void setIcon(int icon) {
        this.icon = icon;
    }
}


text:
<?php
/**
 * A convenience store.
 *
 * @see    http://schema.org/ConvenienceStore
*/
abstract class TypeConvenienceStore extends TypeStore
{
	/**
	 * The Schema.org Type Scope
	 *
	 * @var string
	 */
	protected static $scope = 'https://schema.org/ConvenienceStore';
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="Dia1_Ex2.Dia1_Ex2">
	<uses-sdk />
	<application android:label="Dia1-Ex2">
	</application>
</manifest>


text:
'use strict';

var _Collection = require('./Collection');

var _Collection2 = _interopRequireDefault(_Collection);

var _makeActionTypes = require('./makeActionTypes');

var _redux = require('redux');

var _State = require('./State');

var _State2 = _interopRequireDefault(_State);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

describe('Collection', function () {

  it('generates types, actions, and reducer', function () {
    var state = new _Collection2.default('CollectionTest');

    expect(state.actionTypes).toEqual({
      upsert: (0, _makeActionTypes.makeActionTypeFromActionName)('CollectionTest', 'upsert'),
      remove: (0, _makeActionTypes.makeActionTypeFromActionName)('CollectionTest', 'remove')
    });
    expect(state.actions).toEqual({
      upsert: expect.any(Function),
      remove: expect.any(Function)
    });
    expect((0, _redux.combineReducers)(state.reducer)).toEqual(expect.any(Function));
  });

  it('sets default state', function () {
    var state = new _Collection2.default('CollectionTest');

    expect((0, _redux.combineReducers)(state.reducer)(undefined, {})).toEqual({ byId: {}, allIds: [] });
  });

  it('::upsert inserts a new element with an id', function () {

    var state = new _Collection2.default('CollectionTest');
    var action = state.actions.upsert({ name: 'test' });
    var newState = (0, _redux.combineReducers)(state.reducer)(undefined, action);

    expect(newState.allIds.length).toBe(1);
    var id = newState.allIds[0];
    expect(newState.byId[id]).toEqual({ _id: id, name: 'test' });
  });

  it('::upsert updates an existing element', function () {

    var state = new _Collection2.default('CollectionTest');
    var initialState = {
      byId: { 1: { _id: 1, upsert: 'test' } },
      allIds: [1]
    };
    var action = state.actions.upsert({ _id: 1, add: 'new property' });
    var newState = (0, _redux.combineReducers)(state.reducer)(initialState, action);

    expect(newState.allIds.length).toBe(1);
    expect(newState.byId[1]).toEqual({ _id: 1, add: 'new property' });
  });

  it('::delete removes an existing element', function () {

    var state = new _Collection2.default('CollectionTest');
    var initialState = {
      byId: { 1: { _id: 1, upsert: 'test' } },
      allIds: [1]
    };
    var action = state.actions.remove({ _id: 1 });
    var newState = (0, _redux.combineReducers)(state.reducer)(initialState, action);

    expect(newState.allIds.length).toBe(0);
    expect(newState.byId[1]).not.toBeDefined();
  });

  it('accepts additional substate', function () {
    var state = new _Collection2.default('CollectionTest', {
      another: new _State2.default('another', null, {
        testAction: function testAction() {
          return {};
        }
      })
    });

    expect(state.actionTypes.testAction).toBeDefined();
    expect(state.actions.testAction).toEqual(expect.any(Function));
  });

  it('::upsert accepts arrays', function () {

    var state = new _Collection2.default('CollectionTest');
    var action = state.actions.upsert([{ _id: 1, name: 'test' }, { _id: 2, name: 'test' }]);
    var newState = (0, _redux.combineReducers)(state.reducer)(undefined, action);

    expect(newState.allIds.length).toBe(2);
    var id1 = newState.allIds[0];
    var id2 = newState.allIds[1];
    expect(newState.byId[id1]).toEqual({ _id: id1, name: 'test' });
    expect(newState.byId[id2]).toEqual({ _id: id2, name: 'test' });
  });
}); // I probably shouldn't do this, but f it
//# sourceMappingURL=Collection.test.js.map


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class gov.nasa.worldwind.applications.sar.PositionTable (NASA World Wind)
</TITLE>

<META NAME="date" CONTENT="2010-01-14">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Index
      Help

NASA World Wind

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
gov.nasa.worldwind.applications.sar.PositionTable

Packages that use PositionTable

gov.nasa.worldwind.applications.sar

gov.nasa.worldwind.applications.sar.actions

Uses of PositionTable in gov.nasa.worldwind.applications.sar

Constructors in gov.nasa.worldwind.applications.sar with parameters of type PositionTable

PositionsContextMenu(PositionTable positionTable)

Uses of PositionTable in gov.nasa.worldwind.applications.sar.actions

Fields in gov.nasa.worldwind.applications.sar.actions declared as PositionTable

protected  PositionTable
InsertPositionAction.table

protected  PositionTable
DeletePositionsAction.table

protected  PositionTable
AppendPositionAction.table

protected  PositionTable
AddOffsetToPositionsAction.table

Constructors in gov.nasa.worldwind.applications.sar.actions with parameters of type PositionTable

AddOffsetToPositionsAction(PositionTable table)

AppendPositionAction(PositionTable table)

DeletePositionsAction(PositionTable table)

InsertPositionAction(boolean above,
                     PositionTable table)

      Overview
      Package
      Class
    Use
      Tree
      Index
      Help

NASA World Wind

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
module Text.LaTeX.Packages.AMSSymb
 ( -- * AMSSymb package
   amssymb

   -- * Arrows
  , vartriangleleft, vartriangleright
  , leftleftarrows, rightrightarrows
  , rightleftarrows, leftrightarrows
  , upuparrows, downdownarrows
  , leftarrowtail, rightarrowtail
  , curvearrowleft, curvearrowright
  , twoheadleftarrow, twoheadrightarrow
  , rightleftharpoons
  , lsh2, rsh2
  , leftarrow3, rightarrow3
  , rightsquigarrow, leftrightsquigarrow
  , looparrowleft, looparrowright
  , circlearrowleft, circlearrowright
  , upharpoonleft, upharpoonright
  , downharpoonleft, downharpoonright
  , nleftarrow, nrightarrow
  , nleftarrow2, nrightarrow2
  , nleftrightarrow, nleftrightarrow2

   -- * Other
  , lll, ggg
  , gtrdot, lessdot
  , square, blacksquare
  , lozenge, blacklozenge
  , checkmark, nexists
 ) where

import Text.LaTeX.Base.Class
import Text.LaTeX.Base.Types

-- | AMSSymb package.
-- Example:
--
-- > usepackage [] amssymb
amssymb :: ClassName
amssymb = "amssymb"

--

-- | \(\vartriangleleft\) symbol.
vartriangleleft :: LaTeXC l => l
vartriangleleft = comm0 "vartriangleleft"

-- | \(\vartriangleleft\) symbol.
vartriangleright :: LaTeXC l => l
vartriangleright = comm0 "vartriangleright"

-- | \(\leftleftarrows\) symbol - double left arrows.
leftleftarrows :: LaTeXC l => l
leftleftarrows = comm0 "leftleftarrows"

-- | \(\rightrightarrows\) symbol - double right arrows
rightrightarrows :: LaTeXC l => l
rightrightarrows = comm0 "rightrightarrows"

-- | \(\rightleftarrows\) symbol - right arrow atop a left arrow
rightleftarrows :: LaTeXC l => l
rightleftarrows = comm0 "rightleftarrows"

-- | \(\leftrightarrows\) symbol - left arrow atop a right arrow.
leftrightarrows :: LaTeXC l => l
leftrightarrows = comm0 "leftrightarrows"

-- | \(\upuparrows\) symbol - double upward arrows.
upuparrows :: LaTeXC l => l
upuparrows = comm0 "upuparrows"

-- | \(\downdownarrows\) symbol - double downward arrows.
downdownarrows :: LaTeXC l => l
downdownarrows = comm0 "downdownarrows"

-- | \(\lll\) symbol - triple less than.
lll :: LaTeXC l => l
lll = comm0 "lll"

-- | \(\ggg\) symbol - triple greater than.
ggg :: LaTeXC l => l
ggg = comm0 "ggg"

-- | \(\leftarrowtail\) symbol - leftwards "mapsto"
leftarrowtail :: LaTeXC l => l
leftarrowtail = comm0 "leftarrowtail"

-- | \(\rightarrowtail\) symbol - rightwards "mapsto"
rightarrowtail :: LaTeXC l => l
rightarrowtail = comm0 "rightarrowtail"

-- | \(\curvearrowleft\) symbol - leftwards curved arrow
curvearrowleft :: LaTeXC l => l
curvearrowleft = comm0 "curvearrowleft"

-- | \(\curvearrowright\) symbol - rightwards curved arrow
curvearrowright :: LaTeXC l => l
curvearrowright = comm0 "curvearrowright"

-- | \(\twoheadleftarrow\) symbol - double head left arrow
twoheadleftarrow :: LaTeXC l => l
twoheadleftarrow = comm0 "twoheadleftarrow"

-- | \(\twoheadrightarrow\) symbol - double head right arrow
twoheadrightarrow :: LaTeXC l => l
twoheadrightarrow = comm0 "twoheadleftarrow"

-- | \(\checkmark\) symbol.
checkmark :: LaTeXC l => l
checkmark = comm0 "checkmark"

-- | \(\lozenge\) symbol - narrow diamond
lozenge :: LaTeXC l => l
lozenge = comm0 "lozenge"

-- | \(\blacklozenge\) symbol - filled narrow diamond
blacklozenge :: LaTeXC l => l
blacklozenge = comm0 "blacklozenge"

-- | \(\nexists\) symbol - does not exist
nexists :: LaTeXC l => l
nexists = comm0 "nexists"

-- | \(\lessdot\) symbol - less than with inner dot
lessdot :: LaTeXC l => l
lessdot = comm0 "lessdot"

-- | \(\gtrdot\) symbol - greater than with inner dot
gtrdot :: LaTeXC l => l
gtrdot = comm0 "gtrdot"

-- | \(\square\) symbol - square.
--   For the QED "tombstone", see 'Text.LaTeX.Packages.AMSThm.qed' instead; it is normally the
--   same symbol but gives the suitable text alignment.
square :: LaTeXC l => l
square = comm0 "square"

-- | \(\blacksquare\) symbol - a filled square
blacksquare :: LaTeXC l => l
blacksquare = comm0 "blacksquare"

-- | \(\rightleftharpoons\) symbol
rightleftharpoons :: LaTeXC l => l
rightleftharpoons = comm0 "rightleftharpoons"
-- | \(\Lsh\) symbol
lsh2 :: LaTeXC l => l
lsh2 = comm0 "Lsh"
-- | \(\Rsh\) symbol
rsh2 :: LaTeXC l => l
rsh2 = comm0 "Rsh"
-- | \(\Lleftarrow\) symbol
leftarrow3 :: LaTeXC l => l
leftarrow3 = comm0 "Lleftarrow"
-- | \(\Rrightarrow\) symbol
rightarrow3 :: LaTeXC l => l
rightarrow3 = comm0 "Rrightarrow"
-- | \(\rightsquigarrow\) symbol
rightsquigarrow :: LaTeXC l => l
rightsquigarrow = comm0 "rightsquigarrow"
-- | \(\leftrightsquigarrow\) symbol
leftrightsquigarrow :: LaTeXC l => l
leftrightsquigarrow = comm0 "leftrightsquigarrow"
-- | \(\looparrowleft\) symbol
looparrowleft :: LaTeXC l => l
looparrowleft = comm0 "looparrowleft"
-- | \(\looparrowright\) symbol
looparrowright :: LaTeXC l => l
looparrowright = comm0 "looparrowright"
-- | \(\circlearrowleft\) symbol
circlearrowleft :: LaTeXC l => l
circlearrowleft = comm0 "circlearrowleft"
-- | \(\circlearrowright\) symbol
circlearrowright :: LaTeXC l => l
circlearrowright = comm0 "circlearrowright"
-- | \(\upharpoonleft\) symbol
upharpoonleft :: LaTeXC l => l
upharpoonleft = comm0 "upharpoonleft"
-- | \(\upharpoonright\) symbol
upharpoonright :: LaTeXC l => l
upharpoonright = comm0 "upharpoonright"
-- | \(\downharpoonleft\) symbol
downharpoonleft :: LaTeXC l => l
downharpoonleft = comm0 "downharpoonleft"
-- | \(\downharpoonright\) symbol
downharpoonright :: LaTeXC l => l
downharpoonright = comm0 "downharpoonright"
-- | \(\nleftarrow\) symbol
nleftarrow :: LaTeXC l => l
nleftarrow = comm0 "nleftarrow"
-- | \(\nrightarrow\) symbol
nrightarrow :: LaTeXC l => l
nrightarrow = comm0 "nrightarrow"
-- | \(\nLeftarrow\) symbol
nleftarrow2 :: LaTeXC l => l
nleftarrow2 = comm0 "nLeftarrow"
-- | \(\nRightarrow\) symbol
nrightarrow2 :: LaTeXC l => l
nrightarrow2 = comm0 "nRightarrow"
-- | \(\nleftrightarrow\) symbol
nleftrightarrow :: LaTeXC l => l
nleftrightarrow = comm0 "nleftrightarrow"
-- | \(\nLeftrightarrow\) symbol
nleftrightarrow2 :: LaTeXC l => l
nleftrightarrow2 = comm0 "nLeftrightarrow"


text:
import { TranslationService } from './translation';
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing';

describe('App', () => {
  const translationServiceStub = {};

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [RouterTestingModule],
      providers: [
        { provide: TranslationService, useValue: translationServiceStub }
      ],
    });
  }));

  it('should work', () => {
    const fixture = TestBed.createComponent(AppComponent);
    expect(fixture.componentInstance instanceof AppComponent).toBe(true, 'should create AppComponent');
  });
});


text:
CREATE TABLE funcionario(
  id BIGINT NOT NULL PRIMARY KEY,
  nome varchar(120) NOT NULL,
  email varchar(120) NOT NULL,
  senha varchar(14) NOT NULL,
  cpf varchar(14) NOT NULL,
  valor_hora decimal NOT NULL,
  horas_trabalho_dia FLOAT NOT NULL,
  horas_almoco FLOAT NOT NULL,
  perfil varchar(40),
  data_criacao DATETIME,
  data_atualizacao DATETIME,
  empresaId BIGINT NOT NULL,
  CONSTRAINT FK_Funcionario_Mensagem FOREIGN KEY(EmpresaId) REFERENCES Empresa
)


text:
class Observer {
public:
    virtual ~Observer(){};
    virtual void update(float temperature, float humidity, float pressure) = 0;
};

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>japa</groupId>
  <artifactId>javaparser</artifactId>
  <versioning>
    <release>1.0</release>
    <versions>
      <version>1.0</version>
    </versions>
    <lastUpdated>20120416104620</lastUpdated>
  </versioning>
</metadata>