text:
using System;
using System.Xml.Serialization;

namespace HoloXPLOR.Data.DataForge
{
    [XmlRoot(ElementName = "CommunicationConfig")]
    public partial class CommunicationConfig
    {
        [XmlAttribute(AttributeName = "name")]
        public String Name { get; set; }

        [XmlArray(ElementName = "communications")]
        [XmlArrayItem(Type = typeof(CommunicationEntry))]
        public CommunicationEntry[] Communications { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
var check = require('validator').check,
  sanitize = require('validator').sanitize;

var crypto = require('crypto');
var config = require('../config').config;

var User = require('../proxy').User;
var Message = require('../proxy').Message;
var mail = require('../services/mail');

//sign up
exports.showSignup = function (req, res) {
  res.render('sign/signup');
};

exports.signup = function (req, res, next) {
  var name = sanitize(req.body.name).trim();
  name = sanitize(name).xss();
  var loginname = name.toLowerCase();
  var pass = sanitize(req.body.pass).trim();
  pass = sanitize(pass).xss();
  var email = sanitize(req.body.email).trim();
  email = email.toLowerCase();
  email = sanitize(email).xss();
  var re_pass = sanitize(req.body.re_pass).trim();
  re_pass = sanitize(re_pass).xss();

  if (name === '' || pass === '' || re_pass === '' || email === '') {
    res.render('sign/signup', {error: '信息不完整。', name: name, email: email});
    return;
  }

  if (name.length < 4) {
    res.render('sign/signup', {error: '用户名至少需要4个字符。', name: name, email: email});
    return;
  }

  try {
    check(name, '用户名只能使用0-9,a-z,A-Z。').isAlphanumeric();
  } catch (e) {
    res.render('sign/signup', {error: e.message, name: name, email: email});
    return;
  }

  if (pass !== re_pass) {
    res.render('sign/signup', {error: '两次密码输入不一致。', name: name, email: email});
    return;
  }

  try {
    check(email, '不正确的电子邮箱。').isEmail();
  } catch (e) {
    res.render('sign/signup', {error: e.message, name: name, email: email});
    return;
  }

  User.getUsersByQuery({'$or': [{'loginname': loginname}, {'email': email}]}, {}, function (err, users) {
    if (err) {
      return next(err);
    }
    if (users.length > 0) {
      res.render('sign/signup', {error: '用户名或邮箱已被使用。', name: name, email: email});
      return;
    }

    // md5 the pass
    pass = md5(pass);
    // create gavatar
    var avatar_url = 'http://www.tianxiawuai.com/' + md5(email.toLowerCase()) + '?size=48';

    User.newAndSave(name, loginname, pass, email, avatar_url, false, function (err) {
      if (err) {
        return next(err);
      }
      // 发送激活邮件
      mail.sendActiveMail(email, md5(email + config.session_secret), name);
      res.render('sign/signup', {
        success: '欢迎加入 ' + config.name + '!我们已给您的注册邮箱发送了一封邮件,请点击里面的链接来激活您的帐号。'
      });
    });
  });
};

/**
 * Show user login page.
 *
 * @param  {HttpRequest} req
 * @param  {HttpResponse} res
 */
exports.showLogin = function (req, res) {
  req.session._loginReferer = req.headers.referer;
  res.render('sign/signin');
};

/**
 * define some page when login just jump to the home page
 * @type {Array}
 */
var notJump = [
  '/active_account', //active page
  '/reset_pass',     //reset password page, avoid to reset twice
  '/signup',         //regist page
  '/search_pass'    //serch pass page
];

/**
 * Handle user login.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */
exports.login = function (req, res, next) {
  var loginname = sanitize(req.body.name).trim().toLowerCase();
  var pass = sanitize(req.body.pass).trim();

  if (!loginname || !pass) {
    return res.render('sign/signin', { error: '信息不完整。' });
  }

  User.getUserByLoginName(loginname, function (err, user) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return res.render('sign/signin', { error: '这个用户不存在。' });
    }
    pass = md5(pass);
    if (pass !== user.pass) {
      return res.render('sign/signin', { error: '密码错误。' });
    }
    if (!user.active) {
      // 从新发送激活邮件
      mail.sendActiveMail(user.email, md5(user.email + config.session_secret), user.name);
      return res.render('sign/signin', { error: '此帐号还没有被激活,激活链接已发送到 ' + user.email + ' 邮箱,请查收。' });
    }
    // store session cookie
    gen_session(user, res);
    //check at some page just jump to home page
    var refer = req.session._loginReferer || 'home';
    for (var i = 0, len = notJump.length; i !== len; ++i) {
      if (refer.indexOf(notJump[i]) >= 0) {
        refer = 'home';
        break;
      }
    }
    res.redirect(refer);
  });
};

// sign out
exports.signout = function (req, res, next) {
  req.session.destroy();
  res.clearCookie(config.auth_cookie_name, { path: '/' });
  res.redirect(req.headers.referer || 'home');
};

exports.active_account = function (req, res, next) {
  var key = req.query.key;
  var name = req.query.name;

  User.getUserByName(name, function (err, user) {
    if (err) {
      return next(err);
    }
    if (!user || md5(user.email + config.session_secret) !== key) {
      return res.render('notify/notify', {error: '信息有误,帐号无法被激活。'});
    }
    if (user.active) {
      return res.render('notify/notify', {error: '帐号已经是激活状态。'});
    }
    user.active = true;
    user.save(function (err) {
      if (err) {
        return next(err);
      }
      res.render('notify/notify', {success: '帐号已被激活,请登录'});
    });
  });
};

exports.showSearchPass = function (req, res) {
  res.render('sign/search_pass');
};

exports.updateSearchPass = function (req, res, next) {
  var email = req.body.email;
  email = email.toLowerCase();

  try {
    check(email, '不正确的电子邮箱。').isEmail();
  } catch (e) {
    res.render('sign/search_pass', {error: e.message, email: email});
    return;
  }

  // 动态生成retrive_key和timestamp到users collection,之后重置密码进行验证
  var retrieveKey = randomString(15);
  var retrieveTime = new Date().getTime();
  User.getUserByMail(email, function (err, user) {
    if (!user) {
      res.render('sign/search_pass', {error: '没有这个电子邮箱。', email: email});
      return;
    }
    user.retrieve_key = retrieveKey;
    user.retrieve_time = retrieveTime;
    user.save(function (err) {
      if (err) {
        return next(err);
      }
      // 发送重置密码邮件
      mail.sendResetPassMail(email, retrieveKey, user.name);
      res.render('notify/notify', {success: '我们已给您填写的电子邮箱发送了一封邮件,请在24小时内点击里面的链接来重置密码。'});
    });
  });
};

/**
 * reset password
 * 'get' to show the page, 'post' to reset password
 * after reset password, retrieve_key&time will be destroy
 * @param  {http.req}   req
 * @param  {http.res}   res
 * @param  {Function} next
 */
exports.reset_pass = function (req, res, next) {
  var key = req.query.key;
  var name = req.query.name;
  User.getUserByQuery(name, key, function (err, user) {
    if (!user) {
      return res.render('notify/notify', {error: '信息有误,密码无法重置。'});
    }
    var now = new Date().getTime();
    var oneDay = 1000 * 60 * 60 * 24;
    if (!user.retrieve_time || now - user.retrieve_time > oneDay) {
      return res.render('notify/notify', {error : '该链接已过期,请重新申请。'});
    }
    return res.render('sign/reset', {name : name, key : key});
  });
};

exports.update_pass = function (req, res, next) {
  var psw = req.body.psw || '';
  var repsw = req.body.repsw || '';
  var key = req.body.key || '';
  var name = req.body.name || '';
  if (psw !== repsw) {
    return res.render('sign/reset', {name : name, key : key, error : '两次密码输入不一致。'});
  }
  User.getUserByQuery(name, key, function (err, user) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return res.render('notify/notify', {error : '错误的激活链接'});
    }
    user.pass = md5(psw);
    user.retrieve_key = null;
    user.retrieve_time = null;
    user.active = true; // 用户激活
    user.save(function (err) {
      if (err) {
        return next(err);
      }
      return res.render('notify/notify', {success: '你的密码已重置。'});
    });
  });
};

function getAvatarURL(user) {
  if (user.avatar_url) {
    return user.avatar_url;
  }
  var avatar_url = user.profile_image_url || user.avatar;
  if (!avatar_url) {
    avatar_url = config.site_static_host + '/public/images/user_icon&48.png';
  }
  return avatar_url;
}

// auth_user middleware
exports.auth_user = function (req, res, next) {
  if (req.session.user) {
    if (config.admins.hasOwnProperty(req.session.user.name)) {
      req.session.user.is_admin = true;
    }
    Message.getMessagesCount(req.session.user._id, function (err, count) {
      if (err) {
        return next(err);
      }
      req.session.user.messages_count = count;
      if (!req.session.user.avatar_url) {
        req.session.user.avatar_url = getAvatarURL(req.session.user);
      }
      res.local('current_user', req.session.user);
      return next();
    });
  } else {
    var cookie = req.cookies[config.auth_cookie_name];
    if (!cookie) {
      return next();
    }

    var auth_token = decrypt(cookie, config.session_secret);
    var auth = auth_token.split('\t');
    var user_id = auth[0];
    User.getUserById(user_id, function (err, user) {
      if (err) {
        return next(err);
      }
      if (user) {
        if (config.admins.hasOwnProperty(user.name)) {
          user.is_admin = true;
        }
        Message.getMessagesCount(user._id, function (err, count) {
          if (err) {
            return next(err);
          }
          user.messages_count = count;
          req.session.user = user;
          res.local('current_user', req.session.user);
          return next();
        });
      } else {
        return next();
      }
    });
  }
};

// private
function gen_session(user, res) {
  var auth_token = encrypt(user._id + '\t' + user.name + '\t' + user.pass + '\t' + user.email, config.session_secret);
  res.cookie(config.auth_cookie_name, auth_token, {path: '/', maxAge: 1000 * 60 * 60 * 24 * 30}); //cookie 有效期30天
}

exports.gen_session = gen_session;

function encrypt(str, secret) {
  var cipher = crypto.createCipher('aes192', secret);
  var enc = cipher.update(str, 'utf8', 'hex');
  enc += cipher.final('hex');
  return enc;
}

function decrypt(str, secret) {
  var decipher = crypto.createDecipher('aes192', secret);
  var dec = decipher.update(str, 'hex', 'utf8');
  dec += decipher.final('utf8');
  return dec;
}

function md5(str) {
  var md5sum = crypto.createHash('md5');
  md5sum.update(str);
  str = md5sum.digest('hex');
  return str;
}

function randomString(size) {
  size = size || 6;
  var code_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var max_num = code_string.length + 1;
  var new_pass = '';
  while (size > 0) {
    new_pass += code_string.charAt(Math.floor(Math.random() * max_num));
    size--;
  }
  return new_pass;
}


text:
<?php

namespace Hubzero\Component;

/**
 * Base admin controller for components to extend.
 */
class AdminController extends SiteController
{
	/**
	 * Cancels a task and redirects to default view
	 *
	 * @return  void
	 */
	public function cancelTask()
	{
		// Set the redirect
		\App::redirect(
			\Route::url('index.php?option=' . $this->_option . ($this->_controller ? '&controller=' . $this->_controller : ''), false)
		);
	}
}


text:
<?php

namespace Kuborgh\DataTransferBundle\Command;

use Kuborgh\DataTransferBundle\Traits\DatabaseConnectionTrait;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;

/**
 * Command to export (dump) the current database. This is called on the remote side of the fetch command
 */
class ExportCommand extends ContainerAwareCommand
{
    use DatabaseConnectionTrait;
    const OPT_FILE = 'file';

    /**
     * Configure command
     */
    protected function configure()
    {
        $this->setName('data-transfer:export');
        $this->setDescription('Dump SQL database to stdout');
        $this->addOption(self::OPT_FILE, null, InputOption::VALUE_NONE, 'Dump database to file, not to stdout');
    }

    /**
     * Execute the command
     *
     * @param \Symfony\Component\Console\Input\InputInterface   $input  Input
     * @param \Symfony\Component\Console\Output\OutputInterface $output Output
     *
     * @throws \Exception
     * @return void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Fetch db connection data
        $dbParams = $this->getDatabaseParameter();

        // Prepare command line parameters
        $parameters = Array();
        $parameters[] = escapeshellarg($dbParams['dbName']);
        $parameters[] = sprintf('--user=%s', escapeshellarg($dbParams['dbUser']));
        $parameters[] = sprintf('--password=%s', escapeshellarg($dbParams['dbPass']));
        $parameters[] = sprintf('--host=%s', escapeshellarg($dbParams['dbHost']));

        // Add additional arguments
        if (isset($dbParams['databaseExportArguments'])) {
            foreach ($dbParams['databaseExportArguments'] as $argument) {
                $parameters[] = $argument;
            }
        }

        // Write to file instead of stdout
        $toFile = $input->getOption(self::OPT_FILE);
        $filename = null;
        if ($toFile) {
            $folder = $this->getContainer()->getParameter('kernel.cache_dir');
            $filename = sprintf('%s/db-dump-%s.sql', $folder, time());
            $parameters[] = escapeshellarg('-q');
            $parameters[] = escapeshellarg(sprintf('--result-file=%s', $filename));

            // cleanup old dumps to make some space for new ones
            $this->cleanupOldDumps();
        }

        // call mysqldump
        $cmd = sprintf('mysqldump %s 2>&1', implode(' ', $parameters));

        // Execute command
        $process = new Process($cmd);
        $process->setTimeout(null);

        // Output data directly to not get a timeout
        $process->run(function ($type, $buffer) use ($output, $toFile) {
            // Output directly to console
            if (!$toFile && $type == Process::OUT) {
                $output->write($buffer, false, Output::OUTPUT_RAW);
            }
        });

        if (!$process->isSuccessful()) {
            throw new \Exception(sprintf("Error dumping database:\n%s", $process->getOutput()));
        }

        // Print hints to the file
        if ($toFile) {
            $data = Array();
            $data['filename'] = $filename;
            $data['basename'] = basename($filename);
            $data['size'] = filesize($filename);
            $output->write(json_encode($data), false, Output::OUTPUT_RAW);
        }
    }

    /**
     * Cleanup db dump from cache folder, that are older than 24h
     */
    protected function cleanupOldDumps()
    {
        // Define "old" as 24h in the past
        $old = time() - 24 * 60 * 60;

        $folder = $this->getContainer()->getParameter('kernel.cache_dir');
        foreach (glob($folder.'/db-dump-*.sql') as $dump) {
            if (!preg_match('/db\-dump\-(\d*)\.sql$/', $dump, $matches)) {
                continue;
            }
            if ($matches[1] < $old) {
                $process = new Process(sprintf('rm %s', $dump));
                $process->run();
            }
        }
    }
}


text:
package org.elasticsearch.xpack.sql.expression.function.scalar.geo;

import org.elasticsearch.xpack.ql.expression.Expression;
import org.elasticsearch.xpack.ql.expression.Expressions;
import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction;
import org.elasticsearch.xpack.ql.expression.gen.processor.Processor;
import org.elasticsearch.xpack.ql.expression.gen.script.Scripts;
import org.elasticsearch.xpack.ql.tree.NodeInfo;
import org.elasticsearch.xpack.ql.tree.Source;
import org.elasticsearch.xpack.ql.type.DataType;
import org.elasticsearch.xpack.ql.type.DataTypes;
import org.elasticsearch.xpack.sql.type.SqlDataTypes;

import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isString;

/**
 * Constructs geometric objects from their WTK representations
 */
public class StWkttosql extends UnaryScalarFunction {

    public StWkttosql(Source source, Expression field) {
        super(source, field);
    }

    @Override
    protected StWkttosql replaceChild(Expression newChild) {
        return new StWkttosql(source(), newChild);
    }

    @Override
    protected TypeResolution resolveType() {
        if (DataTypes.isString(field().dataType())) {
            return TypeResolution.TYPE_RESOLVED;
        }
        return isString(field(), sourceText(), Expressions.ParamOrdinal.DEFAULT);
    }

    @Override
    protected Processor makeProcessor() {
        return StWkttosqlProcessor.INSTANCE;
    }

    @Override
    public DataType dataType() {
        return SqlDataTypes.GEO_SHAPE;
    }

    @Override
    protected NodeInfo<StWkttosql> info() {
        return NodeInfo.create(this, StWkttosql::new, field());
    }

    @Override
    public String processScript(String script) {
        return Scripts.formatTemplate(Scripts.SQL_SCRIPTS + ".stWktToSql(" + script + ")");
    }

    @Override
    public Object fold() {
        return StWkttosqlProcessor.INSTANCE.process(field().fold());
    }

}


text:
/* Reset
----------------------------------------------------------------------------- */

/* stylelint-disable */

html, body,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
address, code, img,
dl, dt, dd, ol, ul, li,
fieldset, form, label,
table, th, td,
article, aside, nav, section, figure, figcaption, footer, header,
audio, video {
  margin: 0;
  padding: 0;
}
blockquote, img, fieldset, form {
  border: 0;
}
a, strong, em, b, i, small, sub, sup, img, label, th, td, audio, video {
  vertical-align: baseline;
}
applet, object, iframe,
abbr, acronym, big, cite,
del, dfn, ins, kbd, q, s, samp,
strike, tt, var, u, center, legend,
caption, tbody, tfoot, thead, tr,
canvas, details, embed,
menu, output, ruby, summary,
time, mark {
  margin: 0;
  padding: 0;
  border: 0;
  vertical-align: baseline;
  font: inherit;
  font-size: 100%;
}
ul, ol {
  list-style: none;
}

/* Border-box FTW
https://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/ */
*,
*:before,
*:after {
  box-sizing: inherit;
}
html {
  overflow-y: scroll;
  box-sizing: border-box;
  text-size-adjust: 100%;
}
a {
  background-color: transparent; /* Remove the gray background color from active links in IE 10. */
  -webkit-text-decoration-skip: none;

  &:hover,
  &:active {
    outline: 0;
  }
}
img {
  vertical-align: middle;
}
strong, b {
  font-weight: bold;
}
em, i {
  font-style: italic;
}
h1, h2, h3, h4, h5, h6 {
  font-weight: bold;
}
table {
  border-spacing: 0;
  border-collapse: collapse;
}
th {
  font-weight: bold;
}
td {
  vertical-align: top;
}
input,
select,
textarea,
button {
  margin: 0;
  vertical-align: middle;
  font-size: 100%;
  font-family: inherit;
}

/**
 * 1. Add the correct box sizing in IE 10-.
 * 2. Remove the padding in IE 10-.
 */
[type="checkbox"],
[type="radio"] {
  box-sizing: border-box; /* 1 */
  padding: 0; /* 2 */
}

/**
 * Show the overflow in IE.
 * 1. Show the overflow in Edge.
 * 2. Show the overflow in Edge, Firefox, and IE.
 */
button,
input, /* 1 */
select { /* 2 */
  overflow: visible;
}

/**
 * Address inconsistent `text-transform` inheritance for `button` and `select`.
 * All other form control elements do not inherit `text-transform` values.
 * Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
 * Correct `select` style inheritance in Firefox.
 */
button,
select {
  text-transform: none;
}

/**
 * 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
 *    controls in Android 4.
 * 2. Correct inability to style clickable `input` types in iOS.
 * 3. Improve usability and consistency of cursor style between image-type
 *    `input` and others.
 */
button,
html [type="button"], /* 1 */
[type="reset"],
[type="submit"] {
  cursor: pointer; /* 3 */
  -webkit-appearance: button; /* 2 */
}

/**
 * Remove the inner border and padding in Firefox.
 */
button::-moz-focus-inner,
input::-moz-focus-inner {
  padding: 0;
  border: 0;
}
/**
 * 1. Remove the default vertical scrollbar in IE.
 */
textarea {
  overflow: auto; /* 1 */
  resize: vertical;
}
svg:not(:root) {
  overflow: hidden; /* Correct overflow not hidden in IE. */
}

/**
 * Correct the odd appearance of search inputs in Chrome and Safari.
 */
[type="search"] {
  -webkit-appearance: textfield;
}

/**
 * Remove the inner padding and cancel buttons in Chrome on OS X and
 * Safari on OS X.
 */
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
}
/* stylelint-enable */

[role="button"],
input[type="submit"],
input[type="reset"],
input[type="button"],
button {
    -webkit-box-sizing: content-box;
       -moz-box-sizing: content-box;
            box-sizing: content-box;
}

/* Reset `button` and button-style `input` default styles */
input[type="submit"],
input[type="reset"],
input[type="button"],
button {
    background: none;
    border: 0;
    color: inherit;
    /* cursor: default; */
    font: inherit;
    line-height: normal;
    overflow: visible;
    padding: 0;
    -webkit-appearance: button; /* for input */
    -webkit-user-select: none; /* for button */
       -moz-user-select: none;
        -ms-user-select: none;
}
input::-moz-focus-inner,
button::-moz-focus-inner {
    border: 0;
    padding: 0;
}

/* Make `a` like a button */
[role="button"] {
    color: inherit;
    cursor: default;
    display: inline-block;
    text-align: center;
    text-decoration: none;
    white-space: pre;
    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
}


text:
import mock
import six

from mistralclient.api.v2 import executions

from heat.common import exception
from heat.common import template_format
from heat.engine.clients.os import mistral as client
from heat.engine import resource
from heat.engine import resources
from heat.engine.resources.openstack.mistral import workflow
from heat.engine.resources import signal_responder
from heat.engine.resources import stack_user
from heat.engine import scheduler
from heat.engine import template
from heat.tests import common
from heat.tests import utils

workflow_template = """
heat_template_version: 2013-05-23
resources:
  workflow:
    type: OS::Mistral::Workflow
    properties:
      type: direct
      tasks:
        - name: hello
          action: std.echo output='Good morning!'
          publish:
            result: <% $.hello %>
"""

workflow_template_with_params = """
heat_template_version: 2013-05-23
resources:
  workflow:
    type: OS::Mistral::Workflow
    properties:
      params: {'test':'param_value'}
      type: direct
      tasks:
        - name: hello
          action: std.echo output='Good morning!'
          publish:
            result: <% $.hello %>
"""
workflow_template_with_params_override = """
heat_template_version: 2013-05-23
resources:
  workflow:
    type: OS::Mistral::Workflow
    properties:
      params: {'test':'param_value_override','test1':'param_value_override_1'}
      type: direct
      tasks:
        - name: hello
          action: std.echo output='Good morning!'
          publish:
            result: <% $.hello %>
"""

workflow_template_full = """
heat_template_version: 2013-05-23
resources:
 create_vm:
   type: OS::Mistral::Workflow
   properties:
     name: create_vm
     type: direct
     input:
       name: create_test_server
       image: 31d8eeaf-686e-4e95-bb27-765014b9f20b
       flavor: 2
     output:
       vm_id: <% $.vm_id %>
     tasks:
       - name: create_server
         action: |
           nova.servers_create name=<% $.name %> image=<% $.image %>
           flavor=<% $.flavor %>
         publish:
           vm_id: <% $.create_server.id %>
         on_success:
           - check_server_exists
       - name: check_server_exists
         action: nova.servers_get server=<% $.vm_id %>
         publish:
           server_exists: True
         on_success:
           - wait_instance
       - name: wait_instance
         action: nova.servers_find id=<% $.vm_id %> status='ACTIVE'
         policies:
           retry:
             delay: 5
             count: 15
"""

workflow_template_bad = """
heat_template_version: 2013-05-23
resources:
  workflow:
    type: OS::Mistral::Workflow
    properties:
      type: direct
      tasks:
        - name: second_task
          action: std.noop
          requires: [first_task]
        - name: first_task
          action: std.noop
"""

workflow_template_bad_reverse = """
heat_template_version: 2013-05-23
resources:
  workflow:
    type: OS::Mistral::Workflow
    properties:
      type: reverse
      tasks:
        - name: second_task
          action: std.noop
          requires: [first_task]
        - name: first_task
          action: std.noop
"""

workflow_template_update_replace = """
heat_template_version: 2013-05-23
resources:
  workflow:
    type: OS::Mistral::Workflow
    properties:
      name: hello_action
      type: direct
      tasks:
        - name: hello
          action: std.echo output='Good evening!'
          publish:
            result: <% $.hello %>
"""

workflow_template_update = """
heat_template_version: 2013-05-23
resources:
  workflow:
    type: OS::Mistral::Workflow
    properties:
      type: direct
      description: just testing workflow resource
      tasks:
        - name: hello
          action: std.echo output='Good evening!'
          publish:
            result: <% $.hello %>
"""

class FakeWorkflow(object):
    def __init__(self, name):
        self.name = name
        self._data = {'workflow': 'info'}

class MistralWorkFlowTestResource(workflow.Workflow):
    @classmethod
    def is_service_available(cls, context):
        return True

class TestMistralWorkflow(common.HeatTestCase):

    def setUp(self):
        super(TestMistralWorkflow, self).setUp()
        resources.initialise()
        utils.setup_dummy_db()
        self.ctx = utils.dummy_context()
        tmpl = template_format.parse(workflow_template)
        self.stack = utils.parse_stack(tmpl, stack_name='test_stack')

        resource_defns = self.stack.t.resource_definitions(self.stack)
        self.rsrc_defn = resource_defns['workflow']

        self.mistral = mock.Mock()
        self.patchobject(MistralWorkFlowTestResource, 'client',
                         return_value=self.mistral)

        self.patches = []
        self.patches.append(mock.patch.object(stack_user.StackUser,
                                              '_create_user'))
        self.patches.append(mock.patch.object(signal_responder.SignalResponder,
                                              '_create_keypair'))
        self.patches.append(mock.patch.object(client,
                                              'mistral_base'))
        self.patches.append(mock.patch.object(client.MistralClientPlugin,
                                              '_create'))
        for patch in self.patches:
            patch.start()

        self.client = client.MistralClientPlugin(self.ctx)

    def tearDown(self):
        super(TestMistralWorkflow, self).tearDown()
        for patch in self.patches:
            patch.stop()

    def _create_resource(self, name, snippet, stack):
        wf = MistralWorkFlowTestResource(name, snippet, stack)
        self.mistral.workflows.create.return_value = [
            FakeWorkflow('test_stack-workflow-b5fiekfci3yc')]
        scheduler.TaskRunner(wf.create)()
        return wf

    def test_create(self):
        wf = self._create_resource('workflow', self.rsrc_defn, self.stack)
        expected_state = (wf.CREATE, wf.COMPLETE)
        self.assertEqual(expected_state, wf.state)
        self.assertEqual('test_stack-workflow-b5fiekfci3yc', wf.resource_id)

    def test_create_with_name(self):
        tmpl = template_format.parse(workflow_template_full)
        stack = utils.parse_stack(tmpl)

        rsrc_defns = stack.t.resource_definitions(stack)['create_vm']

        wf = MistralWorkFlowTestResource('create_vm', rsrc_defns, stack)
        self.mistral.workflows.create.return_value = [
            FakeWorkflow('create_vm')]
        scheduler.TaskRunner(wf.create)()

        expected_state = (wf.CREATE, wf.COMPLETE)
        self.assertEqual(expected_state, wf.state)
        self.assertEqual('create_vm', wf.resource_id)

    def test_attributes(self):
        wf = self._create_resource('workflow', self.rsrc_defn, self.stack)
        self.mistral.workflows.get.return_value = \
            FakeWorkflow('test_stack-workflow-b5fiekfci3yc')
        self.assertEqual({'name': 'test_stack-workflow-b5fiekfci3yc',
                          'input': None}, wf.FnGetAtt('data'))
        self.assertEqual([], wf.FnGetAtt('executions'))
        self.assertEqual({'workflow': 'info'}, wf.FnGetAtt('show'))

    def test_direct_workflow_validation_error(self):
        error_msg = ("Mistral resource validation error: "
                     "workflow.properties.tasks.second_task.requires: "
                     "task second_task contains property 'requires' "
                     "in case of direct workflow. Only reverse workflows "
                     "can contain property 'requires'.")
        self._test_validation_failed(workflow_template_bad, error_msg)

    def test_wrong_params_using(self):
        error_msg = ("Mistral resource validation error: "
                     "workflow.properties.params: 'task_name' is not assigned "
                     "in 'params' in case of reverse type workflow.")
        self._test_validation_failed(workflow_template_bad_reverse, error_msg)

    def _test_validation_failed(self, templatem, error_msg):
        tmpl = template_format.parse(templatem)
        stack = utils.parse_stack(tmpl)

        rsrc_defns = stack.t.resource_definitions(stack)['workflow']

        wf = MistralWorkFlowTestResource('workflow', rsrc_defns, stack)

        exc = self.assertRaises(exception.StackValidationFailed,
                                wf.validate)
        self.assertEqual(error_msg, six.text_type(exc))

    def test_create_wrong_definition(self):
        tmpl = template_format.parse(workflow_template)
        stack = utils.parse_stack(tmpl)

        rsrc_defns = stack.t.resource_definitions(stack)['workflow']

        wf = MistralWorkFlowTestResource('workflow', rsrc_defns, stack)

        self.mistral.workflows.create.side_effect = Exception('boom!')

        exc = self.assertRaises(exception.ResourceFailure,
                                scheduler.TaskRunner(wf.create))
        expected_state = (wf.CREATE, wf.FAILED)
        self.assertEqual(expected_state, wf.state)
        self.assertIn('Exception: resources.workflow: boom!',
                      six.text_type(exc))

    def test_update_replace(self):
        wf = self._create_resource('workflow', self.rsrc_defn, self.stack)

        t = template_format.parse(workflow_template_update_replace)
        rsrc_defns = template.Template(t).resource_definitions(self.stack)
        new_workflow = rsrc_defns['workflow']

        new_workflows = [FakeWorkflow('hello_action')]
        self.mistral.workflows.update.return_value = new_workflows
        self.mistral.workflows.delete.return_value = None

        err = self.assertRaises(resource.UpdateReplace,
                                scheduler.TaskRunner(wf.update,
                                                     new_workflow))
        msg = 'The Resource workflow requires replacement.'
        self.assertEqual(msg, six.text_type(err))

    def test_update(self):
        wf = self._create_resource('workflow', self.rsrc_defn,
                                   self.stack)
        t = template_format.parse(workflow_template_update)
        rsrc_defns = template.Template(t).resource_definitions(self.stack)
        new_wf = rsrc_defns['workflow']
        self.mistral.workflows.update.return_value = [
            FakeWorkflow('test_stack-workflow-b5fiekfci3yc')]
        scheduler.TaskRunner(wf.update, new_wf)()
        self.assertTrue(self.mistral.workflows.update.called)
        self.assertEqual((wf.UPDATE, wf.COMPLETE), wf.state)

    def test_update_failed(self):
        wf = self._create_resource('workflow', self.rsrc_defn,
                                   self.stack)
        t = template_format.parse(workflow_template_update)
        rsrc_defns = template.Template(t).resource_definitions(self.stack)
        new_wf = rsrc_defns['workflow']
        self.mistral.workflows.update.side_effect = Exception('boom!')
        self.assertRaises(exception.ResourceFailure,
                          scheduler.TaskRunner(wf.update, new_wf))
        self.assertEqual((wf.UPDATE, wf.FAILED), wf.state)

    def test_delete(self):
        wf = self._create_resource('workflow', self.rsrc_defn, self.stack)

        scheduler.TaskRunner(wf.delete)()
        self.assertEqual((wf.DELETE, wf.COMPLETE), wf.state)

    def test_delete_no_data(self):
        wf = self._create_resource('workflow', self.rsrc_defn, self.stack)

        wf.data_delete('executions')
        self.assertEqual([], wf.FnGetAtt('executions'))
        scheduler.TaskRunner(wf.delete)()
        self.assertEqual((wf.DELETE, wf.COMPLETE), wf.state)

    def test_delete_not_found(self):
        wf = self._create_resource('workflow', self.rsrc_defn, self.stack)

        self.mistral.workflows.delete.side_effect = (
            self.mistral.mistral_base.APIException(error_code=404))

        scheduler.TaskRunner(wf.delete)()
        self.assertEqual((wf.DELETE, wf.COMPLETE), wf.state)

    @mock.patch.object(resource.Resource, 'client_plugin')
    def test_delete_other_errors(self, mock_plugin):
        """We mock client_plugin for returning correct mistral client."""
        mock_plugin.return_value = self.client
        client.mistral_base.APIException = exception.Error
        wf = self._create_resource('workflow', self.rsrc_defn, self.stack)

        self.mistral.workflows.delete.side_effect = (Exception('boom!'))

        exc = self.assertRaises(exception.ResourceFailure,
                                scheduler.TaskRunner(wf.delete))
        self.assertEqual((wf.DELETE, wf.FAILED), wf.state)
        self.assertIn('boom!', six.text_type(exc))

    def test_resource_mapping(self):
        mapping = workflow.resource_mapping()
        self.assertEqual(1, len(mapping))
        self.assertEqual(workflow.Workflow,
                         mapping['OS::Mistral::Workflow'])

    def test_signal_failed(self):
        tmpl = template_format.parse(workflow_template_full)
        stack = utils.parse_stack(tmpl)
        rsrc_defns = stack.t.resource_definitions(stack)['create_vm']
        wf = MistralWorkFlowTestResource('create_vm', rsrc_defns, stack)
        self.mistral.workflows.create.return_value = [
            FakeWorkflow('create_vm')]
        scheduler.TaskRunner(wf.create)()
        details = {'input': {'flavor': '3'}}
        self.mistral.executions.create.side_effect = Exception('boom!')
        err = self.assertRaises(exception.ResourceFailure,
                                scheduler.TaskRunner(wf.signal, details))
        self.assertEqual('Exception: resources.create_vm: boom!',
                         six.text_type(err))

    def test_signal_wrong_input_and_params_type(self):
        tmpl = template_format.parse(workflow_template_full)
        stack = utils.parse_stack(tmpl)
        rsrc_defns = stack.t.resource_definitions(stack)['create_vm']
        wf = MistralWorkFlowTestResource('create_vm', rsrc_defns, stack)
        self.mistral.workflows.create.return_value = [
            FakeWorkflow('create_vm')]
        scheduler.TaskRunner(wf.create)()
        details = {'input': '3'}
        err = self.assertRaises(exception.ResourceFailure,
                                scheduler.TaskRunner(wf.signal, details))
        error_message = ("StackValidationFailed: resources.create_vm: "
                         "Signal data error: Input in"
                         " signal data must be a map, find a <type 'str'>")
        self.assertEqual(error_message, six.text_type(err))
        details = {'params': '3'}
        err = self.assertRaises(exception.ResourceFailure,
                                scheduler.TaskRunner(wf.signal, details))
        error_message = ("StackValidationFailed: resources.create_vm: "
                         "Signal data error: Params "
                         "must be a map, find a <type 'str'>")
        self.assertEqual(error_message, six.text_type(err))

    def test_signal_wrong_input_key(self):
        tmpl = template_format.parse(workflow_template_full)
        stack = utils.parse_stack(tmpl)
        rsrc_defns = stack.t.resource_definitions(stack)['create_vm']
        wf = MistralWorkFlowTestResource('create_vm', rsrc_defns, stack)
        self.mistral.workflows.create.return_value = [
            FakeWorkflow('create_vm')]
        scheduler.TaskRunner(wf.create)()
        details = {'input': {'1': '3'}}
        err = self.assertRaises(exception.ResourceFailure,
                                scheduler.TaskRunner(wf.signal, details))
        error_message = ("StackValidationFailed: resources.create_vm: "
                         "Signal data error: Unknown input 1")
        self.assertEqual(error_message, six.text_type(err))

    def test_signal_and_delete_with_executions(self):
        tmpl = template_format.parse(workflow_template_full)
        stack = utils.parse_stack(tmpl)
        rsrc_defns = stack.t.resource_definitions(stack)['create_vm']
        wf = MistralWorkFlowTestResource('create_vm', rsrc_defns, stack)
        self.mistral.workflows.create.return_value = [
            FakeWorkflow('create_vm')]
        scheduler.TaskRunner(wf.create)()
        details = {'input': {'flavor': '3'}}
        execution = mock.Mock()
        execution.id = '12345'
        # Invoke the real create method (bug 1453539)
        exec_manager = executions.ExecutionManager(wf.client('mistral'))
        self.mistral.executions.create.side_effect = (
            lambda *args, **kw: exec_manager.create(*args, **kw))
        self.patchobject(exec_manager, '_create', return_value=execution)
        scheduler.TaskRunner(wf.signal, details)()
        self.assertEqual({'executions': '12345'}, wf.data())
        scheduler.TaskRunner(wf.delete)()
        self.assertEqual(1, self.mistral.executions.delete.call_count)
        self.assertEqual((wf.DELETE, wf.COMPLETE), wf.state)

    def test_workflow_params(self):
        tmpl = template_format.parse(workflow_template_full)
        stack = utils.parse_stack(tmpl)
        rsrc_defns = stack.t.resource_definitions(stack)['create_vm']
        wf = MistralWorkFlowTestResource('create_vm', rsrc_defns, stack)
        self.mistral.workflows.create.return_value = [
            FakeWorkflow('create_vm')]
        scheduler.TaskRunner(wf.create)()
        details = {'input': {'flavor': '3'},
                   'params': {'test': 'param_value', 'test1': 'param_value_1'}}
        execution = mock.Mock()
        execution.id = '12345'
        self.mistral.executions.create.side_effect = (
            lambda *args, **kw: self.verify_params(*args, **kw))
        scheduler.TaskRunner(wf.signal, details)()

    def test_workflow_params_merge(self):
        tmpl = template_format.parse(workflow_template_with_params)
        stack = utils.parse_stack(tmpl)
        rsrc_defns = stack.t.resource_definitions(stack)['workflow']
        wf = MistralWorkFlowTestResource('workflow', rsrc_defns, stack)
        self.mistral.workflows.create.return_value = [
            FakeWorkflow('workflow')]
        scheduler.TaskRunner(wf.create)()
        details = {'params': {'test1': 'param_value_1'}}
        execution = mock.Mock()
        execution.id = '12345'
        self.mistral.executions.create.side_effect = (
            lambda *args, **kw: self.verify_params(*args, **kw))
        scheduler.TaskRunner(wf.signal, details)()

    def test_workflow_params_override(self):
        tmpl = template_format.parse(workflow_template_with_params_override)
        stack = utils.parse_stack(tmpl)
        rsrc_defns = stack.t.resource_definitions(stack)['workflow']
        wf = MistralWorkFlowTestResource('workflow', rsrc_defns, stack)
        self.mistral.workflows.create.return_value = [
            FakeWorkflow('workflow')]
        scheduler.TaskRunner(wf.create)()
        details = {'params': {'test': 'param_value', 'test1': 'param_value_1'}}
        execution = mock.Mock()
        execution.id = '12345'
        self.mistral.executions.create.side_effect = (
            lambda *args, **kw: self.verify_params(*args, **kw))
        scheduler.TaskRunner(wf.signal, details)()

    def verify_params(self, workflow_name, workflow_input=None, **params):
        self.assertEqual({'test': 'param_value', 'test1': 'param_value_1'},
                         params)
        execution = mock.Mock()
        execution.id = '12345'
        return execution


text:
<?php

  namespace ActiveCollab\Narrative\Error;

  /**
   * Exception that is thrown when we fail to load a given theme
   *
   * @package ActiveCollab\Narrative\Narrative\Error
   */
  class ThemeNotFoundError extends Error
  {
    /**
     * @param string $name
     * @param string $expected_location
     * @param string|null $message
     */
    function __construct($name, $expected_location, $message = null)
    {
      if (empty($message)) {
        $message = "Theme '$name' was not found at '$expected_location'";
      }

      parent::__construct($message);
    }
  }


text:
import { IsNotEmpty, IsString, ValidateIf } from 'class-validator';

import { TInputOptions } from '../../types/options/TInputOptions';

import { SourceMapSourcesMode } from '../../enums/source-map/SourceMapSourcesMode';

/**
 * @returns {PropertyDecorator}
 */
export const IsInputFileName = (): PropertyDecorator => {
    return (target: any, key: string | symbol): void => {
        IsString()(target, key);
        ValidateIf(({sourceMapSourcesMode}: TInputOptions) => {
            return sourceMapSourcesMode === SourceMapSourcesMode.Sources;
        })(target, key);
        IsNotEmpty()(target, key);
    };
};


text:
/**
 * AbstractFile is an abstract representation of a file. There are two implementation:
 * 1. RemoteFile  - representation of a file on a remote server which can be
 * fetched in chunks, e.g. using a Range request.
 * 2. LocalStringFile is a representation of a file that was created from input string.
 * Used for testing and small input files.
 * @flow
 */
'use strict';

//import Q from 'q';

class AbstractFile {
  constructor() {
    //how to prevent instantation of this class???
    //this code doesn't pass npm run flow
//    if (new.target === AbstractFile) {
//      throw new TypeError("Cannot construct AbstractFile instances directly");
//    }
  }

  getBytes(start: number, length: number):Object {//: Q.Promise<ArrayBuffer> {
    throw new TypeError("Method getBytes is not implemented");
  }

  // Read the entire file -- not recommended for large files!
  getAll():Object {//: Q.Promise<ArrayBuffer> {
    throw new TypeError("Method getAll is not implemented");
  }

  // Reads the entire file as a string (not an ArrayBuffer).
  // This does not use the cache.
  getAllString():Object {//: Q.Promise<string> {
    throw new TypeError("Method getAllString is not implemented");
  }

  // Returns a promise for the number of bytes in the remote file.
  getSize():Object {//: Q.Promise<number> {
    throw new TypeError("Method getSize is not implemented");
  }
}

module.exports = AbstractFile;


text:
function [Pmax, PR, opf, gind, op, vnum] = findUniqueParent(ori0, wf0, ORmat, thr, Nv, w0, PRmin, varargin)
% Find unique parent for orientations.
%   Close orientations with misorientation less than 'thr' will be
%   combined in group for reduce the amount of calculation. For group
%   calculate possible parents.
%
% Syntax
%   [Pmax, PR, opf, gind, op, vnum] = findUniqueParent(ori0, wf0, ORmat, thr, Nv, w0, PRmin, varargin)
%
% Output
%   Pmax    - maximal parent probability
%   PR      - first to second probability ratio
%   opf     - orientation of unique parent, 0 if not find
%   gind    - indices of grains in current fragment
%   op      - orientation of parents
%   vnum    - indices of varinats
%
% Input
%   ori0    - set of orienations
%   wf0     - weigth function
%   ORmat   - orientation relation matrix (from alpha to gamma)
%   thr     - orientation integration threshold in radian
%   Nv      - minimal number of variant
%   w0      - tolerance (in radian)
%   PRmin   - minimal probability ratio
%
% Options
%   'onlyFirst'     - check only parents of first child (usefull if all
%                   	grains will be checked).
%   'combineClose'  - combine close orientations
%   'useWeightFunc' - use weight function
%
% History
% 17.04.13  Change 'ORname' to 'ORmat'. Fix comments.
% 28.07.14  Add 'varargin'. Add options 'onlyFirst', 'combineClose'. Some
%           makeups.
% 04.08.14? Rewrite CheckParents, now it find the best parent.

%% Preparation
Pmax = 0;
PR   = 0;
opf  = 0;
gind = 0;
op   = 0;
vnum = 0;

VNmin = Nv;

% Normalize weight function
if (numel(wf0) == 1 && wf0 == 0)
	wf0 = ones(1,length(ori0));
end
wf0  = wf0/sum(wf0);

% Check ORmat
if (numel(ORmat) ~= 9)
    error('Bad OR matrix');
end

% Check number of variants. Now only number of domains.
n0 = length(ori0);
if n0 < Nv
    dprintf(1,'Too few variants\n'); return;
end

% Group close orientation
if check_option(varargin, 'combineClose')
    [ori, gc, gi] = closeOrientation(ori0, n0, thr);
    n = length(ori);
    dprintf(1,['Number of orientation was changed from ' int2str(n0) ' to ' int2str(n) ' \n']);
else
    ori = ori0;             % orientations of groups
    gc  = ones(1,n0);       % number of orientations in group
    gi  = num2cell(1:n0);   % indices of orietations in group
    n   = n0;               % number of groups
end

% Use weight function
if check_option(varargin, 'useWeightFunc')
    wf = cellfun(@(x) sum(wf0(x)), gi);
    Pmin = Nv/length(wf);
else
    wf = gc;
    Pmin = Nv;
end

% Check number of variants again
if n < Nv
    dprintf(1,'Too few variants\n'); return;
end

% Crystall symmetry
CS = get(ori,'CS');
nv = length(CS);

% Array of potential parent orienations and link with domains
[op, opi] = getVariants(ori, ORmat, CS);
np = length(op);

%% Calculation of probabilities of potential parents

% Angle between potential parents
%  aaa = repmat(op, 1, np);
%  bbb = repmat(reshape(op,1,np), np,1);
%  ma = angle(aaa,bbb);

ma = smartAngle(op);

% Check potential parents
%   Pp  - probability of parent
%   rci - relevant child index
%   rvi - relevant varinat index
%   ppo - probable parent orientation
%   Ds  - distance to parent from others
%   Vn  - number of variants
if check_option(varargin, 'onlyFirst')
    [Pp, rci, rvi, ppo, Ds] = CheckFirstParents(1, ma, op, opi, wf, n, np, nv, w0);
else
    [Pp, rci, rvi, ppo, Ds] =      CheckParents(   ma, op, opi, wf, n, np, nv, w0, PRmin, Pmin, VNmin, ori, ORmat, CS);
end

% P = (sum(mm < w0) - mv)/n;
% P = Pp;

%% Find best parent
% Find high probability parents
[Ps,IX] = sort(Pp,'descend');
rci = rci(IX);
rvi = rvi(IX);
ppo = ppo(IX);
Ds  = Ds(IX);

% Max probability
Pmax = Ps(1);
opf = mean(ppo{1});
% opf = ppo{1};
% vnum = rvi{1};
vnum0 = checkVariants(opf, ORmat, CS, ori(rci{1}));
vn = length(unique(vnum0));

debugInfo001(ppo, opf);

% If have only one parent
[goodProbRatio, PR] = checkRatio(Ps, PRmin, Pmin, vn, VNmin);
if goodProbRatio
    gind = rci{1};
    vnum = vnum0;
    op   = ppo{1};

    if (isfulldebug)
        hf = figure; plotpdf(getVariants(opf, inv(ORmat), CS), Miller(1,0,0), 'antipodal', 'MarkerSize',4, 'MarkerColor', 'b')
        hold on; plotpdf(ori(gind),Miller(1,0,0), 'antipodal', 'MarkerSize',4, 'MarkerColor', 'g');
        hold on; plotpdf(ori(~gind),Miller(1,0,0), 'antipodal', 'MarkerSize',4, 'MarkerColor', 'k');
        hold on; plotpdf(ppo{1},Miller(1,0,0), 'antipodal', 'MarkerSize',4, 'MarkerColor', 'r');
        hold off;
        close(hf);
    end;

    gind2 = [];
    for i = gind
        gind2 = [gind2 gi{i}]; %#ok<AGROW>
    end

    gind = gind2;

    if (length(gind) > length(ori0))
        disp('Test!');
    end
else
	opf = 0;
end

% Debug information
dprintf(1,'%d-%d-%3.1f\n', n, Pmax, PR);
end

function ma = smartAngle(op)
% Prevent out of memory
if length(op) > getpref('ebsdam', 'maxProbParents')
    fprintf('Too much probable parent\n');

    ma = [];

    n0 = getpref('ebsdam', 'maxProbParents');
    n1 = length(op);
    n = ceil(n1*n1/(n0*n0));
    ni = ceil(n1/n);
    is = 1;
    ie = ni;
    for i = 1:n
        ind = is:ie;
        mai = angle(op(ind)\op);
        ma = [ma; mai]; %#ok<AGROW>
        is = is + ni;
        ie = ie + ni;
        if (ie > n1)
            ie = n1;
        end
    end
else
    ma = angle(op\op);
end
end

function [bool, PR] = checkRatio(PS, PRmin, Pmin, vn, VNmin)
% Calculate the ratio of parent probabilities
%
% Input
%   PS      - probabilities
%   PRmin   - minimal probability ratio
%   Pmin    - minimal probability value
%   vn      - number of variants
%   VNmin   - minimal number of variants

if (PS(2) ~= 0)
    PR = PS(1)/PS(2);
else
    PR = 100*PS(1);
end

bool = (PR > PRmin) && (PS(1) >= Pmin) && (vn > VNmin);

end

function [ori, c, g] = closeOrientation(ori0, n, thr)
% Combine close orientations in groups
%   Return array of far orientation. Close orientations are combine in
%   group and replace by mean value. Array 'c' contain number of
%   orientations in group, 'g' - indices of orientations in group.

ori = ori0;

% Find close domains. It's not add new information.
i = 1;
g = cell(1,n);  % orientation group
oi = 1:n;       % orientation index

while i <= n
    md = (angle(ori\ori(i)) < thr)';
    g{i} = oi(md);
    if sum(md) > 1
        ori(i) = mean(ori(md));
        md(i) = 0;
        ori = ori(~md);
        oi = oi(~md);
        n = length(ori);
    end
    i = i+1;
end

% Calc count of orientations in groups
c = zeros(1,n);
for i = 1:n
    c(i) = length(g{i});
end

g = g(1:n);
end

function [Pp, rci, rvi, ppo, Ds] = CheckParents(ma, op, opi, wf, n, np, nv, w0, PRmin, Pmin, VNmin, ori, ORmat, CS)
% !!!Important: May have problem this symmetry (not checked). Let's think:
% if all children are from one parent orientation. We can reconstructe
% parent orientation with resepect to symmetry.
%
% Output
%   Pp  - probability of parent
%   rci - relevant child index
%   rvi - relevant varinat index
%   ppo - probable parent orientation
%   Ds  - distance to parent from others
%
% Input
%   ma  - misorientation between possible parents
%   op  - orientation of possible parents
%   opi - possible parents index (see getVariants)
%   wf  - normalized wiegth function
%   n   - number of orientation
%   np  - number of parents
%   nv  - number of varinats
%   w0  - maximal deviation between parents
%   VNmin   - minimal number of variants
%   ori     - set of child orienations
%   ORmat   - orientation relation matrix (from alpha to gamma)
%   CS      - crystal symmetry

if (0)
    % Probability of potential parents
    Pp  = zeros(1,np);  % probability of parent
    Ds  = zeros(1,np);  % probable parent orientation
    rci = cell(1,np);   % relevant child index
    rvi = cell(1,np);   % relevant varinat index
    ppo = cell(1,np);   % probable parent orientation

    for i = 1:n
        j = (i-1)*nv+(1:nv);
        [Pp(j), rci(j), rvi(j), ppo(j), Ds(j)] = CheckFirstParents(i, ma, op, opi, wf, n, np, nv, w0);
    end
else
    % Probability of potential parents
    iPp  = cell(1,n);   % probability of parent
    iDs  = cell(1,n);   % probable parent orientation
    irci = cell(1,n);   % relevant child index
    irvi = cell(1,n);   % relevant varinat index
    ippo = cell(1,n);   % probable parent orientation

    bad = zeros(1,n);
    Pi = zeros(1,n);
    Pmax = 0;
    imax = 0;

    for i = 1:n
        [Pp, rci, rvi, ppo, Ds] = CheckFirstParents(i, ma, op, opi, wf, n, np, nv, w0);

        [Ps,IX] = sort(Pp,'descend');
        rci = rci(IX);
        rvi = rvi(IX);
        ppo = ppo(IX);
        Ds  = Ds(IX);

        opf = mean(ppo{1});
        vnum0 = checkVariants(opf, ORmat, CS, ori(rci{1}));
        vn = length(unique(vnum0));
        [goodProbRatio, PR] = checkRatio(Ps, PRmin, Pmin, vn, VNmin);

        if goodProbRatio
            if (Ps(1) > Pmax)
                Pmax  = Ps(1);
                imax  = i;
            end

            Pi(i) = Ps(1);
            iPp{i}  = Ps;
            irci{i} = rci;
            irvi{i} = rvi;
            ippo{i} = ppo;
            iDs{i}  = Ds;
        else
            bad(i) = 1;
        end
    end

    Pp  = iPp{imax};
    rci = irci{imax};
    rvi = irvi{imax};
    ppo = ippo{imax};
    Ds  = iDs{imax};
end
end

function [Pp, rci, rvi, ppo, Ds] = CheckFirstParents(i, ma, op, opi, wf, n, np, nv, w0)
% !!!Important: this method check only possible parent of first child. Also
%   this method ignores only real distance between parent, only hitting in
%   'w0' region.
%
% Output
%   Pp  - probability of parent
%   rci - relevant child index
%   rvi - relevant varinat index
%   ppo - probable parent orientation
%   Ds  - distance to parent from others
%
% Input
%   ma  - misorientation between possible parents
%   op  - orientation of possible parents
%   opi - possible parents index (see getVariants)
%   wf  - weigth function
%   n   - number of orientation
%   np  - number of parents
%   nv  - number of varinats
%   w0  - maximal deviation between parents

% Probability of potential parents
Pp  = zeros(1,nv);  % probability of parent
Ds  = zeros(1,nv);  % distance to parent from others
rci = cell(1,nv);   % relevant child index
rvi = cell(1,nv);   % relevant varinat index
ppo = cell(1,nv);   % probable parent orientation

% Look over probable parents and count related children for first child. So
% we check only variants of parents for first child.
i1 = find(opi == i);
for k = 1:nv
    i = i1(k);   % index of current parent orientation
    ic = opi(i); % child id (equal 1)
    iv = fix((i-1)/n)+1; % variant id (equal k)

    % Get Remove itself misorientation
    ma1 = ma(i,opi ~= ic); % 1 x (nv*(n-1))
    cl = (1:n ~= ic); % new child logical index for ma1
    ci = find(cl); % new child index for ma1

    % Associate misorientation with child
    ma1 = reshape(ma1, n-1, nv); % (n-1) x nv

    % !!! Where we can lose variants
    % Minimal misorientation for each child (in row, return column)
    [ma2, ma2i] = min(ma1,[],2); % (n-1) x 1

    rcl    = (ma2 < w0)';       % related child logical index
    rci{k} = [ic ci(rcl)];      % related child index
    rvi{k} = [iv ma2i(rcl)'];   % index of variant referred to related child

    % Number of related child within w0 tolerance. Remember about close
    % orientation removed at start and current child.
    Pp(k) = sum(wf(rci{k}));
    Ds(k) = sum(ma2(rcl))/length(Pp(k)); % sum of distances between parents

    % Calc indices of parent orientation, based on varinat and child numbers
    ppi = (rvi{k}-1)*n+rci{k};

    % Get orientation of parents
    ppo{k} = op(ppi);

    if (isfulldebug && 0)
        % changes ori to op
        hf = figure; plotpdf(op(rci{k}), Miller(1,0,0), 'antipodal', 'MarkerSize',4);
        hold on; plotpdf(ppo{k},Miller(1,0,0), 'antipodal', 'MarkerSize',4);
        hold off;
        close(hf);
    end

end

end

function debugInfo001(ppo, opf)

if (isfulldebug)
    h1 = figure;
    ouppp = cellfun(@(x) mean(x),ppo(1:4), 'UniformOutput', false);
    ouppp = [ouppp{:}];
    plotpdf(ouppp,Miller(1,0,0), 'antipodal', 'MarkerSize',4, 'MarkerColor', 'g');
    hold on;
    plotpdf(opf,Miller(1,0,0), 'antipodal', 'MarkerSize',4, 'MarkerColor', 'r');
    hold off;
    close(h1);
end
end


text:
<?php
/**
 * @namespace
 */
namespace Vein\Core\Model\Behavior;

/**
 * Trait AnnotationsInitializer
 *
 * @category   Vein\Core
 * @package    Model
 * @subpackage Behavior
 */
trait Timestampable
{
    /**
     * @Column(type="datetime", nullable=true, column="creation_date")
     */
    public $creation_date;

    /**
     * @Column(type="datetime", nullable=true, column="modified_date")
     */
    public $modified_date;

    public function beforeCreate()
    {
        $this->creation_date = date('Y-m-d H:i:s');
    }

    public function beforeUpdate()
    {
        $this->modified_date = date('Y-m-d H:i:s');
    }
}


text:
import pytest

from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc import RPCErrorResponse

@pytest.fixture(params=['jsonrpc'])
def protocol(request):
    if 'jsonrpc':
        return JSONRPCProtocol()

    raise RuntimeError('Bad protocol name in test case')

def test_protocol_returns_bytes(protocol):
    req = protocol.create_request('foo', ['bar'])

    assert isinstance(req.serialize(), bytes)

def test_procotol_responds_bytes(protocol):
    req = protocol.create_request('foo', ['bar'])
    rep = req.respond(42)
    err_rep = req.error_respond(Exception('foo'))

    assert isinstance(rep.serialize(), bytes)
    assert isinstance(err_rep.serialize(), bytes)

def test_one_way(protocol):
    req = protocol.create_request('foo', None, {'a': 'b'}, True)

    assert req.respond(None) == None

def test_raises_on_args_and_kwargs(protocol):
    with pytest.raises(Exception):
        protocol.create_request('foo', ['arg1', 'arg2'], {'kw_key': 'kw_value'})

def test_supports_no_args(protocol):
        protocol.create_request('foo')

def test_creates_error_response(protocol):
    req = protocol.create_request('foo', ['bar'])
    err_rep = req.error_respond(Exception('foo'))

    assert hasattr(err_rep, 'error')

def test_parses_error_response(protocol):
    req = protocol.create_request('foo', ['bar'])
    err_rep = req.error_respond(Exception('foo'))

    parsed = protocol.parse_reply(err_rep.serialize())

    assert hasattr(parsed, 'error')

def test_default_id_generator():
    from tinyrpc.protocols import default_id_generator
    g = default_id_generator(1)
    assert next(g) == 1
    assert next(g) == 2
    assert next(g) == 3


text:
require 'system/shared/out_examples'
require 'securerandom'

describe 'when `out` is executed in a docker container', type: 'aruba' do
  let(:host_source_directory) { "/tmp/#{SecureRandom.uuid}" }
  let(:container_source_directory) { '/concourse' }
  let(:container_source_file) { File.join(container_source_directory, 'resource_contents') }

  before do
    `docker build -t suhlig/concourse-rss-resource:latest .`

    # We don't necessarily have access to the docker host's file system from
    # this test, so we create the resource contents by mounting another container
    # with the same volume as the one that created the file.
    run_command "docker run --rm \
      --volume #{host_source_directory}:#{container_source_directory} \
      suhlig/concourse-rss-resource \
      'echo #{resource_contents} > #{container_source_file}'"

    run_command "docker run --rm --interactive \
         --volume #{host_source_directory}:#{container_source_directory} \
         suhlig/concourse-rss-resource \
         /opt/resource/out #{container_source_directory}"
  end

  include_examples 'out'
end


text:
<?php

namespace NilPortugues\Tests\Api\Json\Http\Message\Json;

use NilPortugues\Api\Json\Http\Message\ErrorResponse;

class ErrorResponseTest extends \PHPUnit_Framework_TestCase
{
    public function testResponse()
    {
        $response = new ErrorResponse('Internal Server Error', 400);

        $this->assertEquals(400, $response->getStatusCode());
        $this->assertEquals(['application/json; charset=utf-8'], $response->getHeader('Content-type'));
    }
}


text:
<html>
<head>
<script src="inspector-test.js"></script>
<script src="debugger-test.js"></script>
<script src="workspace-test.js"></script>
<script src="breakpoint-manager-test.js"></script>

<script>

function test()
{
    var mockTargetId = 1;
    var MockTarget = function(name, connection, callback)
    {
        WebInspector.Target.call(this, name, connection, callback);
    }
    MockTarget.prototype = {
        _loadedWithCapabilities: function(callback)
        {
            this.debuggerModel = new WebInspector.DebuggerModel(this);
            this.resourceTreeModel = WebInspector.targetManager.mainTarget().resourceTreeModel;
            if (callback)
                callback();
        },

        __proto__: WebInspector.Target.prototype
    }

    function createMockTarget(userCallback)
    {
        var target = new MockTarget("mock-target-" + (mockTargetId++), new InspectorBackendClass.StubConnection(), callback);
        function callback()
        {
            InspectorTest.testTargetManager.addTarget(target);
            userCallback(target);
        }
    }

    function createWorkspaceWithTarget(userCallback)
    {
        InspectorTest.createWorkspace();

        InspectorTest.testWorkspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded);
        InspectorTest.testWorkspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, uiSourceCodeRemoved);

        createMockTarget(callback);
        function callback(target)
        {
            userCallback(target);
        }
    }

    function checkMapping(compiledLineNumber, compiledColumnNumber, sourceURL, sourceLineNumber, sourceColumnNumber, mapping)
    {
        var entry = mapping.findEntry(compiledLineNumber, compiledColumnNumber);
        InspectorTest.addResult(sourceURL + " === " + entry[2]);
        InspectorTest.addResult(sourceLineNumber + " === " + entry[3]);
        InspectorTest.addResult(sourceColumnNumber + " === " + entry[4]);
    }

    function checkReverseMapping(compiledLineNumber, compiledColumnNumber, sourceURL, sourceLineNumber, mapping)
    {
        var entry = mapping.findEntryReversed(sourceURL, sourceLineNumber, 5);
        InspectorTest.addResult(compiledLineNumber + " === " + entry[0]);
        InspectorTest.addResult(compiledColumnNumber + " === " + entry[1]);
    }

    function uiLocation(script, line, column)
    {
        var location = script.target().debuggerModel.createRawLocation(script, line, column);
        return InspectorTest.testDebuggerWorkspaceBinding.rawLocationToUILocation(location);
    }

    function resetModels()
    {
        target.debuggerModel._reset();
        InspectorTest.testDebuggerWorkspaceBinding._reset(target);
    }

    function uiSourceCodeAdded(event)
    {
        var uiSourceCode = event.data;
        var networkURL = InspectorTest.testNetworkMapping.networkURL(uiSourceCode);
        InspectorTest.addResult("UISourceCodeAdded: [" + uiSourceCode.project().type() + "] " + networkURL);
    }

    function uiSourceCodeRemoved(event)
    {
        var uiSourceCode = event.data;
        var networkURL = InspectorTest.testNetworkMapping.networkURL(uiSourceCode);
        InspectorTest.addResult("UISourceCodeRemoved: [" + uiSourceCode.project().type() + "] " + networkURL);
    }

    InspectorTest.runTestSuite([
        function testSimpleMap(next)
        {
            /*
                example.js:
                0         1         2         3
                012345678901234567890123456789012345
                function add(variable_x, variable_y)
                {
                    return variable_x + variable_y;
                }

                var global = "foo";
                ----------------------------------------
                example-compiled.js:
                0         1         2         3
                012345678901234567890123456789012345
                function add(a,b){return a+b}var global="foo";
                foo
            */
            var mappingPayload = {
                "mappings":"AAASA,QAAAA,IAAG,CAACC,CAAD,CAAaC,CAAb,CACZ,CACI,MAAOD,EAAP,CAAoBC,CADxB,CAIA,IAAIC,OAAS;A",
                "sources":["example.js"]
            };
            var mapping = new WebInspector.SourceMap("source-map.json", mappingPayload);

            checkMapping(0, 9, "example.js", 0, 9, mapping);
            checkMapping(0, 13, "example.js", 0, 13, mapping);
            checkMapping(0, 15, "example.js", 0, 25, mapping);
            checkMapping(0, 18, "example.js", 2, 4, mapping);
            checkMapping(0, 25, "example.js", 2, 11, mapping);
            checkMapping(0, 27, "example.js", 2, 24, mapping);
            checkMapping(1, 0, undefined, undefined, undefined, mapping);

            checkReverseMapping(0, 0, "example.js", 0, mapping);
            checkReverseMapping(0, 17, "example.js", 1, mapping);
            checkReverseMapping(0, 18, "example.js", 2, mapping);
            checkReverseMapping(0, 29, "example.js", 4, mapping);
            checkReverseMapping(0, 29, "example.js", 5, mapping);

            next();
        },

        function testNoMappingEntry(next)
        {
            var mappingPayload = {
                "mappings":"AAAA,C,CAAE;",
                "sources":["example.js"]
            };
            var mapping = new WebInspector.SourceMap("source-map.json", mappingPayload);
            checkMapping(0, 0, "example.js", 0, 0, mapping);
            var entry = mapping.findEntry(0, 1);
            InspectorTest.assertEquals(2, entry.length);
            checkMapping(0, 2, "example.js", 0, 2, mapping);
            next();
        },

        function testEmptyLine(next)
        {
            var mappingPayload = {
                "mappings":"AAAA;;;CACA",
                "sources":["example.js"]
            };
            var mapping = new WebInspector.SourceMap("source-map.json", mappingPayload);
            checkMapping(0, 0, "example.js", 0, 0, mapping);
            checkReverseMapping(3, 1, "example.js", 1, mapping);
            next();
        },

        function testSections(next)
        {
            var mappingPayload = {
                "sections": [{
                    "offset": { "line": 0, "column": 0 },
                    "map": {
                        "mappings":"AAAA,CAEC",
                        "sources":["source1.js", "source2.js"]
                    }
                }, {
                    "offset": { "line": 2, "column": 10 },
                    "map": {
                        "mappings":"AAAA,CAEC",
                        "sources":["source2.js"]
                    }
                }
            ]};
            var mapping = new WebInspector.SourceMap("source-map.json", mappingPayload);
            InspectorTest.assertEquals(2, mapping.sources().length);
            checkMapping(0, 0, "source1.js", 0, 0, mapping);
            checkMapping(0, 1, "source1.js", 2, 1, mapping);
            checkMapping(2, 10, "source2.js", 0, 0, mapping);
            checkMapping(2, 11, "source2.js", 2, 1, mapping);
            next();
        },

        function testResolveSourceMapURL(next)
        {
            var func = WebInspector.ParsedURL.completeURL;
            InspectorTest.addResult("http://example.com/map.json === " + func("http://example.com/script.js", "http://example.com/map.json"));
            InspectorTest.addResult("http://example.com/map.json === " + func("http://example.com/script.js", "/map.json"));
            InspectorTest.addResult("http://example.com/maps/map.json === " + func("http://example.com/scripts/script.js", "../maps/map.json"));
            var base = "http://a/b/c/d;p?q";
            InspectorTest.addResult("Tests from http://tools.ietf.org/html/rfc3986#section-5.4 using baseURL=\"" + base + "\"");
            function rfc3986_5_4(lhs, rhs)
            {
                var actual =  WebInspector.ParsedURL.completeURL(base, lhs);
                InspectorTest.addResult(lhs + " resolves to " + actual + "===" + rhs + " passes: " + (actual === rhs));
            }
            rfc3986_5_4("http://h", "http://h");  // modified from RFC3986
            rfc3986_5_4("g", "http://a/b/c/g");
            rfc3986_5_4("./g", "http://a/b/c/g");
            rfc3986_5_4("g/", "http://a/b/c/g/");
            rfc3986_5_4("/g", "http://a/g");
            rfc3986_5_4("//g", "http://g");
            rfc3986_5_4("?y", "http://a/b/c/d;p?y");
            rfc3986_5_4("g?y", "http://a/b/c/g?y");
            rfc3986_5_4("#s", "http://a/b/c/d;p?q#s");
            rfc3986_5_4("g#s", "http://a/b/c/g#s");
            rfc3986_5_4("g?y#s", "http://a/b/c/g?y#s");
            rfc3986_5_4(";x", "http://a/b/c/;x");
            rfc3986_5_4("g;x", "http://a/b/c/g;x");
            rfc3986_5_4("g;x?y#s", "http://a/b/c/g;x?y#s");
            rfc3986_5_4("", "http://a/b/c/d;p?q");
            rfc3986_5_4(".", "http://a/b/c/");
            rfc3986_5_4("./", "http://a/b/c/");
            rfc3986_5_4("..", "http://a/b/");
            rfc3986_5_4("../", "http://a/b/");
            rfc3986_5_4("../g", "http://a/b/g");
            rfc3986_5_4("../..", "http://a/");
            rfc3986_5_4("../../", "http://a/");
            rfc3986_5_4("../../g", "http://a/g");
            rfc3986_5_4("../../../g", "http://a/g");
            rfc3986_5_4("../../../../g", "http://a/g");
            rfc3986_5_4("/./g", "http://a/g");
            rfc3986_5_4("/../g", "http://a/g");
            rfc3986_5_4("g." , "http://a/b/c/g.");
            rfc3986_5_4(".g" , "http://a/b/c/.g");
            rfc3986_5_4("g..", "http://a/b/c/g..");
            rfc3986_5_4("..g", "http://a/b/c/..g");
            rfc3986_5_4("./../g", "http://a/b/g");
            rfc3986_5_4("./g/.", "http://a/b/c/g/");
            rfc3986_5_4("g/./h", "http://a/b/c/g/h");
            rfc3986_5_4("g/../h", "http://a/b/c/h");
            rfc3986_5_4("g;x=1/./y", "http://a/b/c/g;x=1/y");
            rfc3986_5_4("g;x=1/../y", "http://a/b/c/y");
            rfc3986_5_4("g?y/./x", "http://a/b/c/g?y/./x");
            rfc3986_5_4("g?y/../x", "http://a/b/c/g?y/../x");
            rfc3986_5_4("g#s/./x", "http://a/b/c/g#s/./x");
            rfc3986_5_4("g#s/../x", "http://a/b/c/g#s/../x");

             rfc3986_5_4("//secure.com/moo", "http://secure.com/moo");  // not in RFC3986
             rfc3986_5_4("cat.jpeg", "http://a/b/c/cat.jpeg");  // not in RFC3986
            next();
        },

        function testCompilerScriptMapping(next)
        {
            var script;
            var originalUISourceCode;
            var target;
            createWorkspaceWithTarget(step1);

            function step1(newTarget)
            {
                target = newTarget;
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(originalUISourceCodeAdded);
                script = InspectorTest.createScriptMock("compiled.js", 0, 0, true, "", target, function(script) {
                    script.sourceMapURL = "http://localhost:8000/inspector/resources/source-map.json";
                });
                InspectorTest.testDebuggerWorkspaceBinding._targetToData.get(target)._parsedScriptSource({ data: script });
            }

            function originalUISourceCodeAdded(uiSourceCode)
            {
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(originalResourceUISourceCodeAdded);
                InspectorTest.addMockUISourceCodeToWorkspace("compiled.js", WebInspector.resourceTypes.Script, "");
            }

            function originalResourceUISourceCodeAdded(uiSourceCode)
            {
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(stubUISourceCodeAdded, 1, WebInspector.projectTypes.Service);
                originalUISourceCode = uiSourceCode;
            }

            function stubUISourceCodeAdded(uiSourceCode)
            {
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(firstUISourceCodeAdded);
            }

            function firstUISourceCodeAdded(uiSourceCode)
            {
                var networkURL = InspectorTest.testNetworkMapping.networkURL(uiSourceCode);
                if (!networkURL) {
                    InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(firstUISourceCodeAdded);
                    return;
                }
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(secondUISourceCodeAdded);
            }

            function secondUISourceCodeAdded(uiSourceCode)
            {
                var networkURL = InspectorTest.testNetworkMapping.networkURL(uiSourceCode);
                if (!networkURL) {
                    InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(secondUISourceCodeAdded);
                    return;
                }
                afterScriptAdded();
            }

            function afterScriptAdded()
            {
                InspectorTest.addResult("afterScriptAdded");
                var uiSourceCode1 = InspectorTest.testWorkspace.uiSourceCodeForOriginURL("http://localhost:8000/inspector/resources/source1.js");
                var uiSourceCode2 = InspectorTest.testWorkspace.uiSourceCodeForOriginURL("http://localhost:8000/inspector/resources/source2.js");

                InspectorTest.checkUILocation(uiSourceCode1, 4, 4, uiLocation(script, 0, 81));
                InspectorTest.checkUILocation(uiSourceCode1, 5, 4, uiLocation(script, 0, 93));
                InspectorTest.checkUILocation(uiSourceCode2, 7, 4, uiLocation(script, 1, 151));
                InspectorTest.checkUILocation(originalUISourceCode, 1, 200, uiLocation(script, 1, 200));

                InspectorTest.checkRawLocation(script, 0, 42, InspectorTest.testDebuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode1, 3, 10));
                InspectorTest.checkRawLocation(script, 1, 85, InspectorTest.testDebuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode2, 0, 0));
                InspectorTest.checkRawLocation(script, 1, 110, InspectorTest.testDebuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode2, 5, 2));

                uiSourceCode1.requestContent(didRequestContent1);

                function didRequestContent1(content, contentEncoded, mimeType)
                {
                    InspectorTest.assertEquals(0, content.indexOf("window.addEventListener"));
                    uiSourceCode2.requestContent(didRequestContent2);
                }

                function didRequestContent2(content, contentEncoded, mimeType)
                {
                    InspectorTest.assertEquals(0, content.indexOf("function ClickHandler()"));
                    next();
                }
            }
        },

        function testCompilerScriptMappingWhenResourceWasLoadedAfterSource(next)
        {
            var script;
            var originalUISourceCode;
            var target;
            createWorkspaceWithTarget(workspaceCreated);

            function workspaceCreated(newTarget)
            {
                target = newTarget;
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(function() { });
                script = InspectorTest.createScriptMock("compiled.js", 0, 0, true, "", target, function(script) {
                    script.sourceMapURL = "http://localhost:8000/inspector/resources/source-map.json";
                });
                InspectorTest.testDebuggerWorkspaceBinding._targetToData.get(target)._parsedScriptSource({ data: script });
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(originalResourceUISourceCodeAdded);
                InspectorTest.addMockUISourceCodeToWorkspace("compiled.js", WebInspector.resourceTypes.Script, "");
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(firstUISourceCodeAdded);
            }

            function originalResourceUISourceCodeAdded(uiSourceCode)
            {
                originalUISourceCode = uiSourceCode;
            }

            function firstUISourceCodeAdded(uiSourceCode)
            {
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(secondUISourceCodeAdded);
            }

            function secondUISourceCodeAdded(uiSourceCode)
            {
                afterScriptAdded();
            }

            function afterScriptAdded(uiSourceCode)
            {
                var uiSourceCode1 = InspectorTest.testWorkspace.uiSourceCodeForOriginURL("http://localhost:8000/inspector/resources/source1.js");
                var uiSourceCode2 = InspectorTest.testWorkspace.uiSourceCodeForOriginURL("http://localhost:8000/inspector/resources/source2.js");

                InspectorTest.checkUILocation(uiSourceCode1, 4, 4, uiLocation(script, 0, 81));
                InspectorTest.checkUILocation(uiSourceCode1, 5, 4, uiLocation(script, 0, 93));
                InspectorTest.checkUILocation(uiSourceCode2, 7, 4, uiLocation(script, 1, 151));
                InspectorTest.checkUILocation(originalUISourceCode, 1, 200, uiLocation(script, 1, 200));

                InspectorTest.checkRawLocation(script, 0, 42, InspectorTest.testDebuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode1, 3, 10));
                InspectorTest.checkRawLocation(script, 1, 85, InspectorTest.testDebuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode2, 0, 0));
                InspectorTest.checkRawLocation(script, 1, 110, InspectorTest.testDebuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode2, 5, 2));

                uiSourceCode1.requestContent(didRequestContent1);

                function didRequestContent1(content, contentEncoded, mimeType)
                {
                    InspectorTest.assertEquals(0, content.indexOf("window.addEventListener"));
                    uiSourceCode2.requestContent(didRequestContent2);
                }

                function didRequestContent2(content, contentEncoded, mimeType)
                {
                    InspectorTest.assertEquals(0, content.indexOf("function ClickHandler()"));
                    next();
                }
            }
        },

        function testInlinedSourceMap(next)
        {
            var target;
            var script;
            createWorkspaceWithTarget(workspaceCreated);

            function workspaceCreated(newTarget) {
                target = newTarget;
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(compiledUISourceCodeAdded);
                 script = InspectorTest.createScriptMock("http://example.com/compiled.js", 0, 0, true, "", target, function(script) {
                    var sourceMap = {
                        "file":"compiled.js",
                        "mappings":"AAASA,QAAAA,IAAG,CAACC,CAAD,CAAaC,CAAb,CACZ,CACI,MAAOD,EAAP,CAAoBC,CADxB,CAIA,IAAIC,OAAS;",
                        "sources":["source.js"],
                        "sourcesContent":["<source content>"]
                    };
                    script.sourceMapURL = "data:application/json;base64," + btoa(JSON.stringify(sourceMap));
                });
                InspectorTest.testDebuggerWorkspaceBinding._targetToData.get(target)._parsedScriptSource({ data: script });
            }

            function compiledUISourceCodeAdded(uiSourceCode)
            {
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(originalUISourceCodeAdded);
            }

            function originalUISourceCodeAdded(uiSourceCode)
            {
                var uiSourceCode = InspectorTest.testWorkspace.uiSourceCodeForOriginURL("http://example.com/source.js");

                InspectorTest.checkUILocation(uiSourceCode, 2, 4, uiLocation(script, 0, 18));
                InspectorTest.checkRawLocation(script, 0, 18, InspectorTest.testDebuggerWorkspaceBinding.uiLocationToRawLocation(target, uiSourceCode, 2, 4));

                uiSourceCode.requestContent(didRequestContent);

                function didRequestContent(content, contentEncoded, mimeType)
                {
                    InspectorTest.addResult("<source content> === " + content);
                    next();
                }
            }
        },

        function testSourceMapCouldNotBeLoaded(next)
        {
            WebInspector.settings.jsSourceMapsEnabled.get = function() { return true; }
            createWorkspaceWithTarget(workspaceCreated);
            function workspaceCreated(target)
            {
                InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(compiledUISourceCodeAdded);
                var script = InspectorTest.createScriptMock("compiled.js", 0, 0, true, "", target);

                function compiledUISourceCodeAdded(uiSourceCode)
                {
                    InspectorTest.waitForWorkspaceUISourceCodeAddedEvent(originalUISourceCodeAdded);
                }

                function originalUISourceCodeAdded(uiSourceCode) { }

                script.sourceMapURL = "http://localhost:8000/inspector/resources/source-map.json_";
                console.error = function() {}; // Error message is platform dependent.
                InspectorTest.testDebuggerWorkspaceBinding._targetToData.get(target)._parsedScriptSource({ data: script });
                var location = uiLocation(script, 0, 0);
                InspectorTest.addResult(location.uiSourceCode.originURL());
                next();
            }
        },

        function testSourceRoot(next)
        {
            /*
                example.js:
                0         1         2         3
                012345678901234567890123456789012345
                function add(variable_x, variable_y)
                {
                    return variable_x + variable_y;
                }

                var global = "foo";
                ----------------------------------------
                example-compiled.js:
                0         1         2         3
                012345678901234567890123456789012345
                function add(a,b){return a+b}var global="foo";
            */
            var mappingPayload = {
                "mappings":"AAASA,QAAAA,IAAG,CAACC,CAAD,CAAaC,CAAb,CACZ,CACI,MAAOD,EAAP,CAAoBC,CADxB,CAIA,IAAIC,OAAS;",
                "sources":["example.js"],
                "sourceRoot":"/"
            };
            var mapping = new WebInspector.SourceMap("source-map.json", mappingPayload);
            checkMapping(0, 9, "/example.js", 0, 9, mapping);
            checkReverseMapping(0, 0, "/example.js", 0, mapping);
            next();
        },
    ]);
};

</script>

</head>

<body onload="runTest()">
<p>Tests SourceMap and CompilerScriptMapping.</p>
</body>
</html>


text:
cask "google-analytics-opt-out" do
  version "1.0.1"
  sha256 "ffe34fd0cb98bd0b9e29498af40876d65313d61b5bad5a1c388be35626c5e457"

  url "https://dl.google.com/analytics/optout/safari/GoogleAnalyticsOptOut_#{version}.dmg"
  name "Google Analytics Opt Out"
  desc "Prevent website visitor's data from being used by Google Analytics JavaScript"
  homepage "https://tools.google.com/dlpage/gaoptout"

  app "Google Analytics Opt Out.app"
end


text:
.. _Dedicated-replication-network:

=============================
Dedicated replication network
=============================

-------
Summary
-------

Swift's replication process is essential for consistency and availability of
data. By default, replication activity will use the same network interface as
other cluster operations. However, if a replication interface is set in the
ring for a node, that node will send replication traffic on its designated
separate replication network interface. Replication traffic includes REPLICATE
requests and rsync traffic.

To separate the cluster-internal replication traffic from client traffic,
separate replication servers can be used. These replication servers are based
on the standard storage servers, but they listen on the replication IP and
only respond to REPLICATE requests. Storage servers can serve REPLICATE
requests, so an operator can transition to using a separate replication
network with no cluster downtime.

Replication IP and port information is stored in the ring on a per-node basis.
These parameters will be used if they are present, but they are not required.
If this information does not exist or is empty for a particular node, the
node's standard IP and port will be used for replication.

--------------------
For SAIO replication
--------------------

#. Create new script in ~/bin/ (for example: remakerings_new)::

        #!/bin/bash
        cd /etc/swift
        rm -f *.builder *.ring.gz backups/*.builder backups/*.ring.gz
        swift-ring-builder object.builder create 18 3 1
        swift-ring-builder object.builder add z1-127.0.0.1:6010R127.0.0.1:6050/sdb1 1
        swift-ring-builder object.builder add z2-127.0.0.1:6020R127.0.0.1:6060/sdb2 1
        swift-ring-builder object.builder add z3-127.0.0.1:6030R127.0.0.1:6070/sdb3 1
        swift-ring-builder object.builder add z4-127.0.0.1:6040R127.0.0.1:6080/sdb4 1
        swift-ring-builder object.builder rebalance
        swift-ring-builder container.builder create 18 3 1
        swift-ring-builder container.builder add z1-127.0.0.1:6011R127.0.0.1:6051/sdb1 1
        swift-ring-builder container.builder add z2-127.0.0.1:6021R127.0.0.1:6061/sdb2 1
        swift-ring-builder container.builder add z3-127.0.0.1:6031R127.0.0.1:6071/sdb3 1
        swift-ring-builder container.builder add z4-127.0.0.1:6041R127.0.0.1:6081/sdb4 1
        swift-ring-builder container.builder rebalance
        swift-ring-builder account.builder create 18 3 1
        swift-ring-builder account.builder add z1-127.0.0.1:6012R127.0.0.1:6052/sdb1 1
        swift-ring-builder account.builder add z2-127.0.0.1:6022R127.0.0.1:6062/sdb2 1
        swift-ring-builder account.builder add z3-127.0.0.1:6032R127.0.0.1:6072/sdb3 1
        swift-ring-builder account.builder add z4-127.0.0.1:6042R127.0.0.1:6082/sdb4 1
        swift-ring-builder account.builder rebalance

   .. note::
      Syntax of adding device has been changed: R<ip_replication>:<port_replication> was added between z<zone>-<ip>:<port> and /<device_name>_<meta> <weight>. Added devices will use <ip_replication> and <port_replication> for replication activities.

#. Add next rows in /etc/rsyncd.conf::

        [account6052]
        max connections = 25
        path = /srv/1/node/
        read only = false
        lock file = /var/lock/account6052.lock

        [account6062]
        max connections = 25
        path = /srv/2/node/
        read only = false
        lock file = /var/lock/account6062.lock

        [account6072]
        max connections = 25
        path = /srv/3/node/
        read only = false
        lock file = /var/lock/account6072.lock

        [account6082]
        max connections = 25
        path = /srv/4/node/
        read only = false
        lock file = /var/lock/account6082.lock

        [container6051]
        max connections = 25
        path = /srv/1/node/
        read only = false
        lock file = /var/lock/container6051.lock

        [container6061]
        max connections = 25
        path = /srv/2/node/
        read only = false
        lock file = /var/lock/container6061.lock

        [container6071]
        max connections = 25
        path = /srv/3/node/
        read only = false
        lock file = /var/lock/container6071.lock

        [container6081]
        max connections = 25
        path = /srv/4/node/
        read only = false
        lock file = /var/lock/container6081.lock

        [object6050]
        max connections = 25
        path = /srv/1/node/
        read only = false
        lock file = /var/lock/object6050.lock

        [object6060]
        max connections = 25
        path = /srv/2/node/
        read only = false
        lock file = /var/lock/object6060.lock

        [object6070]
        max connections = 25
        path = /srv/3/node/
        read only = false
        lock file = /var/lock/object6070.lock

        [object6080]
        max connections = 25
        path = /srv/4/node/
        read only = false
        lock file = /var/lock/object6080.lock

#. Restart rsync deamon::

        service rsync restart

#. Add changes in configuration files in directories:

   * /etc/swift/object-server(files: 1.conf, 2.conf, 3.conf, 4.conf)
   * /etc/swift/container-server(files: 1.conf, 2.conf, 3.conf, 4.conf)
   * /etc/swift/account-server(files: 1.conf, 2.conf, 3.conf, 4.conf)

   delete all configuration options in section [<*>-replicator]

#. Add configuration files for object-server, in /etc/swift/objec-server/

   * 5.conf::

        [DEFAULT]
        devices = /srv/1/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6050
        user = swift
        log_facility = LOG_LOCAL2
        recon_cache_path = /var/cache/swift

        [pipeline:main]
        pipeline = recon object-server

        [app:object-server]
        use = egg:swift#object
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [object-replicator]
        vm_test_mode = yes

   * 6.conf::

        [DEFAULT]
        devices = /srv/2/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6060
        user = swift
        log_facility = LOG_LOCAL3
        recon_cache_path = /var/cache/swift2

        [pipeline:main]
        pipeline = recon object-server

        [app:object-server]
        use = egg:swift#object
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [object-replicator]
        vm_test_mode = yes

   * 7.conf::

        [DEFAULT]
        devices = /srv/3/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6070
        user = swift
        log_facility = LOG_LOCAL4
        recon_cache_path = /var/cache/swift3

        [pipeline:main]
        pipeline = recon object-server

        [app:object-server]
        use = egg:swift#object
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [object-replicator]
        vm_test_mode = yes

   * 8.conf::

        [DEFAULT]
        devices = /srv/4/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6080
        user = swift
        log_facility = LOG_LOCAL5
        recon_cache_path = /var/cache/swift4

        [pipeline:main]
        pipeline = recon object-server

        [app:object-server]
        use = egg:swift#object
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [object-replicator]
        vm_test_mode = yes

#. Add configuration files for container-server, in /etc/swift/container-server/

   * 5.conf::

        [DEFAULT]
        devices = /srv/1/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6051
        user = swift
        log_facility = LOG_LOCAL2
        recon_cache_path = /var/cache/swift

        [pipeline:main]
        pipeline = recon container-server

        [app:container-server]
        use = egg:swift#container
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [container-replicator]
        vm_test_mode = yes

   * 6.conf::

        [DEFAULT]
        devices = /srv/2/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6061
        user = swift
        log_facility = LOG_LOCAL3
        recon_cache_path = /var/cache/swift2

        [pipeline:main]
        pipeline = recon container-server

        [app:container-server]
        use = egg:swift#container
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [container-replicator]
        vm_test_mode = yes

   * 7.conf::

        [DEFAULT]
        devices = /srv/3/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6071
        user = swift
        log_facility = LOG_LOCAL4
        recon_cache_path = /var/cache/swift3

        [pipeline:main]
        pipeline = recon container-server

        [app:container-server]
        use = egg:swift#container
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [container-replicator]
        vm_test_mode = yes

   * 8.conf::

        [DEFAULT]
        devices = /srv/4/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6081
        user = swift
        log_facility = LOG_LOCAL5
        recon_cache_path = /var/cache/swift4

        [pipeline:main]
        pipeline = recon container-server

        [app:container-server]
        use = egg:swift#container
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [container-replicator]
        vm_test_mode = yes

#. Add configuration files for account-server, in /etc/swift/account-server/

   * 5.conf::

        [DEFAULT]
        devices = /srv/1/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6052
        user = swift
        log_facility = LOG_LOCAL2
        recon_cache_path = /var/cache/swift

        [pipeline:main]
        pipeline = recon account-server

        [app:account-server]
        use = egg:swift#account
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [account-replicator]
        vm_test_mode = yes

   * 6.conf::

        [DEFAULT]
        devices = /srv/2/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6062
        user = swift
        log_facility = LOG_LOCAL3
        recon_cache_path = /var/cache/swift2

        [pipeline:main]
        pipeline = recon account-server

        [app:account-server]
        use = egg:swift#account
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [account-replicator]
        vm_test_mode = yes

   * 7.conf::

        [DEFAULT]
        devices = /srv/3/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6072
        user = swift
        log_facility = LOG_LOCAL4
        recon_cache_path = /var/cache/swift3

        [pipeline:main]
        pipeline = recon account-server

        [app:account-server]
        use = egg:swift#account
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [account-replicator]
        vm_test_mode = yes

   * 8.conf::

        [DEFAULT]
        devices = /srv/4/node
        mount_check = false
        disable_fallocate = true
        bind_port = 6082
        user = swift
        log_facility = LOG_LOCAL5
        recon_cache_path = /var/cache/swift4

        [pipeline:main]
        pipeline = recon account-server

        [app:account-server]
        use = egg:swift#account
        replication_server = True

        [filter:recon]
        use = egg:swift#recon

        [account-replicator]
        vm_test_mode = yes

---------------------------------
For a Multiple Server replication
---------------------------------

#. Move configuration file.

   * Configuration file for object-server from /etc/swift/object-server.conf to /etc/swift/object-server/1.conf

   * Configuration file for container-server from /etc/swift/container-server.conf to /etc/swift/container-server/1.conf

   * Configuration file for account-server from /etc/swift/account-server.conf to /etc/swift/account-server/1.conf

#. Add changes in configuration files in directories:

   * /etc/swift/object-server(files: 1.conf)
   * /etc/swift/container-server(files: 1.conf)
   * /etc/swift/account-server(files: 1.conf)

   delete all configuration options in section [<*>-replicator]

#. Add configuration files for object-server, in /etc/swift/object-server/2.conf::

        [DEFAULT]
        bind_ip = $STORAGE_LOCAL_NET_IP
        workers = 2

        [pipeline:main]
        pipeline = object-server

        [app:object-server]
        use = egg:swift#object
        replication_server = True

        [object-replicator]

#. Add configuration files for container-server, in /etc/swift/container-server/2.conf::

        [DEFAULT]
        bind_ip = $STORAGE_LOCAL_NET_IP
        workers = 2

        [pipeline:main]
        pipeline = container-server

        [app:container-server]
        use = egg:swift#container
        replication_server = True

        [container-replicator]

#. Add configuration files for account-server, in /etc/swift/account-server/2.conf::

        [DEFAULT]
        bind_ip = $STORAGE_LOCAL_NET_IP
        workers = 2

        [pipeline:main]
        pipeline = account-server

        [app:account-server]
        use = egg:swift#account
        replication_server = True

        [account-replicator]


text:
"""InvenioStats views."""

from elasticsearch.exceptions import NotFoundError
from flask import Blueprint, abort, jsonify, request
from invenio_rest.views import ContentNegotiatedMethodView

from .errors import InvalidRequestInputError, UnknownQueryError
from .proxies import current_stats
from .utils import current_user

blueprint = Blueprint(
    'invenio_stats',
    __name__,
    url_prefix='/stats',
)

class StatsQueryResource(ContentNegotiatedMethodView):
    """REST API resource providing access to statistics."""

    view_name = 'stat_query'

    def __init__(self, **kwargs):
        """Constructor."""
        super(StatsQueryResource, self).__init__(
            serializers={
                'application/json':
                lambda data, *args, **kwargs: jsonify(data),
            },
            default_method_media_type={
                'GET': 'application/json',
            },
            default_media_type='application/json',
            **kwargs)

    def post(self, **kwargs):
        """Get statistics."""
        data = request.get_json(force=False)
        if data is None:
            data = {}

        result = {}
        for query_name, config in data.items():
            if config is None or not isinstance(config, dict) \
                    or (set(config.keys()) != {'stat', 'params'} and
                        set(config.keys()) != {'stat'}):
                raise InvalidRequestInputError(
                    'Invalid Input. It should be of the form '
                    '{ STATISTIC_NAME: { "stat": STAT_TYPE, '
                    '"params": STAT_PARAMS }}'
                )
            stat = config['stat']
            params = config.get('params', {})
            try:
                query_cfg = current_stats.queries[stat]
            except KeyError:
                raise UnknownQueryError(stat)
            permission = current_stats.permission_factory(stat, params)
            if permission is not None and not permission.can():
                message = ('You do not have a permission to query the '
                           'statistic "{}" with those '
                           'parameters'.format(stat))
                if current_user.is_authenticated:
                    abort(403, message)
                abort(401, message)
            try:
                query = query_cfg.cls(name=query_name, **query_cfg.params)
                result[query_name] = query.run(**params)
            except ValueError as e:
                raise InvalidRequestInputError(e.args[0])
            except NotFoundError as e:
                # In case there is no index or value for the metric we return 0
                result[query_name] = dict.fromkeys(
                    query.metric_fields.keys(), 0)
        return self.make_response(result)

stats_view = StatsQueryResource.as_view(
    StatsQueryResource.view_name,
)

blueprint.add_url_rule(
    '',
    view_func=stats_view,
)