text:
var twitter = require('twitter'),
	express = require('express'),
	app = express(),
	http = require('http'),
	server = http.createServer(app),
	io = require('socket.io').listen(server);

//Setup twitter stream api
var twit = new twitter({
	//consumer_key: '5VyHDN34uv2gPl0rVoljNflF6',
	//consumer_secret: 'aHhcPDC33DoER4Xfn4809p1pD9WPE9098iSMa7sd1blvmacv8R',
	//access_token_key: '35626713-p880mlq7KURMibu8qa4QIHaSMHLnqG1VybeUqiMto',
	//access_token_secret: '	RnM40yjHEvgHzr0tOpvADXeQLs9wRriazbhz4LkE28unG'
	consumer_key: 'yZiAdoZd0HqKQW4lHbTRUssx1',
    consumer_secret: 'POnmG7n8I64ZspxDg3aCYdVJY59aXqFke4jExniBmpQfaBo26y',
    access_token_key: '35626713-wL8DlhYE8W5k35j5Hvr0oypyh7ycF1wDJcvdpuJkX',
    access_token_secret: 'L6lFOVn1iEAW2FsZwcNRJS4f1QLdjzLIRj4aeXe9CHSEY'
}),
stream = null;

//Use the default port (for beanstalk) or default to 8081 locally
server.listen(process.env.PORT || 8081);

//Setup routing for app
app.use(express.static(__dirname + '/public'));

//Create web sockets connection.
io.sockets.on('connection', function(socket){

	socket.on("start tweets", function(){

		if(stream === null){

			//Connect to twitter stream passing in filter for entire world.
			twit.stream('statuses/filter', {'locations':'-180,-90,180,90'}, function(s) {
				stream = s;
				stream.on('data', function(data){
					//Does the JSON result have coordinates
					if (data.coordinates){
						if (data.coordinates !== null){
							//If so then build up some nice json and send out to web sockets
							var outputPoint = {"lat": data.coordinates.coordinates[0],"lng": data.coordinates.coordinates[1]};

							socket.broadcast.emit("twitter-stream", outputPoint);

							//Send out to web sockets channel.
							socket.emit('twitter-stream', outputPoint);
							}
						}
					});
				});
		}
	});

	// Emits signal to the client telling them that
	// they are connected and can start receiving Tweets
	socket.emit("connected");

});


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThreeTier.Service;
using ThreeTier.Service.DemoServices;
using ThreeTier.Data;

namespace ThreeTier.Tests.Service
{
    /// <summary>
    /// Summary description for DemoUserServiceTest
    /// </summary>
    [TestClass]
    public class DemoUserServiceTest
    {
        IUserService srv;

        [TestMethod]
        public void DemoUserService_Valid_Users_Can_Login()
        {
            srv = new DemoUserService();
            Assert.IsTrue(srv.Login("Robert","Robert"));
        }

        [TestMethod]
        public void DemoUserService_Invalid_Users_Can_Not_Login()
        {
            srv = new DemoUserService();
            Assert.IsFalse(srv.Login("Robert", "Robert1"));
        }

        [TestMethod]
        public void DemoUserService_Should_Return_Friends()
        {
            srv = new DemoUserService();
            List<User> users = srv.GetFriendsFromUser("Robert").ToList();
            Assert.IsNotNull(users);
            Assert.AreNotEqual(0, users.Count);
            Assert.AreEqual("Oli", users[0].Login);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace common\tests\unit\message;

use common\components\message\MessageTemplateKeyHelper;
use common\models\message\IssueMessagesForm;

class KeyIssueMessagesFormTest extends BaseIssueMessagesFormTest {

	protected function messageTemplateFixtureDir(): string {
		return '';
	}

	public function keysProvider(): array {
		return [
			'Custom' => [
				IssueMessagesForm::generateKey('customType', 'customKey'),
				'customType.issue.customKey',
			],
			'Sms Customer Without Issue Types' => [
				IssueMessagesForm::generateKey(
					IssueMessagesForm::TYPE_SMS,
					IssueMessagesForm::keyCustomer(),
				),
				'sms.issue.customer',
			],
			'Email Customer Without Issue Types' => [
				IssueMessagesForm::generateKey(
					IssueMessagesForm::TYPE_EMAIL,
					IssueMessagesForm::keyCustomer(),
				),
				'email.issue.customer',
			],
			'Sms Workers Without Issue Types' => [
				IssueMessagesForm::generateKey(
					IssueMessagesForm::TYPE_SMS,
					IssueMessagesForm::keyWorkers(),
				),
				'sms.issue.workers',
			],
			'Email Workers Without Issue Types' => [
				IssueMessagesForm::generateKey(
					IssueMessagesForm::TYPE_EMAIL,
					IssueMessagesForm::keyWorkers(),
				),
				'email.issue.workers',
			],
			'SMS Customer With Custom Param' => [
				IssueMessagesForm::generateKey(
					IssueMessagesForm::TYPE_SMS,
					IssueMessagesForm::keyCustomer(['onUpdate']),
				),
				'sms.issue.customer.onUpdate',
			],
			'SMS Workers With Custom Param' => [
				IssueMessagesForm::generateKey(
					IssueMessagesForm::TYPE_SMS,
					IssueMessagesForm::keyWorkers(['onUpdate']),
				),
				'sms.issue.workers.onUpdate',
			],
			'Email Customer With Custom Param' => [
				IssueMessagesForm::generateKey(
					IssueMessagesForm::TYPE_EMAIL,
					IssueMessagesForm::keyCustomer(['onUpdate']),
				),
				'email.issue.customer.onUpdate',
			],
			'Email Workers With Custom Param' => [
				IssueMessagesForm::generateKey(
					IssueMessagesForm::TYPE_EMAIL,
					IssueMessagesForm::keyWorkers(['onUpdate']),
				),
				'email.issue.workers.onUpdate',
			],

		];
	}

	public function testCustomerSmsWithTemplateWithoutTypeIds(): void {
		$this->templateFixture->save(
			IssueMessagesForm::generateKey(
				IssueMessagesForm::TYPE_SMS,
				IssueMessagesForm::keyCustomer(),
			), 'SMS to Customer',
			'SMS Message to Customer'
		);

		$this->giveModel();
		$sms = $this->model->getSmsToCustomer();
		$this->tester->assertNotNull($sms);
	}

	public function testCustomerSmsWithTemplateWithOtherIssueTypeIds(): void {
		$this->templateFixture->flushAll();

		$this->templateFixture->save(
			IssueMessagesForm::generateKey(
				IssueMessagesForm::TYPE_SMS,
				IssueMessagesForm::keyCustomer(),
				[2]
			),
			'SMS to Customer',
			'SMS Message to Customer',
		);

		$this->giveModel();
		$sms = $this->model->getSmsToCustomer();
		$this->tester->assertNull($sms);
		$this->giveIssue(2);
		$this->giveModel();
		$sms = $this->model->getSmsToCustomer();
		$this->tester->assertNotNull($sms);
	}

	public function testEmptyIssueType(): void {
		$this->tester->assertSame('issue.create', MessageTemplateKeyHelper::generateKey(
			['issue', 'create', IssueMessagesForm::issueTypesKeyPart([])]
		));
	}

	public function testSingleIssueType(): void {
		$this->tester->assertSame('issue.create.issueTypes:1', MessageTemplateKeyHelper::generateKey(
			['issue', 'create', IssueMessagesForm::issueTypesKeyPart([1])]
		));
	}

	public function testMultipleIssueTypes(): void {
		$this->tester->assertSame('issue.create.issueTypes:1,2', MessageTemplateKeyHelper::generateKey(
			['issue', 'create', IssueMessagesForm::issueTypesKeyPart([1, 2])]
		));
	}

}


text:
title: Using Raygun To Track Errors And Deployments
shortTitle: Tracking Errors And Deployments With Raygun
menus:
  general/integrations:
    title: Using Raygun
    weight: 20
tags:
  - raygun
  - deployment
  - logging
  - analytics
  - reports
  - reporting
  - integrations
  - errors
categories:
  - Integrations
---

* include a table of contents
{:toc}

## About Raygun

[Raygun](https://raygun.com) lets you collect and track errors and deployments for your applications.

By using Raygun you can keep track of error logs and deployment events easier.

[Their documentation](https://raygun.com/docs) does a great job of providing more information, in addition to the setup instructions below.

## CodeShip Pro

### Setting Your API Key And Variables

You will need to add your Raygun API key and other required variables to your [encrypted environment variables]({{ site.baseurl }}{% link _pro/builds-and-configuration/environment-variables.md %}) that you encrypt and include in your [codeship-services.yml file]({{ site.baseurl }}{% link _pro/builds-and-configuration/services.md %}).

### Installing Raygun Dependency

Raygun maintains a list of modules that can be installed as dependencies for a wide variety of languages and frameworks. You will want to [visit their documentation](https://raygun.com/docs) and follow the instructions to use the dependency that is right for your application.

This dependency will need to be installed directly in your application's dependencies, or separately via the Dockerfile that you build via your [codeship-services.yml file]({{ site.baseurl }}{% link _pro/builds-and-configuration/services.md %}).

### Deploying And Sending Data

Once you have your API key, other required variables and dependencies installed, you will either run deployment commands or send data via API calls that you can make in your [codeship-steps.yml file]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}).

For example, here is an example using the [Raygun deployment commands](https://raygun.com/docs/deployments/bash):

```yaml
- name: raygun-deploy
  service: app
  command: raygun.sh
```

Notice that in this case we are calling a script named `raygun.sh`. Inside this script, we could have the Raygun deployment commands:

```bash
while getopts "t:a:v:n:e:g:h" opt; do
	case $opt in
	t)
		RAYGUN_AUTH_TOKEN=$OPTARG
		;;
	a)
		RAYGUN_API_KEY=$OPTARG
		;;
	v)
		DEPLOYMENT_VERSION=$OPTARG
		;;
	n)
		DEPLOYED_BY=$OPTARG
		;;
	e)
		EMAIL_ADDRESS=$OPTARG
		;;
    g)
		GIT_HASH=$OPTARG
		;;
    h)
        HELP=1
        ;;
	esac
done

shift $((OPTIND-1))

if [ $HELP -eq 1 ]
then
cat << EOF
usage: deployment.sh [-h] -v VERSION -t TOKEN -a API_KEY
                      -e EMAIL -n NAME [-g GIT_HASH] NOTES
  h:          show this help
  v VERSION:  version string for this deployment
  t TOKEN:    your Raygun External Auth Token
  a API_KEY:  the API Key for your Raygun Application
  n NAME:     the name of the person who created the deployment
  e EMAIL:    the email address of the person who created the deployment.
              Should be a Raygun users email
  g GIT_HASH: the git commit hash this deployment was built from
  NOTES:      the release notes for this deployment.
              Will be formatted using a Markdown parser
EOF
exit
fi

[ "$1" = "--" ] && shift

if [ "$1" != "" ]
then
    DEPLOYMENT_NOTES=$1
    DEPLOYMENT_NOTES=`echo $DEPLOYMENT_NOTES | sed s/\"/\\\\\\\\\"/g`
fi

url="https://app.raygun.com/deployments?authToken=$RAYGUN_AUTH_TOKEN"

read -d '' deployment <<- EOF
{
    apiKey: \"$RAYGUN_API_KEY\",
    version: \"$DEPLOYMENT_VERSION\",
    ownerName: \"$DEPLOYED_BY\",
    emailAddress: \"$EMAIL_ADDRESS\",
    scmIdentifier: \"$GIT_HASH\",
    comment: \"$DEPLOYMENT_NOTES\"
}
EOF

if ! curl -H "Content-Type: application/json" -d "$deployment" -f $url
then
  echo "Could not send deployment details to Raygun"
  exit 1
fi
```

**Note** that this example uses the [Raygun deployment commands](https://raygun.com/docs/deployments/bash) and requires additional environment variables to be set in the section above. It also requires values to be passed to the script via the environment or via arguments when you call the script from your [codeship-steps.yml file]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}). We recommend visiting the Raygun documentation for more information.

You can also run API calls in the same way, simply running API calls rather than the deployment commands above.

## CodeShip Basic

### Setting Your API Key And Variables

You will need to add your Raygun API key and other required variables to your to your project's [environment variables]({{ site.baseurl }}{% link _basic/builds-and-configuration/set-environment-variables.md %}).

You can do this by navigating to _Project Settings_ and then clicking on the _Environment_ tab.

### Installing Raygun Dependency

Raygun maintains a list of modules that can be installed as dependencies for a wide variety of languages and frameworks. You will want to [visit their documentation](https://raygun.com/docs) and follow the instructions to use the dependency that is right for your application.

This dependency will need to be installed directly in your application's dependencies, or separately via your [setup commands]({{ site.baseurl }}{% link _basic/quickstart/getting-started.md %}).

### Deploying And Sending Data

Once you have your API key, other required variables and dependencies installed, you will either run deployment commands or send data via API calls that you can make in your [test or deployment commands]({{ site.baseurl }}{% link _basic/quickstart/getting-started.md %}):

```bash
while getopts "t:a:v:n:e:g:h" opt; do
	case $opt in
	t)
		RAYGUN_AUTH_TOKEN=$OPTARG
		;;
	a)
		RAYGUN_API_KEY=$OPTARG
		;;
	v)
		DEPLOYMENT_VERSION=$OPTARG
		;;
	n)
		DEPLOYED_BY=$OPTARG
		;;
	e)
		EMAIL_ADDRESS=$OPTARG
		;;
    g)
		GIT_HASH=$OPTARG
		;;
    h)
        HELP=1
        ;;
	esac
done

shift $((OPTIND-1))

if [ $HELP -eq 1 ]
then
cat << EOF
usage: deployment.sh [-h] -v VERSION -t TOKEN -a API_KEY
                      -e EMAIL -n NAME [-g GIT_HASH] NOTES
  h:          show this help
  v VERSION:  version string for this deployment
  t TOKEN:    your Raygun External Auth Token
  a API_KEY:  the API Key for your Raygun Application
  n NAME:     the name of the person who created the deployment
  e EMAIL:    the email address of the person who created the deployment.
              Should be a Raygun users email
  g GIT_HASH: the git commit hash this deployment was built from
  NOTES:      the release notes for this deployment.
              Will be formatted using a Markdown parser
EOF
exit
fi

[ "$1" = "--" ] && shift

if [ "$1" != "" ]
then
    DEPLOYMENT_NOTES=$1
    DEPLOYMENT_NOTES=`echo $DEPLOYMENT_NOTES | sed s/\"/\\\\\\\\\"/g`
fi

url="https://app.raygun.com/deployments?authToken=$RAYGUN_AUTH_TOKEN"

read -d '' deployment <<- EOF
{
    apiKey: \"$RAYGUN_API_KEY\",
    version: \"$DEPLOYMENT_VERSION\",
    ownerName: \"$DEPLOYED_BY\",
    emailAddress: \"$EMAIL_ADDRESS\",
    scmIdentifier: \"$GIT_HASH\",
    comment: \"$DEPLOYMENT_NOTES\"
}
EOF

if ! curl -H "Content-Type: application/json" -d "$deployment" -f $url
then
  echo "Could not send deployment details to Raygun"
  exit 1
fi
```

**Note** that this example uses the [Raygun deployment commands](https://raygun.com/docs/deployments/bash) and requires additional environment variables to be set in the section above. It also requires values to be passed to the script via the environment or via arguments when you call the script. We recommend visiting the Raygun documentation for more information.

You can also run API calls in the same way, simply running API calls rather than the deployment commands above.


text:
<?php

namespace core\container;

class CreateException extends \Exception
{
}

?>


text:
use base::objc;
use base;

#[nolink]
#[link_args="-framework AppKit"]
pub extern mod appkit {
    fn NSBeep();
}

pub fn NSApp() -> base::id {
    unsafe {
        let klass = str::as_c_str(~"NSApplication", |s| objc::objc_getClass(s));
        let sel = str::as_c_str(~"sharedApplication", |s| objc::sel_registerName(s));
        objc::objc_msgSend(klass, sel)
    }
}


text:
<?php

namespace Application;

//use Application\Model\Services;

use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Mvc\Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Session\Config\SessionConfig;
use Zend\Session\Container;
use Zend\Session\SessionManager;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Application\Model\Users;
use Application\Model\UsersTable;
use Application\Model\Jobseekers;
use Application\Model\JobseekersTable;
use Application\Model\Rservices;
use Application\Model\RservicesTable;
use Application\Model\Industry;
use Application\Model\IndustryTable;
use Application\Model\Jobrole;
use Application\Model\JobroleTable;
use Application\Model\Pages;
use Application\Model\PagesTable;
use Application\Model\Services;
use Application\Model\ServicesTable;
use Application\Model\ServiceOption;
use Application\Model\ServiceOptionTable;
use Application\Model\Jobseekersdetails;
use Application\Model\JobseekersdetailsTable;
use Application\Model\Cart;
use Application\Model\CartTable;
use Application\Model\Payment;
use Application\Model\PaymentTable;
use Application\Model\Admins;
use Application\Model\AdminsTable;
use Application\Model\UserDetails;
use Application\Model\UserDetailsTable;

class Module implements ConfigProviderInterface
{
    private $app;
    private $serviceManager;

    public function onBootstrap(MvcEvent $e)
    {
       /* $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
     */
        $this->app = $e->getApplication();
        $this->serviceManager = $this->app->getServiceManager();

        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
        $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractController', 'dispatch', function($e) {
            $controller      = $e->getTarget();
            //var_dump($controller); exit;
            $controllerClass = get_class($controller);
            $moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
            $config          = $e->getApplication()->getServiceManager()->get('config');
            //echo "<pre>";
            //print_r($config);
            // echo $config['module_layouts'][$moduleNamespace];
            // exit;
            if (isset($config['module_layouts'][$moduleNamespace])) {
                $controller->layout($config['module_layouts'][$moduleNamespace]);
            }
        }, 100);
        $eventManager->attach('dispatch', array($this, 'setLayoutVars'));
        $eventManager->attach('dispatch', array($this, 'setBreadcrum'));
        $eventManager->attach('dispatch', array($this, 'setPaymentLayoutVars'));
        $eventManager->attach('dispatch', array($this, 'sessionVars'));
        $eventManager->attach('dispatch', array($this, 'getServices'));
        $eventManager->attach('dispatch', array($this, 'getPages'));

        $this->initSession(array(
            'remember_me_seconds' => 60*60*24*30 ,
            'use_cookies' => true,
            'cookie_httponly' => true,
        ));

    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getPages(){

        $sm = $this->serviceManager;
        $pagesTable = $sm->get('\Application\Model\PagesTable');

        $res = $pagesTable->getMenuLink();
        return $res;
    }

    public function getServices(MvcEvent $e){

        $sm = $this->serviceManager;
        $serviceTable = $sm->get('\Application\Model\ServicesTable');

        $res = $serviceTable->getServices("","none");
        $controller = $e->getTarget();
        $controller->layout()->setVariable('serviceMenu' , $res);
        return;
    }

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                '\Application\Model\UsersTable' =>  function($sm) {
                    $tableGateway = $sm->get('UsersTableGateway');
                    $table = new UsersTable($tableGateway);
                    return $table;
                },
                'UsersTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Users());
                    return new TableGateway('users', $dbAdapter, null, $resultSetPrototype);
                },

               /*  '\Application\Model\JobseekersTable' =>  function($sm) {
                    $tableGateway = $sm->get('JobseekersTableGateway');
                    $table = new JobseekersTable($tableGateway);
                    return $table;
                },
                'JobseekersTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Jobseekers());
                    return new TableGateway('jobseekers', $dbAdapter, null, $resultSetPrototype);
                },*/

                '\Application\Model\RservicesTable' =>  function($sm) {
                    $tableGateway = $sm->get('RservicesTableGateway');
                    $table = new RservicesTable($tableGateway);
                    return $table;
                },
                'RservicesTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Rservices());
                    return new TableGateway('services', $dbAdapter, null, $resultSetPrototype);
                },

                '\Application\Model\IndustryTable' =>  function($sm) {
                    $tableGateway = $sm->get('IndustryTableGateway');
                    $table = new IndustryTable($tableGateway);
                    return $table;
                },
                'IndustryTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Industry());
                    return new TableGateway('cj_mast_industry', $dbAdapter, null, $resultSetPrototype);
                },
                '\Application\Model\JobroleTable' =>  function($sm) {
                    $tableGateway = $sm->get('JobroleTableGateway');
                    $table = new JobroleTable($tableGateway);
                    return $table;
                },
                'JobroleTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Jobrole());
                    return new TableGateway('cj_mast_jobrole', $dbAdapter, null, $resultSetPrototype);
                },
                '\Application\Model\PagesTable' =>  function($sm) {
                    $tableGateway = $sm->get('PagesTableGateway');
                    $table = new PagesTable($tableGateway);
                    return $table;
                },
                'PagesTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Pages());
                    return new TableGateway('pages', $dbAdapter, null, $resultSetPrototype);
                },
                '\Application\Model\ServicesTable' =>  function($sm) {
                    $tableGateway = $sm->get('ServicesTableGateway');
                    $table = new ServicesTable($tableGateway);
                    return $table;
                },
                'ServicesTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Services());
                    return new TableGateway('services', $dbAdapter, null, $resultSetPrototype);
                },
                '\Application\Model\ServiceOptionTable' =>  function($sm) {
                    $tableGateway = $sm->get('ServiceOptionTableGateway');
                    $table = new ServiceOptionTable($tableGateway);
                    return $table;
                },
                'ServiceOptionTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new ServiceOption());
                    return new TableGateway('service_options', $dbAdapter, null, $resultSetPrototype);
                },
                '\Application\Model\CartTable' =>  function($sm) {
                    $tableGateway = $sm->get('CartTableGateway');
                    $table = new CartTable($tableGateway);
                    return $table;
                },
                'CartTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Cart());
                    return new TableGateway('resume_cart', $dbAdapter, null, $resultSetPrototype);
                },
                /*'\Application\Model\JobseekersdetailsTable' =>  function($sm) {
                    $tableGateway = $sm->get('JobseekersdetailsTableGateway');
                    $table = new JobseekersdetailsTable($tableGateway);
                    return $table;
                },
                'JobseekersdetailsTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Jobseekersdetails());
                    return new TableGateway('cj_ch_jobseekers_res_det', $dbAdapter, null, $resultSetPrototype);
                },*/
                '\Application\Model\PaymentTable' =>  function($sm) {
                    $tableGateway = $sm->get('PaymentTableGateway');
                    $table = new PaymentTable($tableGateway);
                    return $table;
                },
                'PaymentTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Payment());
                    return new TableGateway('payment', $dbAdapter, null, $resultSetPrototype);
                },
                '\Application\Model\AdminsTable' =>  function($sm) {
                    $tableGateway = $sm->get('AdminsTableGateway');
                    $table = new AdminsTable($tableGateway);
                    return $table;
                },
                'AdminsTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Admins());
                    return new TableGateway('admins', $dbAdapter, null, $resultSetPrototype);
                },
                '\Application\Model\UserDetailsTable' =>  function($sm) {
                    $tableGateway = $sm->get('UserDetailsTableGateway');
                    $table = new UserDetailsTable($tableGateway);
                    return $table;
                },
                'UserDetailsTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new UserDetails() );
                    return new TableGateway('user_details', $dbAdapter, null, $resultSetPrototype);
                },

            ),

        );
    }

    public function getControllerConfig()
    {
        return [
            'factories' => [
                Controller\IndexController::class => function($container) {
                    return new Controller\IndexController(
                        $container->get(Model\IndustryTable::class)
                    );
                },
            ],
        ];
    }

    public function setPaymentLayoutVars($e){
        //$target->layout()->setVariable('name', $admin_session->name);
        $controller      = $e->getTarget();
        $controllerClass = get_class($controller);
        $moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
        $actionArray = explode('\\', $controllerClass);
        $action = end($actionArray);
        // var_dump($action); exit;
        $action = $e->getRouteMatch()->getMatchedRouteName();
        $target = $e->getTarget();
        //var_dump($target); exit;
        $target->layout()->setVariable('routeName', ucfirst($action));

        // for making the  user name avaialble after login
        $adminSession = new Container('admin');
        if(isset($adminSession->admin)){
            $target->layout()->setVariable('admin', $adminSession->admin);
        }

        return;

    }

    public function setLayoutVars($e){
        //$target->layout()->setVariable('name', $admin_session->name);
        $controller      = $e->getTarget();
        $controllerClass = get_class($controller);
        $moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
        $actionArray = explode('\\', $controllerClass);
        $action = end($actionArray);
        // var_dump($action); exit;
        $action = $e->getRouteMatch()->getMatchedRouteName();
        $target = $e->getTarget();
        //var_dump($target); exit;
        $target->layout()->setVariable('routeName', ucfirst($action));

        // for making the  user name avaialble after login
        $userSession = new Container('user');
        if(isset($userSession->userDetails)){
            $target->layout()->setVariable('userDetails', $userSession->userDetails);
        }

        return;

    }

    public function setBreadcrum($e){
        //$target->layout()->setVariable('name', $admin_session->name);
        $controller      = $e->getTarget();
        $controllerClass = get_class($controller);
        $moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
        $actionArray = explode('\\', $controllerClass);
        $action = end($actionArray);
        //var_dump($action); exit;
        //$action = $e->getRouteMatch()->getMatchedRouteName();

        $controllerName = $e->getRouteMatch()->getMatchedRouteName();
        //echo $controllerName;
        // getting service name so we can genrate breadcrum
        $controller->layout()->setVariable('controllerName' , $controllerName);

        if($action=="IndexController" || $action == "RegisterController" || $action == "ProfileController"  ){
            $controller->layout()->setVariable('bread' , "false");

        } else {
            $controller->layout()->setVariable('bread' , "true");
            ///$controller->layout()->setVariable('serviceName' , "dddd");

        }

        return;

    }

    public function sessionVars(MvcEvent $e){
        $session = new Container('user');
        //$session->user = 'Foo'; //store username
        //echo "jshdsjkdh" ; var_dump($session->user);  exit;
        $controller = $e->getTarget();
        $controller->layout()->setVariable('user' , $session->userDetails);
        $cart_session = new Container('cart');
        $controller->layout()->setVariable('cart_count' , $cart_session->cart_count);

        return;
    }

    public function initSession($config)
    {
        $sessionConfig = new SessionConfig();
        $sessionConfig->setOptions($config);
        $sessionManager = new SessionManager($sessionConfig);
        $sessionManager->start();
        Container::setDefaultManager($sessionManager);
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Opegrapha aenea Lam. & DC.

### Remarks
null


text:
#!/usr/bin/env node

var _ = require('underscore');
var app = require('./package.json');
var opts = require('commander');
var path = require('path');
var utils = require('./utils');

// globals for keeping track of walked files/dirs
var dirs = [];
var files = [];

// There are only two options: encrypt, and decrypt.
//
// Note:
// e.g. .option('FLAG, EXPANDED_FLAG|OPTION_NAME', 'DEFAULT|DESCRIPTION')
opts
  .version( app.version )
  .usage('[options]')
  .option('-e, --encrypt', 'the option to encrypt files')
  .option('-d, --decrypt', 'the option to decrypt files')
  .parse(process.argv);

// ensure notes, encrypted, and tmp directories exist
if (!utils.directoryExists('./notes')) {
  utils.createDirectory('./notes');
}
if (!utils.directoryExists('./encrypted')) {
  utils.createDirectory('./encrypted');
}
if (!utils.directoryExists('/tmp/notes')) {
  utils.createDirectory('/tmp/notes');
}
if (!utils.directoryExists('/tmp/encrypted')) {
  utils.createDirectory('/tmp/encrypted');
}

/**
 * Creates a file based on given parameters
 *
 * @param {String} root
 * @param {Object} stat
 * @param {function} next
 */
var walkFileCallback = function(root, stat, next) {
  var filePath = path.join(root, stat.name);
  files.push(filePath);
  next();
};

/**
 * Creates a directory based on given parameters
 *
 * @param {String} root
 * @param {Object} stat
 * @param {function} next
 */
var walkDirCallback = function(root, stat, next) {
  var dirPath = path.join(root, stat.name);
  dirs.push(dirPath);
  next();
};

/**
 * Reports error and exits
 *
 * @param {String} root
 * @param {Object} stats
 * @param {function} next
 */
var walkErrorCallback = function(root, stats, next) {
  console.log('walk error!');
  process.exit(1);
  // next();
};

if (opts.encrypt) {

  // locally backup encrypted dir before we try to encrypt
  utils.copyDirectory('./encrypted', '/tmp/encrypted', function(err) {
    // catch any copying error
    if (err) {
      console.log('error creating local backup!');
      process.exit(1);
    }

    utils.promptForPassword(function(err, result) {
      if (err) {
        console.log('problem with password prompt');
      }

      // walk notes dir
      utils.walk('./notes', walkFileCallback, walkDirCallback,
          walkErrorCallback, function doneCallback() {
        // create dirs
        _.each(dirs, function(dir) {
          var destination =
              path.join('./encrypted', utils.stripLeadingDirectory(dir));
          try {
            utils.createDirectory(destination);
          } catch(e) {
            if (e.code !== 'EEXIST') {
              process.exit(1);
            }
          }
        });

        // read note files, encrypt them, and save them in the destination dir
        _.each(files, function(file) {
          var destination =
              path.join('./encrypted', utils.stripLeadingDirectory(file));
          var data = utils.getFile(file);
          utils.saveEncryptedFile(data, destination, result.password);
        });
      });

    });

  });
} else if (opts.decrypt) {

  // locally backup notes dir before we try to decrypt
  utils.copyDirectory('./notes', '/tmp/notes', function(err) {
    if (err) {
      console.log('error creating local backup!');
      process.exit(1);
    }

    utils.promptForPassword(function(err, result) {
      if (err) {
        console.log('problem with password prompt');
      }

      // walk encrypted dir
      utils.walk('./encrypted', walkFileCallback, walkDirCallback,
          walkErrorCallback, function doneCallback() {
        // create dirs
        _.each(dirs, function(dir) {
          var destination =
              path.join('./notes', utils.stripLeadingDirectory(dir));
          try {
            utils.createDirectory(destination);
          } catch(e) {
            // if the directory exists, skip over the error. Otherwise exit.
            if (e.code !== 'EEXIST') {
              process.exit(1);
            }
          }
        });

        // read note files, decrypt them, and save them in the destination dir
        _.each(files, function(file) {
          var destination =
              path.join('./notes', utils.stripLeadingDirectory(file));
          var data = utils.getEncryptedFile(file, result.password);
          utils.saveFile(data, destination);
        });

      });

    });

  });

} else {
  // report error
  console.log('error, no option chosen');
}


text:
package org.gearvrf.jassimp2;

/**
 * Defines how the Nth texture of a specific type is combined with the result
 * of all previous layers.

 *
 * Example (left: key, right: value):

 *

 *  DiffColor0     - gray
 *  DiffTextureOp0 - aiTextureOpMultiply
 *  DiffTexture0   - tex1.png
 *  DiffTextureOp0 - aiTextureOpAdd
 *  DiffTexture1   - tex2.png
 *

 *
 * Written as equation, the final diffuse term for a specific pixel would be:
 *

 *  diffFinal = DiffColor0 * sampleTex(DiffTexture0,UV0) +
 *     sampleTex(DiffTexture1,UV0) * diffContrib;
 *

 * where 'diffContrib' is the intensity of the incoming light for that pixel.
 */
public enum AiTextureOp {
    /**
     * T = T1 * T2.
     */
    MULTIPLY(0x0),

    /**
     * T = T1 + T2.
      */
    ADD(0x1),

    /**
     * T = T1 - T2.
      */
    SUBTRACT(0x2),

    /**
     * T = T1 / T2.
     */
    DIVIDE(0x3),

    /**
     * T = (T1 + T2) - (T1 * T2) .
     */
    SMOOTH_ADD(0x4),

    /**
     * T = T1 + (T2-0.5).
     */
    SIGNED_ADD(0x5);

    /**
     * Utility method for converting from c/c++ based integer enums to java
     * enums.

     *
     * This method is intended to be used from JNI and my change based on
     * implementation needs.
     *
     * @param rawValue an integer based enum value (as defined by assimp)
     * @return the enum value corresponding to rawValue
     */
    static AiTextureOp fromRawValue(int rawValue) {
        for (AiTextureOp type : AiTextureOp.values()) {
            if (type.m_rawValue == rawValue) {
                return type;
            }
        }

        throw new IllegalArgumentException("unexptected raw value: " +
                rawValue);
    }

    /**
     * Constructor.
     *
     * @param rawValue maps java enum to c/c++ integer enum values
     */
    private AiTextureOp(int rawValue) {
        m_rawValue = rawValue;
    }

    /**
     * The mapped c/c++ integer enum value.
     */
    private final int m_rawValue;
}


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0                       http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.torquebox.mojo.jruby9</groupId>
  <artifactId>test</artifactId>
  <version>testing</version>

  <repositories>
    <repository>
      <id>mavengems</id>
      <url>mavengem:https://rubygems.org</url>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>mavengems</id>
      <url>mavengem:https://rubygems.org</url>
    </pluginRepository>
  </pluginRepositories>

  <dependencies>
    <dependency>
      <groupId>org.torquebox.mojo.jruby9</groupId>
      <artifactId>archive</artifactId>
      <version>testing</version>
    </dependency>
    <dependency>
      <groupId>org.jruby</groupId>
      <artifactId>jruby-complete</artifactId>
      <version>${j.version}</version>
      <type>jar</type>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>rubygems</groupId>
      <artifactId>rspec</artifactId>
      <version>3.3.0</version>
      <type>gem</type>
    </dependency>
  </dependencies>

  <properties>
    <j.version>1.7.22</j.version>
  </properties>

  <build>
    <extensions>
      <extension>
        <groupId>org.torquebox.mojo</groupId>
        <artifactId>mavengem-wagon</artifactId>
        <version>0.2.0</version>
      </extension>
    </extensions>
    <plugins>
      <plugin>
        <groupId>de.saumya.mojo</groupId>
        <artifactId>gem-maven-plugin</artifactId>
        <version>1.1.3</version>
       	<executions>
	  <execution>
            <goals>
              <goal>initialize</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
"""Sketch handler."""

import os

from typing import Dict

from dm_nevis.datasets_storage.handlers import extraction_utils as eu
from dm_nevis.datasets_storage.handlers import splits
from dm_nevis.datasets_storage.handlers import types

from tensorflow.io import gfile

def _path_to_label_fn(path: str, label_to_id: Dict[str, int]) -> int:
  label = os.path.basename(os.path.dirname(path))
  return label_to_id[label]

def sketch_handler(dataset_path: str) -> types.HandlerOutput:
  """Handler for Sketch dataset."""
  files = gfile.listdir(dataset_path)

  labels = [
      'snail', 'candle', 'crane (machine)', 'parking meter', 'bathtub',
      'loudspeaker', 'bulldozer', 'skateboard', 'ant', 'radio', 'tennis-racket',
      'envelope', 'house', 'person walking', 'basket', 'rainbow', 'paper clip',
      'alarm clock', 'screwdriver', 'cactus', 'umbrella', 'carrot', 'fan',
      'kangaroo', 'bell', 't-shirt', 'hedgehog', 'santa claus', 'angel',
      'trousers', 'eyeglasses', 'pretzel', 'snake', 'elephant', 'frying-pan',
      'bread', 'rollerblades', 'tomato', 'cake', 'couch', 'pizza', 'crown',
      'cannon', 'baseball bat', 'moon', 'potted plant', 'cup', 'syringe',
      'pipe (for smoking)', 'hand', 'telephone', 'pumpkin', 'race car', 'table',
      'brain', 'snowboard', 'flashlight', 'cloud', 'helmet', 'monkey',
      'ice-cream-cone', 'wineglass', 'strawberry', 'speed-boat', 'cigarette',
      'pigeon', 'book', 'lion', 'rabbit', 'violin', 'grenade', 'skull',
      'car (sedan)', 'bee', 'head', 'spoon', 'ship', 'laptop', 'diamond',
      'church', 'spider', 'wheelbarrow', 'flower with stem', 'mosquito',
      'apple', 'giraffe', 'submarine', 'tree', 'harp', 'face', 'boomerang',
      'floor lamp', 'fork', 'horse', 'scissors', 'cell phone', 'comb',
      'beer-mug', 'helicopter', 'hot air balloon', 'bear (animal)', 'lightbulb',
      'trombone', 'computer monitor', 'computer-mouse', 'fire hydrant',
      'squirrel', 'camera', 'binoculars', 'sponge bob', 'streetlight', 'blimp',
      'satellite', 'rooster', 'key', 'windmill', 'duck', 'zebra', 'armchair',
      'skyscraper', 'bookshelf', 'shark', 'tablelamp', 'nose', 'truck', 'fish',
      'chandelier', 'bottle opener', 'mailbox', 'donut', 'door', 'chair',
      'castle', 'ipod', 'power outlet', 'wrist-watch', 'wheel', 'dog', 'bus',
      'foot', 'panda', 'megaphone', 'microscope', 'bench', 'snowman', 'mug',
      'sun', 'wine-bottle', 'suv', 'vase', 'door handle', 'arm', 'ear',
      'hot-dog', 'ladder', 'banana', 'toilet', 'pineapple', 'mushroom',
      'dolphin', 'mouse (animal)', 'owl', 'hat', 'palm tree', 'tv',
      'calculator', 'bicycle', 'standing bird', 'bowl', 'ashtray', 'trumpet',
      'microphone', 'saxophone', 'leaf', 'tire', 'bed', 'shovel', 'socks',
      'traffic light', 'feather', 'crab', 'frog', 'walkie talkie', 'purse',
      'hammer', 'parrot', 'rifle', 'sailboat', 'scorpion', 'head-phones',
      'backpack', 'toothbrush', 'guitar', 'human-skeleton', 'bridge', 'bush',
      'axe', 'sheep', 'mermaid', 'eye', 'pig', 'cabinet', 'sword',
      'satellite dish', 'keyboard', 'stapler', 'teacup', 'present', 'motorbike',
      'airplane', 'canoe', 'pear', 'teddy-bear', 'knife', 'butterfly', 'camel',
      'flying saucer', 'pickup truck', 'van', 'swan', 'sea turtle', 'teapot',
      'tractor', 'hourglass', 'tooth', 'lobster', 'hamburger', 'grapes',
      'mouth', 'parachute', 'dragon', 'person sitting', 'pen', 'train', 'tent',
      'tiger', 'revolver', 'suitcase', 'shoe', 'barn', 'flying bird', 'octopus',
      'seagull', 'space shuttle', 'cat', 'crocodile', 'piano', 'penguin', 'cow',
      'lighter'
  ]

  label_to_id = dict(
      ((label, label_id) for label_id, label in enumerate(labels)))

  metadata = types.DatasetMetaData(
      num_classes=250,
      num_channels=1,
      image_shape=(),  # Ignored for now.
      additional_metadata=dict(
          label_to_id=label_to_id,
          task_type='classification',
          image_type='object',
      ))

  ignored_files_regex = [eu.DEFAULT_IGNORED_FILES_REGEX, r'filelist.txt']
  ignored_files_regex = '|'.join(ignored_files_regex)

  def make_gen_fn():
    return eu.generate_images_from_zip_files(
        dataset_path,
        files,
        path_to_label_fn=lambda path: _path_to_label_fn(path, label_to_id),
        ignored_files_regex=ignored_files_regex)

  per_split_gen = splits.random_split_generator_into_splits_with_fractions(
      make_gen_fn, splits.SPLIT_WITH_FRACTIONS_FOR_ALL_DATA,
      splits.MERGED_TRAIN_AND_DEV)

  return metadata, per_split_gen

sketch_dataset = types.DownloadableDataset(
    name='sketch',
    download_urls=[
        types.DownloadableArtefact(
            url='https://cybertron.cg.tu-berlin.de/eitz/projects/classifysketch/sketches_png.zip',
            checksum='023123df86a928a5273e3ba11990d8fd')
    ],
    website_url='https://cybertron.cg.tu-berlin.de/eitz/projects/classifysketch',
    handler=sketch_handler)


text:
<!DOCTYPE html>

	<title>Integration with dhtmlxScheduler</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/fonts/font_roboto/roboto.css"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>


text:
<?php

declare(strict_types=1);

namespace FSi\Bundle\AdminBundle\EventListener;

use FSi\Bundle\AdminBundle\Admin\Element;
use FSi\Bundle\AdminBundle\Admin\ManagerInterface;
use FSi\Bundle\AdminBundle\Event\MenuEvent;
use FSi\Bundle\AdminBundle\Menu\Builder\Exception\InvalidYamlStructureException;
use FSi\Bundle\AdminBundle\Menu\Item\ElementItem;
use FSi\Bundle\AdminBundle\Menu\Item\Item;
use Symfony\Component\Yaml\Yaml;

class MainMenuListener
{
    /**
     * @var string
     */
    private $configFilePath;

    /**
     * @var Yaml
     */
    private $yaml;

    /**
     * @var ManagerInterface
     */
    private $manager;

    public function __construct(ManagerInterface $manager, string $configFilePath)
    {
        $this->configFilePath = $configFilePath;
        $this->yaml = new Yaml();
        $this->manager = $manager;
    }

    public function createMainMenu(MenuEvent $event): Item
    {
        if (defined('Symfony\Component\Yaml\Yaml::PARSE_OBJECT')) {
            $config = $this->yaml->parse(
                file_get_contents($this->configFilePath),
                Yaml::PARSE_OBJECT | Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE
            );
        } else {
            $config = $this->yaml->parse(file_get_contents($this->configFilePath), true, true);
        }

        if (!isset($config['menu'])) {
            throw new InvalidYamlStructureException(
                sprintf('File "%s" should contain top level "menu:" key', $this->configFilePath)
            );
        }

        $menu = $event->getMenu();
        $menu->setOptions([
            'attr' => [
                'id' => 'top-menu',
                'class' => 'nav navbar-nav',
            ]
        ]);

        $this->populateMenu($menu, $config['menu']);

        return $menu;
    }

    private function populateMenu(Item $menu, array $configs): void
    {
        foreach ($configs as $itemConfig) {
            $item = $this->buildSingleItem($itemConfig);

            if (null !== $item) {
                $options = ['attr' => ['class' => 'admin-element']];
                if ($item instanceof ElementItem) {
                    $options['elements'] = $this->buildItemElements($itemConfig);
                }
                $item->setOptions($options);
            }

            if (null === $item) {
                if ($this->isSingleItem($itemConfig)) {
                    continue;
                }
                $item = new Item(key($itemConfig));
                $group = array_values($itemConfig);
                $this->populateMenu($item, $group[0]);
            }

            $menu->addChild($item);
        }
    }

    /**
     * @param array|string $itemConfig
     * @return Item|null
     */
    private function buildSingleItem($itemConfig): ?Item
    {
        if (is_string($itemConfig)) {
            if ($this->manager->hasElement($itemConfig)) {
                return new ElementItem($itemConfig, $this->manager->getElement($itemConfig));
            }

            return new Item($itemConfig);
        }

        if (!$this->isSingleItem($itemConfig) || !$this->manager->hasElement($itemConfig['id'])) {
            return null;
        }

        return new ElementItem(
            $this->hasEntry($itemConfig, 'name') ? $itemConfig['name'] : $itemConfig['id'],
            $this->manager->getElement($itemConfig['id'])
        );
    }

    /**
     * @param array|string $itemConfig
     * @return bool
     */
    private function isSingleItem($itemConfig): bool
    {
        return $this->hasEntry($itemConfig, 'id');
    }

    /**
     * @param array|string $itemConfig
     * @param string $keyName
     * @return bool
     */
    private function hasEntry($itemConfig, string $keyName): bool
    {
        return is_array($itemConfig) && array_key_exists($keyName, $itemConfig);
    }

    /**
     * @param array|string $itemConfig
     * @return Element[]
     */
    private function buildItemElements($itemConfig): array
    {
        $elements = [];

        if ($this->hasEntry($itemConfig, 'elements')) {
            $elementIds = (array)$itemConfig['elements'];
            foreach ($elementIds as $elementId) {
                $elements[] = $this->manager->getElement($elementId);
            }
        }

        return $elements;
    }
}


text:
<?php

namespace AngryBytes\Cache\Adapter;

use AngryBytes\Cache\Adapter;
use AngryBytes\Cache\ResultNotFound;

use AngryBytes\Cache\Adapter\Memcached\AdapterInterface as MemcachedAdapterInterface;
use AngryBytes\Cache\Adapter\Memcached\Adapter as MemcachedAdapter;

use \Exception as Exception;

/**
 * Memcached
 *
 * Simple memcached adapter for AngryBytes\Cache.
 *
 * Does not use any of the more advanced functions such as CAS and deferred
 * loading. Allows multiple servers to be added through addServer().
 *
 * @category        AngryBytes
 * @package         Cache
 * @subpackage      Adapter
 */
class Memcached extends Adapter
{
    /**
     * Memcached adapter
     *
     * @var MemcachedAdapterInterface
     **/
    private $memcached;

    /**
     * Constructor
     *
     * @param  mixed $persistentId By default the Memcached instances are destroyed at the end of the request.
     *                             To create an instance that persists between requests, use $persistentId to
     *                             specify a unique ID for the instance. All instances created with the same
     *                             $persistentId will share the same connection.
     * @return void
     **/
    public function __construct($persistentId = null)
    {
        // Init the adapter
        $this->setMemcached(
            new MemcachedAdapter($persistentId)
        );
    }

    /**
     * Get the memcached adapter
     *
     * @return MemcachedAdapterInterface
     */
    public function getMemcached()
    {
        return $this->memcached;
    }

    /**
     * Set the memcached adapter
     *
     * @param  MemcachedAdapterInterface $memcached
     * @return Memcached
     */
    public function setMemcached(MemcachedAdapterInterface $memcached)
    {
        $this->memcached = $memcached;

        return $this;
    }

    /**
     * Add a server
     *
     * @param  string    $host
     * @param  int       $port
     * @param  int       $weight
     * @return Memcached
     **/
    public function addServer($host, $port, $weight = 0)
    {
        $this->getMemcached()->addServer($host, $port, $weight);

        return $this;
    }

    /**
     * Save some data
     *
     * @param  string $data
     * @param  string $id
     * @param  int    $lifeTime lifetime in seconds
     * @return bool
     **/
    public function save($data, $id, $lifeTime)
    {
        return $this->getMemcached()->set($id, $data, $lifeTime);
    }

    /**
     * Load an item from the cache
     *
     * @param  string               $id
     * @return mixed|ResultNotFound
     **/
    public function load($id)
    {
        $result = $this->getMemcached()->get($id);

        if ($this->getMemcached()->getResultCode() !== MemcachedAdapter::RES_SUCCESS) {
            return new ResultNotFound($id);
        }

        return $result;
    }

    /**
     * Delete an item from the cache
     *
     * @param  string $id
     * @return bool
     **/
    public function delete($id)
    {
        return $this->getMemcached()->delete($id);
    }
}


text:
#import <Foundation/Foundation.h>

#import "FIRAuth.h"
#import "FIRMultiFactorAssertion.h"
#import "FIRMultiFactorInfo.h"
#import "FIRMultiFactorSession.h"

NS_ASSUME_NONNULL_BEGIN

/** @typedef FIRMultiFactorSessionCallback
    @brief The callback that triggered when a developer calls `getSessionWithCompletion`.
        This type is available on iOS only.
    @param session The multi factor session returned, if any.
    @param error The error which occurred, if any.
*/
typedef void (^FIRMultiFactorSessionCallback)(FIRMultiFactorSession *_Nullable session,
                                              NSError *_Nullable error)
    NS_SWIFT_UNAVAILABLE("Use Swift's closure syntax instead.")
        API_UNAVAILABLE(macos, tvos, watchos);

/**
   @brief The string identifier for second factors. e.g. "phone".
        This constant is available on iOS only.
*/
extern NSString *const _Nonnull FIRPhoneMultiFactorID NS_SWIFT_NAME(PhoneMultiFactorID)
    API_UNAVAILABLE(macos, tvos, watchos);

/** @class FIRMultiFactor
    @brief The interface defining the multi factor related properties and operations pertaining to a
        user.
        This class is available on iOS only.
*/
NS_SWIFT_NAME(MultiFactor) API_UNAVAILABLE(macos, tvos, watchos) @interface FIRMultiFactor
    : NSObject

@property(nonatomic, readonly) NSArray<FIRMultiFactorInfo *> *enrolledFactors;

/** @fn getSessionWithCompletion:
    @brief Get a session for a second factor enrollment operation.
    @param completion A block with the session identifier for a second factor enrollment operation.
        This is used to identify the current user trying to enroll a second factor.
*/
- (void)getSessionWithCompletion:(nullable void (^)(FIRMultiFactorSession *_Nullable credential,
                                                    NSError *_Nullable error))completion;

/** @fn enrollWithAssertion:displayName:completion:
    @brief Enrolls a second factor as identified by the `MultiFactorAssertion` parameter for the
        current user.
    @param displayName An optional display name associated with the multi factor to enroll.
    @param completion The block invoked when the request is complete, or fails.
*/
- (void)enrollWithAssertion:(FIRMultiFactorAssertion *)assertion
                displayName:(nullable NSString *)displayName
                 completion:(nullable void (^)(NSError *_Nullable error))completion;

/** @fn unenrollWithInfo:completion:
    @brief Unenroll the given multi factor.
    @param completion The block invoked when the request to send the verification email is complete,
        or fails.
*/
- (void)unenrollWithInfo:(FIRMultiFactorInfo *)factorInfo
              completion:(nullable void (^)(NSError *_Nullable error))completion;

/** @fn unenrollWithFactorUID:completion:
    @brief Unenroll the given multi factor.
    @param completion The block invoked when the request to send the verification email is complete,
        or fails.
*/
- (void)unenrollWithFactorUID:(NSString *)factorUID
                   completion:(nullable void (^)(NSError *_Nullable error))completion;

@end

NS_ASSUME_NONNULL_END


text:
<title>dlib C++ Library - set_kernel_c.h</title>

// Copyright (C) 2003  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_SET_KERNEl_C_
#define DLIB_SET_KERNEl_C_

#include "set_kernel_abstract.h"
#include "../algs.h"
#include "../assert.h"

namespace dlib
{

    template <
        typename set_base
        >
    class set_kernel_c : public set_base
    {
        typedef typename set_base::type T;
    public:

        void add (
            T& item
        );

        void remove_any (
            T& item
        );

        void remove (
            const T& item,
            T& item_copy
        );

        void destroy (
            const T& item
        );

        const T& element (
        );

        const T& element (
        ) const;
    };

    template <
        typename set_base
        >
    inline void swap (
        set_kernel_c<set_base>& a,
        set_kernel_c<set_base>& b
    ) { a.swap(b); }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        typename set_base
        >
    void set_kernel_c<set_base>::
    add(
        T& item
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT( !this->is_member(item),
                 "\tvoid set::add"
                 << "\n\titem being added must not already be in the set"
                 << "\n\tthis: " << this
        );

        // call the real function
        set_base::add(item);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename set_base
        >
    void set_kernel_c<set_base>::
    remove (
        const T& item,
        T& item_copy
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT( this->is_member(item) &&
                 (static_cast<const void*>(&item) != static_cast<void*>(&item_copy)),
                 "\tvoid set::remove"
                 << "\n\titem should be in the set if it's going to be removed"
                 << "\n\tthis:            " << this
                 << "\n\t&item:           " << &item
                 << "\n\t&item_copy:      " << &item_copy
                 << "\n\tis_member(item): " << (this->is_member(item)?"true":"false")
        );

        // call the real function
        set_base::remove(item,item_copy);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename set_base
        >
    void set_kernel_c<set_base>::
    destroy (
        const T& item
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT( this->is_member(item),
                 "\tvoid set::destroy"
                 << "\n\titem should be in the set if it's going to be removed"
                 << "\n\tthis:            " << this
                 << "\n\t&item:           " << &item
        );

        // call the real function
        set_base::destroy(item);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename set_base
        >
    void set_kernel_c<set_base>::
    remove_any (
        T& item
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT( this->size() != 0,
                 "\tvoid set::remove_any"
                 << "\n\tsize must be greater than zero if an item is to be removed"
                 << "\n\tthis: " << this
        );

        // call the real function
        set_base::remove_any(item);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename set_base
        >
    const typename set_base::type& set_kernel_c<set_base>::
    element (
    ) const
    {
        // make sure requires clause is not broken
        DLIB_CASSERT(this->current_element_valid() == true,
                "\tconst T& set::element() const"
                << "\n\tyou can't access the current element if it doesn't exist"
                << "\n\tthis: " << this
        );

        // call the real function
        return set_base::element();
    }

// ----------------------------------------------------------------------------------------

    template <
        typename set_base
        >
    const typename set_base::type& set_kernel_c<set_base>::
    element (
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT(this->current_element_valid() == true,
                "\tconst T& set::element"
                << "\n\tyou can't access the current element if it doesn't exist"
                << "\n\tthis: " << this
        );

        // call the real function
        return set_base::element();
    }

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_SET_KERNEl_C_


text:
/*
 * This example was developed using the following STMicroelectronics
 * evaluation boards:
 *
 * - STEVAL_MKI109V3 + STEVAL-MKI197V1
 * - NUCLEO_F411RE + STEVAL-MKI197V1
 * - DISCOVERY_SPC584B + STEVAL-MKI197V1
 *
 * Used interfaces:
 *
 * STEVAL_MKI109V3    - Host side:   USB (Virtual COM)
 *                    - Sensor side: SPI(Default) / I2C(supported)
 *
 * NUCLEO_STM32F411RE - Host side: UART(COM) to USB bridge
 *                    - Sensor side: I2C(Default) / SPI(supported)
 *
 * DISCOVERY_SPC584B  - Host side: UART(COM) to USB bridge
 *                    - Sensor side: I2C(Default) / SPI(supported)
 *
 * If you need to run this example on a different hardware platform a
 * modification of the functions: `platform_write`, `platform_read`,
 * `tx_com` and 'platform_init' is required.
 *
 */

/* STMicroelectronics evaluation boards definition
 *
 * Please uncomment ONLY the evaluation boards in use.
 * If a different hardware is used please comment all
 * following target board and redefine yours.
 */

//#define STEVAL_MKI109V3  /* little endian */
//#define NUCLEO_F411RE    /* little endian */
//#define SPC584B_DIS      /* big endian */

/* ATTENTION: By default the driver is little endian. If you need switch
 *            to big endian please see "Endianness definitions" in the
 *            header file of the driver (_reg.h).
 */

#if defined(STEVAL_MKI109V3)
/* MKI109V3: Define communication interface */
#define SENSOR_BUS hspi2
/* MKI109V3: Vdd and Vddio power supply values */
#define PWM_3V3 915

#elif defined(NUCLEO_F411RE)
/* NUCLEO_F411RE: Define communication interface */
#define SENSOR_BUS hi2c1

#elif defined(SPC584B_DIS)
/* DISCOVERY_SPC584B: Define communication interface */
#define SENSOR_BUS I2CD1

#endif

/* Includes ------------------------------------------------------------------*/
#include <string.h>
#include <stdio.h>
#include "lsm6dso32x_reg.h"

#if defined(NUCLEO_F411RE)
#include "stm32f4xx_hal.h"
#include "usart.h"
#include "gpio.h"
#include "i2c.h"

#elif defined(STEVAL_MKI109V3)
#include "stm32f4xx_hal.h"
#include "usbd_cdc_if.h"
#include "gpio.h"
#include "spi.h"
#include "tim.h"

#elif defined(SPC584B_DIS)
#include "components.h"
#endif

/* Private macro -------------------------------------------------------------*/
#define    BOOT_TIME            10 //ms

/* Private variables ---------------------------------------------------------*/
static uint8_t whoamI, rst;
static uint8_t tx_buffer[1000];

/* Extern variables ----------------------------------------------------------*/

/* Private functions ---------------------------------------------------------*/

/*
 *   WARNING:
 *   Functions declare in this section are defined at the end of this file
 *   and are strictly related to the hardware platform used.
 *
 */
static int32_t platform_write(void *handle, uint8_t reg, const uint8_t *bufp,
                              uint16_t len);
static int32_t platform_read(void *handle, uint8_t reg, uint8_t *bufp,
                             uint16_t len);
static void tx_com( uint8_t *tx_buffer, uint16_t len );
static void platform_delay(uint32_t ms);
static void platform_init(void);

/* Main Example --------------------------------------------------------------*/
void lsm6dso32x_tilt(void)
{
  lsm6dso32x_emb_sens_t emb_sens;
  stmdev_ctx_t dev_ctx;
  /* Uncomment to configure INT 1 */
  //lsm6dso32x_pin_int1_route_t int1_route;
  /* Uncomment to configure INT 2 */
  lsm6dso32x_pin_int2_route_t int2_route;
  /* Initialize mems driver interface */
  dev_ctx.write_reg = platform_write;
  dev_ctx.read_reg = platform_read;
  dev_ctx.handle = &SENSOR_BUS;
  /* Init test platform */
  platform_init();
  /* Wait sensor boot time */
  platform_delay(BOOT_TIME);
  /* Check device ID */
  lsm6dso32x_device_id_get(&dev_ctx, &whoamI);

  if (whoamI != LSM6DSO32X_ID)
    while (1);

  /* Restore default configuration */
  lsm6dso32x_reset_set(&dev_ctx, PROPERTY_ENABLE);

  do {
    lsm6dso32x_reset_get(&dev_ctx, &rst);
  } while (rst);

  /* Disable I3C interface */
  lsm6dso32x_i3c_disable_set(&dev_ctx, LSM6DSO32X_I3C_DISABLE);
  /*
   * Set XL Output Data Rate: The tilt function works at 26 Hz,
   * so the accelerometer ODR must be set at 26 Hz or higher values
   */
  lsm6dso32x_xl_data_rate_set(&dev_ctx, LSM6DSO32X_XL_ODR_26Hz);
  /* Set 2g full XL scale. */
  lsm6dso32x_xl_full_scale_set(&dev_ctx, LSM6DSO32X_4g);
  /* Enable Tilt in embedded function. */
  emb_sens.tilt = PROPERTY_ENABLE;
  lsm6dso32x_embedded_sens_set(&dev_ctx, &emb_sens);
  /* Uncomment if interrupt generation on Tilt INT1 pin */
  //lsm6dso32x_pin_int1_route_get(&dev_ctx, &int1_route);
  //int1_route.reg.emb_func_int1.int1_tilt = PROPERTY_ENABLE;
  //lsm6dso32x_pin_int1_route_set(&dev_ctx, &int1_route);
  /* Uncomment if interrupt generation on Tilt INT2 pin */
  lsm6dso32x_pin_int2_route_get(&dev_ctx, &int2_route);
  int2_route.tilt = PROPERTY_ENABLE;
  lsm6dso32x_pin_int2_route_set(&dev_ctx, int2_route);

  /* Uncomment to have interrupt latched */
  //lsm6dso32x_int_notification_set(&dev_ctx, PROPERTY_ENABLE);

  /* Wait Events. */
  while (1) {
    uint8_t is_tilt;
    /* Check if Tilt events */
    lsm6dso32x_tilt_flag_data_ready_get(&dev_ctx, &is_tilt);

    if (is_tilt) {
      sprintf((char *)tx_buffer, "TILT Detected\r\n");
      tx_com(tx_buffer, strlen((char const *)tx_buffer));
    }
  }
}

/*
 * @brief  Write generic device register (platform dependent)
 *
 * @param  handle    customizable argument. In this examples is used in
 *                   order to select the correct sensor bus handler.
 * @param  reg       register to write
 * @param  bufp      pointer to data to write in register reg
 * @param  len       number of consecutive register to write
 *
 */
static int32_t platform_write(void *handle, uint8_t reg, const uint8_t *bufp,
                              uint16_t len)
{
#if defined(NUCLEO_F411RE)
  HAL_I2C_Mem_Write(handle, LSM6DSO32X_I2C_ADD_L, reg,
                    I2C_MEMADD_SIZE_8BIT, (uint8_t*) bufp, len, 1000);
#elif defined(STEVAL_MKI109V3)
  HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_RESET);
  HAL_SPI_Transmit(handle, &reg, 1, 1000);
  HAL_SPI_Transmit(handle, (uint8_t*) bufp, len, 1000);
  HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_SET);
#elif defined(SPC584B_DIS)
  i2c_lld_write(handle,  LSM6DSO32X_I2C_ADD_L & 0xFE, reg,
               (uint8_t*) bufp, len);
#endif
  return 0;
}

/*
 * @brief  Read generic device register (platform dependent)
 *
 * @param  handle    customizable argument. In this examples is used in
 *                   order to select the correct sensor bus handler.
 * @param  reg       register to read
 * @param  bufp      pointer to buffer that store the data read
 * @param  len       number of consecutive register to read
 *
 */
static int32_t platform_read(void *handle, uint8_t reg, uint8_t *bufp,
                             uint16_t len)
{
#if defined(NUCLEO_F411RE)
  HAL_I2C_Mem_Read(handle, LSM6DSO32X_I2C_ADD_L, reg,
                   I2C_MEMADD_SIZE_8BIT, bufp, len, 1000);
#elif defined(STEVAL_MKI109V3)
  reg |= 0x80;
  HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_RESET);
  HAL_SPI_Transmit(handle, &reg, 1, 1000);
  HAL_SPI_Receive(handle, bufp, len, 1000);
  HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_SET);
#elif defined(SPC584B_DIS)
  i2c_lld_read(handle, LSM6DSO32X_I2C_ADD_L & 0xFE, reg, bufp, len);
#endif
  return 0;
}

/*
 * @brief  platform specific outputs on terminal (platform dependent)
 *
 * @param  tx_buffer     buffer to transmit
 * @param  len           number of byte to send
 *
 */
static void tx_com(uint8_t *tx_buffer, uint16_t len)
{
#if defined(NUCLEO_F411RE)
  HAL_UART_Transmit(&huart2, tx_buffer, len, 1000);
#elif defined(STEVAL_MKI109V3)
  CDC_Transmit_FS(tx_buffer, len);
#elif defined(SPC584B_DIS)
  sd_lld_write(&SD2, tx_buffer, len);
#endif
}

/*
 * @brief  platform specific delay (platform dependent)
 *
 * @param  ms        delay in ms
 *
 */
static void platform_delay(uint32_t ms)
{
#if defined(NUCLEO_F411RE) | defined(STEVAL_MKI109V3)
  HAL_Delay(ms);
#elif defined(SPC584B_DIS)
  osalThreadDelayMilliseconds(ms);
#endif
}

/*
 * @brief  platform specific initialization (platform dependent)
 */
static void platform_init(void)
{
#if defined(STEVAL_MKI109V3)
  TIM3->CCR1 = PWM_3V3;
  TIM3->CCR2 = PWM_3V3;
  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
  HAL_Delay(1000);
#endif
}


text:
package org.yq.spring.ch7.composable;

import org.junit.Test;
import org.springframework.aop.Advisor;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.ComposablePointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.yq.spring.ch7.cflow.SimpleBeforeAdvice;

public class SampleBeanTest {

	@Test
	public void test() {
		SampleBean target = new SampleBean();

		ComposablePointcut pc = new ComposablePointcut(ClassFilter.TRUE,
				new GetterMethodMatcher());

		System.out.println("Test 1");

		SampleBean proxy = getProxy(pc, target);
		testInvoke(proxy);

		System.out.println("Test 2");
		pc.union(new SetterMethodMatcher());
		proxy = getProxy(pc, target);
		testInvoke(proxy);

		System.out.println("Test 3");
		pc.intersection(new GetAgeMethodMatcher());
		proxy = getProxy(pc, target);
		testInvoke(proxy);
	}

	private void testInvoke(SampleBean proxy) {
		proxy.getAge();
		proxy.getName();
		proxy.setName("Clarence Ho");

	}

	private SampleBean getProxy(ComposablePointcut pc, SampleBean target) {
		Advisor advisor = new DefaultPointcutAdvisor(pc,
				new SimpleBeforeAdvice());
		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(target);
		pf.addAdvisor(advisor);

		return (SampleBean) pf.getProxy();
	}

}


text:
layout: post
title: Tracing code execution with Alive
---

We built [Alive](http://comealive.io) with one goal in mind: to show you what your code is doing the moment you write it. Recently, one of our users [let us know](https://github.com/CodeConnect/AliveFeedback/issues/44) that they wanted to see which lines of code were executed in their current function.

While Alive largely focuses on showing you what data flows through your programs, we saw this as an opportunity to visualize control flow as well.

Today we're happy to announce the introduction of **code highlighting** for Alive. Code highlighting grays out lines of code that were not executed, making it even easier to understand your code.

![GIF that shows before and after the highlighting](/images/Highlighting/highlighting-binary.gif)

---

Highlighting makes it easy to see which code paths were taken in a method and how these paths are impacted when you change your code.

<video autoplay loop preload>
		<source src="https://codeconnectcdn.blob.core.windows.net/cdn/blog/highlighting-editing.mp4" type="video/mp4">
		<source src="https://codeconnectcdn.blob.core.windows.net/cdn/blog/highlighting-editing.webm" type="video/webm">
</video>

---

Highlighting reveals where the assertion aborted code execution.

![Screenshot that shows behavior with exception](/images/Highlighting/highlighting-with-exception.png)

---

As usual, we're always open to feature requests and bug reports on our [public issue tracker](http://github.com/CodeConnect/AliveFeedback/).

P.S. We're interested in investigating how Alive could also be used to teach students how to program. If you run a code camp or teach classes on programming please shoot us an email at: founders@comealive.io for some free sponsored licenses!

**Like what you see?**

Why not start a 30-day trial of Alive? Download Alive right from the [Visual Studio Gallery](https://visualstudiogallery.msdn.microsoft.com/4af8eb1a-c64f-4da8-9bf0-6835cf3e95c8).

Follow us on Twitter: [@CodeConnectHQ](https://twitter.com/codeconnecthq)


text:
package mesosphere.marathon.upgrade

import akka.actor.{ Actor, ActorLogging }
import akka.event.EventStream
import mesosphere.marathon.SchedulerActions
import mesosphere.marathon.core.launchqueue.LaunchQueue
import mesosphere.marathon.core.task.tracker.TaskTracker
import mesosphere.marathon.event.{ HealthStatusChanged, MarathonHealthCheckEvent, MesosStatusUpdateEvent }
import mesosphere.marathon.state.AppDefinition
import org.apache.mesos.SchedulerDriver

import scala.concurrent.duration._

trait StartingBehavior { this: Actor with ActorLogging =>
  import context.dispatcher
  import mesosphere.marathon.upgrade.StartingBehavior._

  def eventBus: EventStream
  def scaleTo: Int
  def nrToStart: Int
  def taskQueue: LaunchQueue
  def driver: SchedulerDriver
  def scheduler: SchedulerActions
  def taskTracker: TaskTracker

  val app: AppDefinition
  val Version = app.version
  // FIXME: Don't use a string here!
  val VersionString = app.version.toString
  var atLeastOnceHealthyTasks = Set.empty[String]
  var startedRunningTasks = Set.empty[String]
  val AppId = app.id
  val withHealthChecks: Boolean = app.healthChecks.nonEmpty

  def initializeStart(): Unit

  final override def preStart(): Unit = {
    if (withHealthChecks) {
      eventBus.subscribe(self, classOf[MarathonHealthCheckEvent])
    }
    else {
      eventBus.subscribe(self, classOf[MesosStatusUpdateEvent])
    }

    initializeStart()
    checkFinished()

    context.system.scheduler.scheduleOnce(5.seconds, self, Sync)
  }

  final override def receive: Receive = {
    val behavior =
      if (withHealthChecks) checkForHealthy
      else checkForRunning
    behavior orElse commonBehavior: PartialFunction[Any, Unit] // type annotation makes Intellij happy
  }

  final def checkForHealthy: Receive = {
    case HealthStatusChanged(AppId, taskId, Version, true, _, _) if !atLeastOnceHealthyTasks(taskId.idString) =>
      atLeastOnceHealthyTasks += taskId.idString
      log.info(s"$taskId is now healthy")
      checkFinished()
  }

  final def checkForRunning: Receive = {
    case MesosStatusUpdateEvent(_, taskId, "TASK_RUNNING", _, app.`id`, _, _, _, VersionString, _, _) if !startedRunningTasks(taskId.idString) => // scalastyle:off line.size.limit
      startedRunningTasks += taskId.idString
      log.info(s"New task $taskId now running during app ${app.id.toString} scaling, " +
        s"${nrToStart - startedRunningTasks.size} more to go")
      checkFinished()
  }

  def commonBehavior: Receive = {
    case MesosStatusUpdateEvent(_, taskId, StartErrorState(_), _, app.`id`, _, _, _, VersionString, _, _) => // scalastyle:off line.size.limit
      log.warning(s"New task [$taskId] failed during app ${app.id.toString} scaling, queueing another task")
      startedRunningTasks -= taskId.idString
      taskQueue.add(app)

    case Sync =>
      val actualSize = taskQueue.get(app.id).map(_.finalTaskCount).getOrElse(taskTracker.countLaunchedAppTasksSync(app.id))
      val tasksToStartNow = Math.max(scaleTo - actualSize, 0)
      if (tasksToStartNow > 0) {
        log.info(s"Reconciling tasks during app ${app.id.toString} scaling: queuing $tasksToStartNow new tasks")
        taskQueue.add(app, tasksToStartNow)
      }
      context.system.scheduler.scheduleOnce(5.seconds, self, Sync)
  }

  def checkFinished(): Unit = {
    val started =
      if (withHealthChecks) atLeastOnceHealthyTasks.size
      else startedRunningTasks.size
    if (started == nrToStart) {
      success()
    }
  }

  def success(): Unit
}

object StartingBehavior {
  case object Sync
}

private object StartErrorState {
  def unapply(state: String): Option[String] = state match {
    case "TASK_ERROR" | "TASK_FAILED" | "TASK_KILLED" | "TASK_LOST" => Some(state)
    case _ => None
  }
}


text:
"""Fichier contenant le paramètre 'editer' de la commande 'versions'."""

from primaires.interpreteur.masque.parametre import Parametre

class PrmEditer(Parametre):

    """Commande 'versions editer'.

    """

    def __init__(self):
        """Constructeur du paramètre"""
        Parametre.__init__(self, "editer", "edit")
        self.groupe = "administrateur"
        self.schema = "<nombre> <message>"
        self.aide_courte = "édite une modification"
        self.aide_longue = \
            "Cette sous-commande prend en paramètre l'id d'une modification " \
            "et un message, et remplace le contenu de la modification en " \
            "question par le message précisé."

    def interpreter(self, personnage, dic_masques):
        """Interprétation du paramètre"""
        id = dic_masques["nombre"].nombre
        modif = dic_masques["message"].message
        versions = type(self).importeur.information.versions

        if id > len(versions):
            personnage << "|err|Aucune modification ne correspond à l'id " \
                    "spécifié.|ff|"
        else:
            id -= 1
            versions[id] = modif
            personnage << "|att|La modification a bien été éditée.|ff|"


text:
package router

import play.api.mvc._
import javax.inject.Inject

class InstanceController @Inject()(c: ControllerComponents) extends AbstractController(c) {
  var invoked = 0

  def index = Action {
    invoked += 1
    Ok(invoked.toString)
  }
}


text:
from setuptools import setup

setup(
    name='ardbeg',
    version='0.0.1',
    author='Jon McClure',
    author_email='jmcclure@dallasnews.com',
    packages=['ardbeg', 'ardbeg.test'],
    entry_points={
        'console_scripts': [
            'ardbeg = ardbeg.cli:start',
        ],
    },
    url='https://github.com/DallasMorningNews/ardbeg',
    license='LICENSE.txt',
    description='Static site generator based on Jinja2.',
    long_description=open('README.txt').read(),
    install_requires=[
        "Jinja2 >= 2.7.3",
        "docopt",
        "easywatch",
        "python-tablefu",
        "boto",
        "libsass >= 0.5.0",
    ],
    classifiers=[
        'Environment :: Web Environment',
        'License :: OSI Approved :: BSD License', # example license
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
)


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import <Foundation/Foundation.h>
#import "MOZUClient.h"
#import "MOZUFulfillmentAction.h"
#import "MOZUOrder.h"

@interface MOZUFulfillmentActionClient : NSObject

//
#pragma mark -
#pragma mark Get Operations
#pragma mark -
//

//
#pragma mark -
#pragma mark Post Operations
#pragma mark -
//

/**
Sets the fulfillment action to "Ship" or "PickUp". To ship an order or prepare it for in-store pickup, the order must have a customer name, the "Open" or "OpenAndProcessing" status. To ship the order, it must also have the full shipping address and shipping method. Shipping all packages or picking up all pickups for an order will complete a paid order.
@param body Properties of an action to perform when fulfilling an item in an order, whether through in-store pickup or direct shipping.
@param orderId Unique identifier of the order.
@param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
*/

+ (MOZUClient *)clientForPerformFulfillmentActionOperationWithBody:(MOZUFulfillmentAction *)body orderId:(NSString *)orderId responseFields:(NSString *)responseFields;

/**
orders-fulfillment Post ResendPackageFulfillmentEmail description DOCUMENT_HERE
@param body Properties of an action to perform when fulfilling an item in an order, whether through in-store pickup or direct shipping.
@param orderId Unique identifier of the order.
@param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
*/

+ (MOZUClient *)clientForResendPackageFulfillmentEmailOperationWithBody:(MOZUFulfillmentAction *)body orderId:(NSString *)orderId responseFields:(NSString *)responseFields;

//
#pragma mark -
#pragma mark Put Operations
#pragma mark -
//

//
#pragma mark -
#pragma mark Delete Operations
#pragma mark -
//

@end


text:
<LinearLayout
    android:paddingTop="@dimen/padding_custom_10dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:background="@drawable/card_drawable"
    android:elevation="2dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="10dp"
    android:orientation="horizontal">
    <com.project.quiz.customviews.TextViewRegularFont
        android:id="@+id/team_number_text"
        android:layout_weight="1"
        android:textSize="50sp"
        android:gravity="center"
        android:textColor="@color/colorPrimaryLight"
        android:text="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
    <LinearLayout
        android:layout_marginLeft="@dimen/padding_custom_10dp"
        android:gravity="center"
        android:padding="10dp"
        android:orientation="horizontal"
        android:layout_weight="5"
        android:layout_width="0dp"
        android:layout_height="match_parent">

            <com.project.quiz.customviews.TextViewRegularFont
                android:gravity="left"
                android:textSize="@dimen/font_size_xlarge"
                android:textColor="@color/colorPrimaryLight"
                android:text="Changed Score:"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <com.project.quiz.customviews.TextViewRegularFont
                android:layout_marginLeft="5dp"
                android:gravity="center"
                android:id="@+id/inc_score_number"
                android:textSize="@dimen/font_size_xlarge"
                android:textColor="@color/colorAccent"
                android:text="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <com.project.quiz.customviews.TextViewBoldFont
            android:layout_gravity="center"
            android:id="@+id/current_score_number"
            android:gravity="center"
            android:layout_weight="2.7"
            android:textSize="40sp"
            android:textColor="@color/colorPrimaryLighter"
            android:text="090"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    </LinearLayout>


text:
package com.intellij.psi.impl;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.JavaClassSupers;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Set;

public class InheritanceImplUtil {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.InheritanceImplUtil");

  public static boolean isInheritor(@NotNull final PsiClass candidateClass, @NotNull PsiClass baseClass, final boolean checkDeep) {
    if (baseClass instanceof PsiAnonymousClass || baseClass.getManager().areElementsEquivalent(baseClass, candidateClass)) return false;
    if (!checkDeep) {
      return isInheritor(candidateClass.getManager(), candidateClass, baseClass, false, null);
    }

    GlobalSearchScope scope = candidateClass.getResolveScope();
    return JavaClassSupers.getInstance().getSuperClassSubstitutor(baseClass, candidateClass, scope, PsiSubstitutor.EMPTY) != null;
  }

  public static boolean hasObjectQualifiedName(@NotNull PsiClass candidateClass) {
    if (!CommonClassNames.JAVA_LANG_OBJECT_SHORT.equals(candidateClass.getName())) {
      return false;
    }
    PsiElement parent = candidateClass.getParent();
    return parent instanceof PsiJavaFile && CommonClassNames.DEFAULT_PACKAGE.equals(((PsiJavaFile)parent).getPackageName());
  }

  private static boolean isInheritor(@NotNull PsiManager manager,
                                     @NotNull PsiClass candidateClass,
                                     @NotNull PsiClass baseClass,
                                     boolean checkDeep,
                                     @Nullable Set<PsiClass> checkedClasses) {
    if (candidateClass instanceof PsiAnonymousClass) {
      final PsiClass baseCandidateClass = ((PsiAnonymousClass)candidateClass).getBaseClassType().resolve();
      return baseCandidateClass != null && InheritanceUtil.isInheritorOrSelf(baseCandidateClass, baseClass, checkDeep);
    }
    /* //TODO fix classhashprovider so it doesn't use class qnames only
    final ClassHashProvider provider = getHashProvider((PsiManagerImpl) manager);
    if (checkDeep && provider != null) {
      try {
        return provider.isInheritor(baseClass, candidateClass);
      }
      catch (ClassHashProvider.OutOfRangeException e) {
      }
    }
    */
    if(checkDeep && LOG.isDebugEnabled()){
      LOG.debug("Using uncached version for " + candidateClass.getQualifiedName() + " and " + baseClass);
    }

    if (hasObjectQualifiedName(baseClass)) {
      PsiClass objectClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(CommonClassNames.JAVA_LANG_OBJECT, candidateClass.getResolveScope());
      if (manager.areElementsEquivalent(baseClass, objectClass)) {
        if (manager.areElementsEquivalent(candidateClass, objectClass)) return false;
        if (checkDeep || candidateClass.isInterface()) return true;
        return manager.areElementsEquivalent(candidateClass.getSuperClass(), objectClass);
      }
    }

    if (!checkDeep) {
      final boolean cInt = candidateClass.isInterface();
      final boolean bInt = baseClass.isInterface();

      if (candidateClass instanceof PsiCompiledElement) {
        String baseQName = baseClass.getQualifiedName();
        if (baseQName == null) return false;

        GlobalSearchScope scope = candidateClass.getResolveScope();
        if (cInt == bInt && checkReferenceListWithQualifiedNames(baseQName, candidateClass.getExtendsList(), manager, scope)) return true;
        return bInt && !cInt && checkReferenceListWithQualifiedNames(baseQName, candidateClass.getImplementsList(), manager, scope);
      }
      String baseName = baseClass.getName();
      if (cInt == bInt) {
        for (PsiClassType type : candidateClass.getExtendsListTypes()) {
          if (Comparing.equal(type.getClassName(), baseName)) {
            if (manager.areElementsEquivalent(baseClass, type.resolve())) {
              return true;
            }
          }
        }
      }
      else if (!cInt) {
        for (PsiClassType type : candidateClass.getImplementsListTypes()) {
          if (Comparing.equal(type.getClassName(), baseName)) {
            if (manager.areElementsEquivalent(baseClass, type.resolve())) {
              return true;
            }
          }
        }
      }

      return false;
    }

    return isInheritorWithoutCaching(manager, candidateClass, baseClass, checkedClasses);
  }

  private static boolean checkReferenceListWithQualifiedNames(final String baseQName, final PsiReferenceList extList, final PsiManager manager,
                                                              final GlobalSearchScope scope) {
    if (extList != null) {
      final PsiJavaCodeReferenceElement[] refs = extList.getReferenceElements();
      for (PsiJavaCodeReferenceElement ref : refs) {
        if (Comparing.equal(PsiNameHelper.getQualifiedClassName(ref.getQualifiedName(), false), baseQName) && JavaPsiFacade
          .getInstance(manager.getProject()).findClass(baseQName, scope) != null)
          return true;
      }
    }
    return false;
  }

  private static boolean isInheritorWithoutCaching(@NotNull PsiManager manager,
                                                   @NotNull PsiClass aClass,
                                                   @NotNull PsiClass baseClass,
                                                   @Nullable Set<PsiClass> checkedClasses) {
    if (manager.areElementsEquivalent(aClass, baseClass)) return false;

    if (aClass.isInterface() && !baseClass.isInterface()) {
      return false;
    }

    if (checkedClasses == null) {
      checkedClasses = new THashSet<PsiClass>();
    }
    checkedClasses.add(aClass);

    return checkInheritor(manager, aClass.getExtendsListTypes(), baseClass, checkedClasses) ||
           checkInheritor(manager, aClass.getImplementsListTypes(), baseClass, checkedClasses);
  }

  private static boolean checkInheritor(@NotNull PsiManager manager,
                                        @NotNull PsiClassType[] supers,
                                        @NotNull PsiClass baseClass,
                                        @NotNull Set<PsiClass> checkedClasses) {
    for (PsiClassType aSuper : supers) {
      PsiClass aClass = aSuper.resolve();
      if (aClass != null && checkInheritor(manager, aClass, baseClass, checkedClasses)) {
        return true;
      }
    }
    return false;
  }

  private static boolean checkInheritor(@NotNull PsiManager manager,
                                        @NotNull PsiClass aClass,
                                        @NotNull PsiClass baseClass,
                                        @NotNull Set<PsiClass> checkedClasses) {
    ProgressIndicatorProvider.checkCanceled();
    if (manager.areElementsEquivalent(baseClass, aClass)) {
      return true;
    }
    if (checkedClasses.contains(aClass)) { // to prevent infinite recursion
      return false;
    }
    return isInheritor(manager, aClass, baseClass, true, checkedClasses);
  }

  public static boolean isInheritorDeep(@NotNull PsiClass candidateClass, @NotNull PsiClass baseClass, @Nullable final PsiClass classToByPass) {
    if (baseClass instanceof PsiAnonymousClass) {
      return false;
    }

    Set<PsiClass> checkedClasses = null;
    if (classToByPass != null) {
      checkedClasses = new THashSet<PsiClass>();
      checkedClasses.add(classToByPass);
    }
    return isInheritor(candidateClass.getManager(), candidateClass, baseClass, true, checkedClasses);
  }
}


text:
// # Setup Test
// Test that setup works correctly

/*global CasperTest, casper, email */

CasperTest.begin('Ghost setup fails properly', 5, function suite(test) {
    casper.thenOpenAndWaitForPageLoad('setup', function then() {
        test.assertUrlMatch(/ghost\/setup\/$/, 'Landed on the correct URL');
    });

    casper.then(function setupWithShortPassword() {
        casper.fillAndAdd('#setup', {email: email, password: 'test'});
    });

    // should now throw a short password error
    casper.waitForSelector('.notification-error', function onSuccess() {
        test.assert(true, 'Got error notification');
        test.assertSelectorDoesntHaveText('.notification-error', '[object Object]');
    }, function onTimeout() {
        test.assert(false, 'No error notification :(');
    });

    casper.then(function setupWithLongPassword() {
        casper.fillAndAdd('#setup', {email: email, password: 'testing1234'});
    });

    // should now throw a 1 user only error
    casper.waitForSelector('.notification-error', function onSuccess() {
        test.assert(true, 'Got error notification');
        test.assertSelectorDoesntHaveText('.notification-error', '[object Object]');
    }, function onTimeout() {
        test.assert(false, 'No error notification :(');
    });
}, true);

CasperTest.begin('Authenticated user is redirected', 8, function suite(test) {
    casper.thenOpenAndWaitForPageLoad('signin', function testTitleAndUrl() {
        test.assertTitle('Ghost Admin', 'Ghost admin has no title');
        test.assertUrlMatch(/ghost\/signin\/$/, 'Landed on the correct URL');
    });

    casper.waitForOpaque('.login-box', function then() {
        this.fillAndSave('#login', user);
    });

    casper.wait(2000);

    casper.waitForResource(/posts/, function testForDashboard() {
        test.assertUrlMatch(/ghost\/\d+\/$/, 'Landed on the correct URL');
        test.assertExists('#global-header', 'Global admin header is present');
        test.assertExists('.manage', 'We\'re now on content');
    }, function onTimeOut() {
        test.fail('Failed to signin');
    });

    casper.thenOpenAndWaitForPageLoad('setup-authenticated', function testTitleAndUrl() {
        test.assertUrlMatch(/ghost\/\d+\/$/, 'Landed on the correct URL');
        test.assertExists('#global-header', 'Global admin header is present');
        test.assertExists('.manage', 'We\'re now on content');
    }, function onTimeOut() {
        test.fail('Failed to redirect');
    });
}, true);


text:
module BelongsToCompany
  extend ActiveSupport::Concern

  included do
    belongs_to :company

    validates :company_id, :presence => true
  end

end


text:
Title: {{ list.myTitle }}

    {{ item.quantity }} of {{ item.name }}
    <button ng-click="list.badRemove($index);">Bad Remove Item</button>
    <button ng-click="list.onRemove({index: $index});">Remove Item</button>

WARNING! WARNING! COOKIES DETECTED!