text:
package ca.lakeland.plantsd.flightlogger.Fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ListView;

import ca.lakeland.plantsd.flightlogger.Activities.ChecklistInfoActivity;
import ca.lakeland.plantsd.flightlogger.Activities.MainActivity;
import ca.lakeland.plantsd.flightlogger.Adapters.ChecklistAdapter;
import ca.lakeland.plantsd.flightlogger.Objects.DoneChecklist;
import ca.lakeland.plantsd.flightlogger.Objects.Storage;
import ca.lakeland.plantsd.flightlogger.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class ChecklistFragment extends Fragment {

    private ListView lvPreflightChecklists;
    private ChecklistAdapter customAdapter;
    Storage stor;

    public ChecklistFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_checklist, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        MainActivity main = (MainActivity)getActivity();
        stor = main.getStorage();

        if (stor.getDoneChecklists().size() <= 0) { // no checklists
            ViewStub noChecklistsStub = (ViewStub) main.findViewById(R.id.no_checklists_block);
            View inflated = noChecklistsStub.inflate();
        }

        lvPreflightChecklists = (ListView) getView().findViewById(R.id.lvPreflightChecklists);
        customAdapter = new ChecklistAdapter(main, R.layout.adapter_checklist_row, stor.getDoneChecklists());
        lvPreflightChecklists.setAdapter(customAdapter);
        lvPreflightChecklists.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Log.i("Hello THERE", "you clicked item: " + id + " at position: " + position);
                DoneChecklist dl = stor.getDoneChecklists().get(position);
                // Log.i("-----------------|", "that would be " + fl.getDate());
                Intent intent = new Intent(view.getContext(), ChecklistInfoActivity.class);
                intent.putExtra("DONE_CHECKLIST", dl);
                startActivity(intent);
            }
        });
    }

    public static void refresh(FragmentManager fragman) {
        ChecklistFragment fragment = new ChecklistFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction = fragman.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment, "CHECKLIST_FRAGMENT");
        fragmentTransaction.commit();
    }

}


text:
package com.base.engine.physics;

public enum ColliderType {
    SPHERE,
    AABB
}

redpajama_set_name: RedPajamaGithub


text:
module Braintree
  class WebhookNotificationGateway # :nodoc:
    def initialize(gateway)
      @gateway = gateway
      @config = gateway.config
    end

    def parse(signature_string, payload)
      _verify_signature(signature_string, payload)
      attributes = Xml.hash_from_xml(Base64.decode64(payload))
      WebhookNotification._new(@gateway, attributes[:notification])
    end

    def verify(challenge)
      digest = Braintree::Digest.hexdigest(@config.private_key, challenge)
      "#{@config.public_key}|#{digest}"
    end

    def _matching_signature_pair(signature_string)
      signature_pairs = signature_string.split("&")
      valid_pairs = signature_pairs.select { |pair| pair.include?("|") }.map { |pair| pair.split("|") }

      valid_pairs.detect do |public_key, signature|
        public_key == @config.public_key
      end
    end

    def _verify_signature(signature, payload)
      public_key, signature = _matching_signature_pair(signature)
      payload_signature = Braintree::Digest.hexdigest(@config.private_key, payload)

      raise InvalidSignature if public_key.nil?
      raise InvalidSignature unless Braintree::Digest.secure_compare(signature, payload_signature)
    end
  end
end


text:
package com.artech.prototype2.tsaplin.statistics;

import com.artech.prototype2.saver.dbo.AbstractSUBD;
import com.artech.prototype2.tsaplin.statistics.statisticholder.AbstractNgramStatistic;
import com.artech.prototype2.tsaplin.statistics.statisticholder.impl.*;

/**
 * Интерфейс сохранения статистики в базу данных.
 *
 * Created by User on 13.12.2014.
 */
public interface StatisticSaverToDB {
    /**
     * Сохранение русскоязычных одиночных слов в БД.
     * @param statistic
     * @param db
     */
    public void saveStatisticToDB(SingleWordRuStatisticImpl statistic, AbstractSUBD db);

    /**
     * Сохранение англоязычных одиночных слов в БД.
     * @param statistic
     * @param db
     */
    public void saveStatisticToDB(SingleWordEnStatisticImpl statistic, AbstractSUBD db);

    /**
     * Сохранение русскоязычных биграмм в БД.
     * @param statistic
     * @param db
     */
    public void saveStatisticToDB(BigramRuStatisticImpl statistic, AbstractSUBD db);

    /**
     * Сохранение англоязычных биграмм в БД.
     * @param statistic
     * @param db
     */
    public void saveStatisticToDB(BigramEnStatisticImpl statistic, AbstractSUBD db);

    /**
     * Сохранение русскоязычных триграмм в БД.
     * @param statistic
     * @param db
     */
    public void saveStatisticToDB(ThreegramRuStatisticImpl statistic, AbstractSUBD db);

    /**
     * Сохранение англоязычныых триграмм в БД.
     * @param statistic
     * @param db
     */
    public void saveStatisticToDB(ThreegramEnStatisticImpl statistic, AbstractSUBD db);

    /**
     * Сохранение русскоязычных форграмм в БД.
     * @param statistic
     * @param db
     */
    public void saveStatisticToDB(FourgramRuStatisticImpl statistic, AbstractSUBD db);

    /**
     * Сохранение англоязычных форграммв БД.
     * @param statistic
     * @param db
     */
    public void saveStatisticToDB(FourgramEnStatisticImpl statistic, AbstractSUBD db);
}


text:
using namespace std;
int main(int argc, char const *argv[]) {

	return 0;
}


text:
<?php
namespace CodingPride\Document;

use Doctrine\ODM\MongoDB\DocumentRepository;

/**
 * CommitRepository
 *
 */
class CommitRepository extends DocumentRepository
{
	/**
	 * Tries to save in database the given commit.
	 * If it's already there, it returns false.
	 *
	 * @param Commit $commit The commit to create
	 * @return mixed $commit The commit that just created
	 */
	public function create( Commit $commit )
	{
		$commit_from_database = $this->findOneBy( array( 'revision' => $commit->getRevision() ) );

		if ( !empty( $commit_from_database ) )
		{
			return false;
		}

		$user_repository	= $this->dm->getRepository( '\CodingPride\Document\User' );
		$author				= $user_repository->create( $commit->getAuthorUsername() );
		$commit->setAuthor( $author );

		$this->dm->persist( $commit );
		$this->dm->flush();

		return $commit;
	}
}


text:
"""
Debugging features in in the template.
"""
__author__ = "Diederik van der Boor"
__license__ = "Apache License, Version 2"

# Objects
from django.template import Library, Node, Variable
from django.db.models.query import QuerySet
from django.forms.forms import BoundField

# Util functions
from django.core.serializers import serialize
from django.template.defaultfilters import linebreaksbr
from django.utils.encoding import smart_str
from django.utils.html import escape, mark_safe
from pprint import pformat
from itertools import chain

register = Library()

class PrintNode(Node):
    def __init__(self, varnames):
        # Thread safety OK: the list of varnames won't change for this node.
        # Data is read only inside the render() function.
        self.variables = dict( (v,Variable(v)) for v in varnames )

    def render(self, context):
        text = ''
        if self.variables:
            for name, var in self.variables.iteritems():
                data = var.resolve(context)
                textdata = linebreaksbr(escape(_dump_var(data)))
                if isinstance(data, (bool,int,basestring,float)):
                    text += "
%s = %s
" % (name, textdata)
                else:
                    text += "
%s = %s...\n%s
" % (name, data.__class__.__name__, textdata)
        else:
            text = '
Template context scope:
\n'
            for i, part in enumerate(context):
                text += "
%i: %s
" % (i, linebreaksbr(escape(_dump_var(part))))

        return mark_safe(text)

@register.tag('print')
def _print(parser, token):
    """
    A template tag which prints dumps the contents of objects.
    """
    varnames = token.contents.split()
    return PrintNode(varnames[1:])

# ---- Internal print helper ----

def _dump_var(object):
    """
    A variable dumper to generate sensible output for template context fields.
    """
    if isinstance(object, QuerySet):
        text = serialize('python', object)
    elif isinstance(object, basestring):
        text = repr(object)
    else:
        if hasattr(object, '__dict__'):
            # Instead of just printing <SomeType at 0xfoobar>, expand the fields
            # Construct a dictionary that will be passed to pformat()

            all_attrs = object.__dict__.iteritems()
            if object.__class__:
                # Add class members too.
                all_attrs = chain(all_attrs, object.__class__.__dict__.iteritems())

            attrs = dict((k, v) for k, v in all_attrs if not k.startswith('_'))

            # Format property objects
            for name, value in attrs.iteritems():
                if isinstance(value, property):
                    try:
                        attrs[name] = getattr(object, name)
                    except (TypeError, AttributeError), e:
                        attrs[name] = e

            # Include representations which are relevant in template context.
            attrs['__str__'] = smart_str(object)  # smart_str() avoids crashes because of unicode chars.
            if hasattr(object, '__iter__'):
                attrs['__iter__'] = '__ITER__'
            if hasattr(object, '__getitem__'):
                attrs['__getitem__'] = '...'

            # Enrich members with values from dir (e.g. add auto_id)
            for member in dir(object):
                if member.startswith('_') or not hasattr(object, member):
                    continue

                value = getattr(object, member)
                if callable(value) or attrs.has_key(member):
                    continue

                attrs[member] = value

            _format_values(attrs)
            object = attrs

        elif isinstance(object, dict):
            object = object.copy()
            _format_values(object)

        try:
            text = pformat(object)
        except Exception, e:
            text = "<caught %s while rendering: %s>" % (e.__class__.__name__, str(e) or "<no msg>")

        text = text.replace("'__ITER__'", '<iterator object>')
        text = text.replace("<django.utils.functional.__proxy__ object", '<proxy object')

    return text

def _format_values(attrs):
    # Format some values for better display
    for name, value in attrs.iteritems():
        if isinstance(value, BoundField):
            attrs[name] = str(value) + "???"
        elif isinstance(value, Node):
            # The Block node is very verbose, making debugging hard.
            attrs[name] = "<Block Node: %s, ...>" % value.name


text:
from framework.dependency_management.dependency_resolver import ServiceLocator

"""
GREP Plugin for Cookies Attributes
NOTE: GREP plugins do NOT send traffic to the target and only grep the HTTP Transaction Log
"""

import string, re
import cgi
import logging

DESCRIPTION = "Searches transaction DB for Cookie attributes"

def run(PluginInfo):
    # ServiceLocator.get_component("config").Show()
    plugin_helper = ServiceLocator.get_component("plugin_helper")
    Content = plugin_helper.HtmlString("This plugin looks for cookie setting headers (TODO: Check vuln scanners' output!)<br />")
    Content += plugin_helper.FindResponseHeaderMatchesForRegexpName('HEADERS_FOR_COOKIES')
    # TODO: Fix up
    # AttributeAnalysis = ServiceLocator.get_component("plugin_helper").CookieAttributeAnalysis(AllValues, Header2TransacDict)
    return Content


text:
package com.javarush.task.task28.task2811;

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteMap<K, V> {
    private final Map<K, V> map;
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();

    public ReadWriteMap(Map<K, V> map) {
        this.map = map;
    }

    public V put(K key, V value) {
        try {
            writeLock.lock();
            return map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }

    public V get(K key) {
        try {
            readLock.lock();
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }
}


text:
package com.google.javascript.jscomp;

import com.google.javascript.rhino.Node;

/**
 * This interface defines how objects capable of creating scopes from the parse
 * tree behave.
 *
*
 */
interface ScopeCreator {
  /**
   * Creates a {@link Scope} object.
   *
   * @param n the root node (either a FUNCTION node, a SCRIPT node, or a
   *    synthetic block node whose children are all SCRIPT nodes)
   * @param parent the parent Scope object (may be null)
   */
  Scope createScope(Node n, Scope parent);
}


text:
package header

import "container/list"

/**
 * The Server header field contains information about the software used by
 * the UAS to handle the request. Revealing the specific software version of
 * the server might allow the server to become more vulnerable to attacks
 * against software that is known to contain security holes. Implementers
 * SHOULD make the Server header field a configurable option. If the Response
 * is being forwarded through a proxy, the proxy application must not modify
 * the ServerHeaders. Instead, it should include a ViaHeader.
 *

 * For Example:

 * Server: HomeServer v2
 *
 * @see ViaHeader
 * @see UserAgentHeader
 */
type ServerHeader interface {
	Header

	/**
	 * Returns a ListIterator over the List of product values.
	 *
	 * @return a ListIterator over the List of strings identifying the
	 * software of this ServerHeader
	 */
	GetProduct() *list.List

	/**
	 * Sets the List of product values of the ServerHeader.
	 *
	 * @param product - a List of Strings specifying the product values
	 * @throws ParseException which signals that an error has been reached
	 * unexpectedly while parsing the List of product value strings.
	 */
	SetProduct(product *list.List) (ParseException error)
}


text:
#include <aws/ec2/model/InstanceNetworkInterface.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace EC2
{
namespace Model
{

InstanceNetworkInterface::InstanceNetworkInterface() :
    m_networkInterfaceIdHasBeenSet(false),
    m_subnetIdHasBeenSet(false),
    m_vpcIdHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_ownerIdHasBeenSet(false),
    m_statusHasBeenSet(false),
    m_macAddressHasBeenSet(false),
    m_privateIpAddressHasBeenSet(false),
    m_privateDnsNameHasBeenSet(false),
    m_sourceDestCheck(false),
    m_sourceDestCheckHasBeenSet(false),
    m_groupsHasBeenSet(false),
    m_attachmentHasBeenSet(false),
    m_associationHasBeenSet(false),
    m_privateIpAddressesHasBeenSet(false)
{
}

InstanceNetworkInterface::InstanceNetworkInterface(const XmlNode& xmlNode) :
    m_networkInterfaceIdHasBeenSet(false),
    m_subnetIdHasBeenSet(false),
    m_vpcIdHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_ownerIdHasBeenSet(false),
    m_statusHasBeenSet(false),
    m_macAddressHasBeenSet(false),
    m_privateIpAddressHasBeenSet(false),
    m_privateDnsNameHasBeenSet(false),
    m_sourceDestCheck(false),
    m_sourceDestCheckHasBeenSet(false),
    m_groupsHasBeenSet(false),
    m_attachmentHasBeenSet(false),
    m_associationHasBeenSet(false),
    m_privateIpAddressesHasBeenSet(false)
{
  *this = xmlNode;
}

InstanceNetworkInterface& InstanceNetworkInterface::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode networkInterfaceIdNode = resultNode.FirstChild("networkInterfaceId");
    if(!networkInterfaceIdNode.IsNull())
    {
      m_networkInterfaceId = StringUtils::Trim(networkInterfaceIdNode.GetText().c_str());
      m_networkInterfaceIdHasBeenSet = true;
    }
    XmlNode subnetIdNode = resultNode.FirstChild("subnetId");
    if(!subnetIdNode.IsNull())
    {
      m_subnetId = StringUtils::Trim(subnetIdNode.GetText().c_str());
      m_subnetIdHasBeenSet = true;
    }
    XmlNode vpcIdNode = resultNode.FirstChild("vpcId");
    if(!vpcIdNode.IsNull())
    {
      m_vpcId = StringUtils::Trim(vpcIdNode.GetText().c_str());
      m_vpcIdHasBeenSet = true;
    }
    XmlNode descriptionNode = resultNode.FirstChild("description");
    if(!descriptionNode.IsNull())
    {
      m_description = StringUtils::Trim(descriptionNode.GetText().c_str());
      m_descriptionHasBeenSet = true;
    }
    XmlNode ownerIdNode = resultNode.FirstChild("ownerId");
    if(!ownerIdNode.IsNull())
    {
      m_ownerId = StringUtils::Trim(ownerIdNode.GetText().c_str());
      m_ownerIdHasBeenSet = true;
    }
    XmlNode statusNode = resultNode.FirstChild("status");
    if(!statusNode.IsNull())
    {
      m_status = NetworkInterfaceStatusMapper::GetNetworkInterfaceStatusForName(StringUtils::Trim(statusNode.GetText().c_str()).c_str());
      m_statusHasBeenSet = true;
    }
    XmlNode macAddressNode = resultNode.FirstChild("macAddress");
    if(!macAddressNode.IsNull())
    {
      m_macAddress = StringUtils::Trim(macAddressNode.GetText().c_str());
      m_macAddressHasBeenSet = true;
    }
    XmlNode privateIpAddressNode = resultNode.FirstChild("privateIpAddress");
    if(!privateIpAddressNode.IsNull())
    {
      m_privateIpAddress = StringUtils::Trim(privateIpAddressNode.GetText().c_str());
      m_privateIpAddressHasBeenSet = true;
    }
    XmlNode privateDnsNameNode = resultNode.FirstChild("privateDnsName");
    if(!privateDnsNameNode.IsNull())
    {
      m_privateDnsName = StringUtils::Trim(privateDnsNameNode.GetText().c_str());
      m_privateDnsNameHasBeenSet = true;
    }
    XmlNode sourceDestCheckNode = resultNode.FirstChild("sourceDestCheck");
    if(!sourceDestCheckNode.IsNull())
    {
      m_sourceDestCheck = StringUtils::ConvertToBool(StringUtils::Trim(sourceDestCheckNode.GetText().c_str()).c_str());
      m_sourceDestCheckHasBeenSet = true;
    }
    XmlNode groupsNode = resultNode.FirstChild("groupSet");
    if(!groupsNode.IsNull())
    {
      XmlNode groupsMember = groupsNode.FirstChild("item");
      while(!groupsMember.IsNull())
      {
        m_groups.push_back(groupsMember);
        groupsMember = groupsMember.NextNode("item");
      }

      m_groupsHasBeenSet = true;
    }
    XmlNode attachmentNode = resultNode.FirstChild("attachment");
    if(!attachmentNode.IsNull())
    {
      m_attachment = attachmentNode;
      m_attachmentHasBeenSet = true;
    }
    XmlNode associationNode = resultNode.FirstChild("association");
    if(!associationNode.IsNull())
    {
      m_association = associationNode;
      m_associationHasBeenSet = true;
    }
    XmlNode privateIpAddressesNode = resultNode.FirstChild("privateIpAddressesSet");
    if(!privateIpAddressesNode.IsNull())
    {
      XmlNode privateIpAddressesMember = privateIpAddressesNode.FirstChild("item");
      while(!privateIpAddressesMember.IsNull())
      {
        m_privateIpAddresses.push_back(privateIpAddressesMember);
        privateIpAddressesMember = privateIpAddressesMember.NextNode("item");
      }

      m_privateIpAddressesHasBeenSet = true;
    }
  }

  return *this;
}

void InstanceNetworkInterface::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_networkInterfaceIdHasBeenSet)
  {
      oStream << location << index << locationValue << ".NetworkInterfaceId=" << StringUtils::URLEncode(m_networkInterfaceId.c_str()) << "&";
  }

  if(m_subnetIdHasBeenSet)
  {
      oStream << location << index << locationValue << ".SubnetId=" << StringUtils::URLEncode(m_subnetId.c_str()) << "&";
  }

  if(m_vpcIdHasBeenSet)
  {
      oStream << location << index << locationValue << ".VpcId=" << StringUtils::URLEncode(m_vpcId.c_str()) << "&";
  }

  if(m_descriptionHasBeenSet)
  {
      oStream << location << index << locationValue << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&";
  }

  if(m_ownerIdHasBeenSet)
  {
      oStream << location << index << locationValue << ".OwnerId=" << StringUtils::URLEncode(m_ownerId.c_str()) << "&";
  }

  if(m_statusHasBeenSet)
  {
      oStream << location << index << locationValue << ".Status=" << NetworkInterfaceStatusMapper::GetNameForNetworkInterfaceStatus(m_status) << "&";
  }

  if(m_macAddressHasBeenSet)
  {
      oStream << location << index << locationValue << ".MacAddress=" << StringUtils::URLEncode(m_macAddress.c_str()) << "&";
  }

  if(m_privateIpAddressHasBeenSet)
  {
      oStream << location << index << locationValue << ".PrivateIpAddress=" << StringUtils::URLEncode(m_privateIpAddress.c_str()) << "&";
  }

  if(m_privateDnsNameHasBeenSet)
  {
      oStream << location << index << locationValue << ".PrivateDnsName=" << StringUtils::URLEncode(m_privateDnsName.c_str()) << "&";
  }

  if(m_sourceDestCheckHasBeenSet)
  {
      oStream << location << index << locationValue << ".SourceDestCheck=" << m_sourceDestCheck << "&";
  }

  if(m_groupsHasBeenSet)
  {
      unsigned groupsIdx = 1;
      for(auto& item : m_groups)
      {
        Aws::StringStream groupsSs;
        groupsSs << location << index << locationValue << ".GroupSet." << groupsIdx++;
        item.OutputToStream(oStream, groupsSs.str().c_str());
      }
  }

  if(m_attachmentHasBeenSet)
  {
      Aws::StringStream attachmentLocationAndMemberSs;
      attachmentLocationAndMemberSs << location << index << locationValue << ".Attachment";
      m_attachment.OutputToStream(oStream, attachmentLocationAndMemberSs.str().c_str());
  }

  if(m_associationHasBeenSet)
  {
      Aws::StringStream associationLocationAndMemberSs;
      associationLocationAndMemberSs << location << index << locationValue << ".Association";
      m_association.OutputToStream(oStream, associationLocationAndMemberSs.str().c_str());
  }

  if(m_privateIpAddressesHasBeenSet)
  {
      unsigned privateIpAddressesIdx = 1;
      for(auto& item : m_privateIpAddresses)
      {
        Aws::StringStream privateIpAddressesSs;
        privateIpAddressesSs << location << index << locationValue << ".PrivateIpAddressesSet." << privateIpAddressesIdx++;
        item.OutputToStream(oStream, privateIpAddressesSs.str().c_str());
      }
  }

}

void InstanceNetworkInterface::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_networkInterfaceIdHasBeenSet)
  {
      oStream << location << ".NetworkInterfaceId=" << StringUtils::URLEncode(m_networkInterfaceId.c_str()) << "&";
  }
  if(m_subnetIdHasBeenSet)
  {
      oStream << location << ".SubnetId=" << StringUtils::URLEncode(m_subnetId.c_str()) << "&";
  }
  if(m_vpcIdHasBeenSet)
  {
      oStream << location << ".VpcId=" << StringUtils::URLEncode(m_vpcId.c_str()) << "&";
  }
  if(m_descriptionHasBeenSet)
  {
      oStream << location << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&";
  }
  if(m_ownerIdHasBeenSet)
  {
      oStream << location << ".OwnerId=" << StringUtils::URLEncode(m_ownerId.c_str()) << "&";
  }
  if(m_statusHasBeenSet)
  {
      oStream << location << ".Status=" << NetworkInterfaceStatusMapper::GetNameForNetworkInterfaceStatus(m_status) << "&";
  }
  if(m_macAddressHasBeenSet)
  {
      oStream << location << ".MacAddress=" << StringUtils::URLEncode(m_macAddress.c_str()) << "&";
  }
  if(m_privateIpAddressHasBeenSet)
  {
      oStream << location << ".PrivateIpAddress=" << StringUtils::URLEncode(m_privateIpAddress.c_str()) << "&";
  }
  if(m_privateDnsNameHasBeenSet)
  {
      oStream << location << ".PrivateDnsName=" << StringUtils::URLEncode(m_privateDnsName.c_str()) << "&";
  }
  if(m_sourceDestCheckHasBeenSet)
  {
      oStream << location << ".SourceDestCheck=" << m_sourceDestCheck << "&";
  }
  if(m_groupsHasBeenSet)
  {
      unsigned groupsIdx = 1;
      for(auto& item : m_groups)
      {
        Aws::StringStream groupsSs;
        groupsSs << location <<  ".item." << groupsIdx++;
        item.OutputToStream(oStream, groupsSs.str().c_str());
      }
  }
  if(m_attachmentHasBeenSet)
  {
      Aws::String attachmentLocationAndMember(location);
      attachmentLocationAndMember += ".Attachment";
      m_attachment.OutputToStream(oStream, attachmentLocationAndMember.c_str());
  }
  if(m_associationHasBeenSet)
  {
      Aws::String associationLocationAndMember(location);
      associationLocationAndMember += ".Association";
      m_association.OutputToStream(oStream, associationLocationAndMember.c_str());
  }
  if(m_privateIpAddressesHasBeenSet)
  {
      unsigned privateIpAddressesIdx = 1;
      for(auto& item : m_privateIpAddresses)
      {
        Aws::StringStream privateIpAddressesSs;
        privateIpAddressesSs << location <<  ".item." << privateIpAddressesIdx++;
        item.OutputToStream(oStream, privateIpAddressesSs.str().c_str());
      }
  }
}

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
var assert = require("assert");
var path = require("path");
var Promise = require("nodegit-promise");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));

var exec = promisify(function(command, opts, callback) {
  return require("child_process").exec(command, opts, callback);
});

describe("Stage", function() {
  var RepoUtils = require("../utils/repository_setup");
  var NodeGit = require("../../");
	var test;

  beforeEach(function() {
    test = this;
		var repoDir = "../repos/stagingRepo/";
    var repoPath = path.resolve(__dirname, repoDir);

    return RepoUtils.createRepository(repoPath)
      .then(function(repo) {
        test.repository = repo;
        return repo.openIndex();
      })
      .then(function(index) {
        test.index = index;
      });
  });

  after(function() {
		return fse.remove(test.repository.workdir());
  });

function stagingTest(staging, newFileContent) {
    var fileContent = newFileContent ||
                      "One line of text\n" +
                      "Two lines of text\n"+
                      "Three lines of text\n"+
                      "Four lines of text\n"+
                      "Five lines of text\n"+
                      "Six lines of text\n"+
                      "Seven lines of text\n"+
                      "Eight lines of text\n"+
                      "Nine lines of text\n"+
                      "Ten lines of text\n"+
                      "Eleven lines of text\n"+
                      "Twelve lines of text\n"+
                      "Thirteen lines of text\n"+
                      "Fourteen lines of text\n"+
                      "Fifteen lines of text\n"+
                      "Sixteen lines of text\n"+
                      "Seventeen lines of text\n"+
                      "Eighteen lines of text\n"+
                      "Nineteen lines of text\n"+
                      "Twenty lines of text\n";
    var fileName = "stagedLinesTest.txt";
    var index;
    var stagedFile;
    var workingDirFile;
    var getDiffFunction;
    if (staging) {
      stagedFile = fileContent.replace("Fifteen", "Changed fifteen");
      workingDirFile = stagedFile.replace("Three", "Changed three")
                            .replace("Seventeen", "Changed seventeen");
      getDiffFunction = function() {
        return NodeGit.Diff.indexToWorkdir(test.repository, index, {
            flags:
              NodeGit.Diff.OPTION.SHOW_UNTRACKED_CONTENT |
              NodeGit.Diff.OPTION.RECURSE_UNTRACKED_DIRS
          });
      };
    }
    else {
      stagedFile = fileContent.replace("Three", "Changed three")
                            .replace("Seventeen", "Changed seventeen");
      workingDirFile = stagedFile.replace("Fifteen", "Changed fifteen");

      getDiffFunction = function() {
        return RepoUtils.addFileToIndex(test.repository, fileName)
          .then(function() {
            return test.repository.getBranchCommit("master");
          })
          .then(function(masterCommit) {
            return masterCommit.getTree();
          })
          .then(function(masterTree) {
            return NodeGit.Diff.treeToIndex(
              test.repository, masterTree, index, {
              flags:
                NodeGit.Diff.OPTION.SHOW_UNTRACKED_CONTENT |
                NodeGit.Diff.OPTION.RECURSE_UNTRACKED_DIRS
            });
          });
      };
    }

    return RepoUtils.commitFileToRepo(test.repository, fileName, fileContent)
    .then(function() {
      return fse.writeFile(path.join(test.repository.workdir(), fileName),
                            workingDirFile);
    })
    .then(function() {
      return test.repository.openIndex();
    })
    .then(function(repoIndex) {
      index = repoIndex;
      return getDiffFunction();
    })
    .then(function(fileDiff) {
      return fileDiff.patches();
    })
    .then(function(patches) {
      var pathPatch = patches.filter(function(patch) {
        return patch.newFile().path() === fileName;
      });
      return pathPatch[0].hunks();
    })
    .then(function(pathHunks) {
      var linePromises = [];

      pathHunks.forEach(function(pathHunk) {
        linePromises.push(pathHunk.lines());
      });

      return Promise.all(linePromises);
    })
    .then(function(lines) {
      var linesToStage = [];
      lines.forEach(function(hunkLines) {
        hunkLines.forEach(function(line) {
          if (line.content().toLowerCase().indexOf("fifteen") >= 0){
            linesToStage.push(line);
          }
        });
      });
      return test.repository.stageLines(fileName, linesToStage, !staging);
    })
    .then(function(stageResult) {
      assert.equal(stageResult, 0);
      var pathOid = index.getByPath(fileName).id;
      return test.repository.getBlob(pathOid);
    })
    .then(function(resultFileContents) {
      assert.equal(resultFileContents.toString(), stagedFile);
    });
  }

  it("can stage selected lines", function() {
    return stagingTest(true);
  });
  it("can unstage selected lines", function() {
    return stagingTest(false);
  });

  //This is used to test cases where there are no newline at EOF
  var newlineEofTestFileContent =
                  "One line of text\n" +
                  "Two lines of text\n"+
                  "Three lines of text\n"+
                  "Four lines of text\n"+
                  "Five lines of text\n"+
                  "Six lines of text\n"+
                  "Seven lines of text\n"+
                  "Eight lines of text\n"+
                  "Nine lines of text\n"+
                  "Ten lines of text\n"+
                  "Eleven lines of text\n"+
                  "Twelve lines of text\n"+
                  "Thirteen lines of text\n"+
                  "Fourteen lines of text\n"+
                  "Fifteen lines of text";
  it("can stage last line with no newline at EOF", function() {
    return stagingTest(true, newlineEofTestFileContent);
  });
  it("can unstage last line with no newline at EOF", function() {
    return stagingTest(false, newlineEofTestFileContent);
  });
  it("can stage second to last line with no newline at EOF", function() {
    var newlineEofTestFileContent2 = newlineEofTestFileContent +
     "\nSixteen lines of text\nSeventeen lines of text\nEighteen lines of text";
    return stagingTest(true, newlineEofTestFileContent2);
  });
  it("can unstage second to last line with no newline at EOF", function() {
    var newlineEofTestFileContent2 = newlineEofTestFileContent +
     "\nSixteen lines of text\nSeventeen lines of text\nEighteen lines of text";
    return stagingTest(false, newlineEofTestFileContent2);
  });

  //This is used to test case where the last hunk is staged.
  var lastHunkStagedFileContent =
                "Thirteen lines of text\n"+
                "Fourteen lines of text\n"+
                "Fifteen lines of text\n"+
                "Sixteen lines of text\n"+
                "Shforteenteen lines of text\n";

  it("staging last hunk stages whole file if no filemode changes", function() {
    return stagingTest(true, lastHunkStagedFileContent)
      .then(function() {
        return test.repository.openIndex();
      })
      .then(function(index) {
        return NodeGit.Diff.indexToWorkdir(test.repository, index, {
            flags:
              NodeGit.Diff.OPTION.SHOW_UNTRACKED_CONTENT |
              NodeGit.Diff.OPTION.RECURSE_UNTRACKED_DIRS
          });
      })
      .then(function(diff) {
        assert.equal(Object.keys(diff).length, 0);  //Empty diff
        return diff.patches();
      })
      .then(function(patches) {
        //patches will have at least one item if there is something unstaged
        assert.equal(patches.length, 0);
      });
  });

  function compareFilemodes(vsWorkdir, index, fileModeDifference) {
    //Takes diff of head commit vs Workdir (if vsWorkdir is set) or vs Index
    //(if vsWorkdir is unset). Note: there's only one file in the filemode
    //staging tests for which this helper fn was written.
    //index - index to use (vsWorkdir is unset)
    //fileModeDifference - expected (newfilemode) - (oldfilemode)
    return test.repository.getHeadCommit()
      .then(function(commit) {
        return commit.getTree();
      })
      .then(function(tree) {
        if (vsWorkdir) {
          return NodeGit.Diff.treeToWorkdir(test.repository, tree);
        } else {
          return NodeGit.Diff.treeToIndex(test.repository, tree, index);
        }
      })
      .then(function(diff) {
        return diff.getDelta(0);
      })
      .then(function(delta) {
        if (fileModeDifference === 0) {
          if (!delta) {
            return true;
          } else {
            throw ("File change when no file change expected.");
          }
        } else {
          assert(delta.newFile().mode() - delta.oldFile().mode() ===
            fileModeDifference);
        }
        return true;
      });
  }

  if (process.platform == "linux" || process.platform == "darwin") {
    it("can stage filemode changes", function() {
      var fileContent = "Blek";
      var fileName = "stageFilemodeTest.txt";
      var index;

      return RepoUtils.commitFileToRepo(test.repository, fileName, fileContent)
      .then(function() {
        //First, create a file, have the same file in both the repo and workdir.
        return fse.writeFile(path.join(test.repository.workdir(), fileName),
                              fileContent)
          .then(function() {
            //Then, change the permission locally.
            return fse.chmod(path.join(test.repository.workdir(), fileName),
              0755 /* new filemode */);
          });
      })
      //Then, diff between head commit and workdir should have filemode change
      .then(function() {
        return compareFilemodes(true, null, 0111 /* expect +x */)
          .then(function() {
            return test.repository.stageFilemode(fileName, true);
          });
      })
      //Now lets do a commit...
      .then(function() {
        return test.repository.openIndex();
      })
      .then(function(repoIndex) {
        index = repoIndex;
        index.read(1);
        return index.writeTree();
      })
      .then(function (oid) {
        var signature = NodeGit.Signature.create("Foo bar",
          "foo@bar.com", 123456789, 60);
        return test.repository.createCommit("HEAD", signature, signature,
            "initial commit", oid, []);
        //... alright, we did a commit.
      })
      //Now if we compare head commit to index, should be a filemode change
      .then(function() {
        return compareFilemodes(false, index, 0111 /* expect +x */);
      });
    });

    it("can unstage filemode changes", function() {
      var fileContent = "Blek";
      var fileName = "stageFilemodeTest2.txt";
      var index;

      return RepoUtils.commitFileToRepo(test.repository, fileName, fileContent)
      .then(function() {
        //First, create a file, have the same file in both the repo and workdir.
        return fse.writeFile(path.join(test.repository.workdir(), fileName),
                              fileContent)
          .then(function() {
            //Then, change the permission locally.
            return fse.chmod(path.join(test.repository.workdir(), fileName),
              0755 /* new filemode */);
          });
      })
      //Then, diff between head commit and workdir should have filemode change
      .then(function() {
        return compareFilemodes(true, null, 0111 /* expect +x */);
      })
      .then(function() {
        return test.repository.openIndex();
      })
      .then(function(repoIndex) {
        //Now we stage the whole file...
        index = repoIndex;
        index.addByPath(fileName);
        return index.write();
      })
      .then(function() {
        //We expect the Index to have the filemode changes now.
        return compareFilemodes(false, index, 0111 /* expect +x */)
          .then(function() {
            //...then we attempt to unstage filemode
            return test.repository.stageFilemode(fileName, false /* unstage */);
          });
      })
      //We expect the Index to have no filemode changes, since we unstaged.
      .then(function() {
        return compareFilemodes(false, index, 0 /* expect +x */);
      })
      //We also expect the workdir to now have the filemode change.
      .then(function() {
        return compareFilemodes(true, null, 0111 /* expect +x */);
      });
    });
  } else if (process.platform == "win32") {
    it("can stage/unstage filemode changes", function() {
      var fileContent = "Blek";
      var fileName = "stageFilemodeTest.txt";
      var index;

      return RepoUtils.commitFileToRepo(test.repository, fileName, fileContent)
      .then(function() {
        //First, create a file, have the same file in both the repo and workdir.
        return fse.writeFile(path.join(test.repository.workdir(), fileName),
                              fileContent)
          .then(function() {
            //Then, change the permission on index
            return exec("git update-index --chmod=+x " + fileName,
              {cwd: test.repository.workdir()});
          })
          .then(function() {
          //Then, change the permission on index
          return exec("git commit -m 'test'",
            {cwd: test.repository.workdir()});
          })
          .then(function() {
          //Then, change the permission on index
          return exec("git update-index --chmod=-x " + fileName,
            {cwd: test.repository.workdir()});
          });
      })
      .then(function() {
        return test.repository.openIndex();
      })
      .then(function(repoIndex) {
        index = repoIndex;
        //Head commit vs index
        //We expect the Index to have +x
        return compareFilemodes(false, index, -0111 /* expect +x */);
      })
      .then(function() {
        //...then we attempt to unstage filemode
        return test.repository.stageFilemode(fileName, false /* unstage */);
      })
      .then(function() {
        return compareFilemodes(false, index, 0 /* expect nochange */);
      });
    });
  }

});


text:
"""

"""
import py

def cmdexec(cmd):
    import os, sys
    import subprocess

    from subprocess import Popen, PIPE
    """ return unicode output of executing 'cmd' in a separate process.

    raise cmdexec.Error exeception if the command failed.
    the exception will provide an 'err' attribute containing
    the error-output from the command.
    if the subprocess module does not provide a proper encoding/unicode strings
    sys.getdefaultencoding() will be used, if that does not exist, 'UTF-8'.
    """
    process = subprocess.Popen(cmd, shell=True,
            universal_newlines=True,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = process.communicate()
    if sys.version_info[0] < 3: # on py3 we get unicode strings, on py2 not
        try:
            default_encoding = sys.getdefaultencoding() # jython may not have it
        except AttributeError:
            default_encoding = sys.stdout.encoding or 'UTF-8'
        out = unicode(out, process.stdout.encoding or default_encoding)
        err = unicode(err, process.stderr.encoding or default_encoding)
    status = process.poll()
    if status:
        raise ExecutionFailed(status, status, cmd, out, err)
    return out

class ExecutionFailed(py.error.Error):
    def __init__(self, status, systemstatus, cmd, out, err):
        Exception.__init__(self)
        self.status = status
        self.systemstatus = systemstatus
        self.cmd = cmd
        self.err = err
        self.out = out

    def __str__(self):
        return "ExecutionFailed: %d  %s\n%s" %(self.status, self.cmd, self.err)

# export the exception under the name 'py.process.cmdexec.Error'
cmdexec.Error = ExecutionFailed
try:
    ExecutionFailed.__module__ = 'py.process.cmdexec'
    ExecutionFailed.__name__ = 'Error'
except (AttributeError, TypeError):
    pass


text:
<!DOCTYPE html>

<title>Attack of Buddha</title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta property="og:title" content="Attack of Buddha">
<meta property="og:description" content="Move Buddha to crush green guys. Don't crush red guys. Game is over if miss reaches 50.">
<meta property="og:type" content="article">
<meta property="og:url" content="https://obono.github.io/Pico8Works/buddha.html">
<meta property="og:image" content="https://obono.github.io/Pico8Works/img/thumb_buddha.png">
<meta property="og:site_name" content="OBONO's PICO-8 Works">

<meta name="twitter:card" content="player">
<meta name="twitter:site" content="@OBONO">
<meta name="twitter:title" content="Attack of Buddha">
<meta name="twitter:description" content="Move Buddha to crush green guys. Don't crush red guys. Game is over if miss reaches 50.">
<meta name="twitter:player" content="https://obono.github.io/Pico8Works/buddha.html?canvas_only">
<meta name="twitter:player:width" content="256">
<meta name="twitter:player:height" content="256">
<meta name="twitter:image" content="https://obono.github.io/Pico8Works/img/thumb_buddha.png">

<meta name="my:version" content="0.30">
<meta name="my:release_date" content="Oct 27, 2015">
<meta name="my:instruction" content="Î×:Start/Retry game,ËÑ:Move Buddha">
<meta name="my:source_url" content="https://github.com/obono/Pico8Works/blob/master/src/buddha.p8">
<meta name="my:thread_url" content="http://www.lexaloffle.com/bbs/?tid=2671">

<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/style_canvas_only.css" disabled="true" id="canvas_only">
<link rel="shortcut icon" type="image/vnd.microsoft.icon" href="img/favicon.ico">
<link rel="icon" type="image/gif" href="img/favicon_anim.gif" sizes="16x16">

<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()"></canvas>


text:
package edu.isi.karma.controller.update;

import java.io.PrintWriter;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.isi.karma.view.VWorkspace;

public class NewDatabaseCommandUpdate extends AbstractUpdate{
	private String commandId;
	private static Logger logger = LoggerFactory.getLogger(NewDatabaseCommandUpdate.class);

	public enum JsonKeys {
		commandId
	}

	public NewDatabaseCommandUpdate(String commandId) {
		this.commandId = commandId;
	}

	@Override
	public void generateJson(String prefix, PrintWriter pw,
			VWorkspace vWorkspace) {
		JSONObject responseObj = new JSONObject();
		try {
			responseObj.put(JsonKeys.commandId.name(), commandId);
			responseObj.put(GenericJsonKeys.updateType.name(), "NewImportDatabaseTableCommandUpdate");
			pw.print(responseObj.toString(4));
		} catch (JSONException e) {
			logger.error("Error generating JSON!", e);
		}
	}

}


text:
package com.microsoft.azure.management.recoveryservices.backup.v2016_06_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * This object filters the list of backup items.
 */
public class GetProtectedItemQueryObject {
    /**
     * Specifies if the additional information should be provided for this
     * item.
     */
    @JsonProperty(value = "expand")
    private String expand;

    /**
     * Get specifies if the additional information should be provided for this item.
     *
     * @return the expand value
     */
    public String expand() {
        return this.expand;
    }

    /**
     * Set specifies if the additional information should be provided for this item.
     *
     * @param expand the expand value to set
     * @return the GetProtectedItemQueryObject object itself.
     */
    public GetProtectedItemQueryObject withExpand(String expand) {
        this.expand = expand;
        return this;
    }

}


text:
package redis

import (
	"log"
)

type subType uint8

const (
	subSubscribe subType = iota
	subUnsubscribe
	subPsubscribe
	subPunsubscribe
)

// Subscription is a structure for holding a Redis subscription for multiple channels.
type Subscription struct {
	c       *conn
	msgHdlr func(msg *Message)
}

// newSubscription returns a new Subscription or an error.
func newSubscription(config *Config, msgHdlr func(msg *Message)) (*Subscription, *Error) {
	var err *Error

	s := &Subscription{
		msgHdlr: msgHdlr,
	}

	// Connection handling
	s.c, err = newConn(config)
	if err != nil {
		return nil, err
	}

	s.c.noReadTimeout = true // disable read timeout during pubsub mode
	go s.listener()
	return s, nil
}

// Subscribe subscribes to given channels or returns an error.
func (s *Subscription) Subscribe(channels ...string) (err *Error) {
	return s.c.subscription(subSubscribe, channels)
}

// Unsubscribe unsubscribes from given channels or returns an error.
func (s *Subscription) Unsubscribe(channels ...string) (err *Error) {
	return s.c.subscription(subUnsubscribe, channels)
}

// Psubscribe subscribes to given patterns or returns an error.
func (s *Subscription) Psubscribe(patterns ...string) (err *Error) {
	return s.c.subscription(subPsubscribe, patterns)
}

// Punsubscribe unsubscribes from given patterns or returns an error.
func (s *Subscription) Punsubscribe(patterns ...string) (err *Error) {
	return s.c.subscription(subPunsubscribe, patterns)
}

// Close closes the subscription.
func (s *Subscription) Close() {
	// just sack the connection, listener will close down eventually.
	s.c.close()
}

// readMessage reads and parses pubsub message data from the connection and returns it as a message.
func (s *Subscription) readMessage() *Message {
	var err error
	var rs string
	m := new(Message)
	r := s.c.read()

	if r.Type != ReplyMulti || len(r.Elems) < 3 {
		goto Err
	}

	// first argument is the message type
	if rs, err = r.Elems[0].Str(); err != nil {
		goto Err
	}

	switch rs {
	case "subscribe":
		m.Type = MessageSubscribe
	case "unsubscribe":
		m.Type = MessageUnsubscribe
	case "psubscribe":
		m.Type = MessagePsubscribe
	case "punsubscribe":
		m.Type = MessagePunsubscribe
	case "message":
		m.Type = MessageMessage
	case "pmessage":
		m.Type = MessagePmessage
	default:
		goto Err
	}

	// second argument
	if rs, err = r.Elems[1].Str(); err != nil {
		goto Err
	}

	switch {
	case m.Type == MessageSubscribe || m.Type == MessageUnsubscribe:
		m.Channel = rs

		// number of subscriptions
		if m.Subscriptions, err = r.Elems[2].Int(); err != nil {
			goto Err
		}
	case m.Type == MessagePsubscribe || m.Type == MessagePunsubscribe:
		m.Pattern = rs

		// number of subscriptions
		if m.Subscriptions, err = r.Elems[2].Int(); err != nil {
			goto Err
		}
	case m.Type == MessageMessage:
		m.Channel = rs

		// payload
		if m.Payload, err = r.Elems[2].Str(); err != nil {
			goto Err
		}
	case m.Type == MessagePmessage:
		m.Pattern = rs

		// name of the originating channel
		if m.Channel, err = r.Elems[2].Str(); err != nil {
			goto Err
		}

		if len(r.Elems) < 4 {
			goto Err
		}

		// payload
		if m.Payload, err = r.Elems[3].Str(); err != nil {
			goto Err
		}
	default:
		goto Err
	}

	return m

Err:
	// Error/Invalid message reply
	// we shouldn't generally get these, except when closing.
	if r.Err != nil && !r.Err.Test(ErrorConnection) {
		log.Printf("received an unexpected error reply while in pubsub mode: %s.\n ignoring...",
			r.Err)
	}

	return nil
}

// listener is a goroutine for reading and handling pubsub messages.
func (s *Subscription) listener() {
	var m *Message

	// read until connection is closed
	for {
		m = s.readMessage()
		if m == nil && s.c.closed() {
			return
		}

		go s.msgHdlr(m)
	}
}


text:
/**
 * Autogenerated by Avro
 *
 * DO NOT EDIT DIRECTLY
 */
package org.kaaproject.kaa.schema.base;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public class Log extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
  public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"Log\",\"namespace\":\"org.kaaproject.kaa.schema.base\",\"fields\":[]}");
  public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }

  public org.apache.avro.Schema getSchema() { return SCHEMA$; }
  // Used by DatumWriter.  Applications should not call.
  public java.lang.Object get(int field$) {
    switch (field$) {
    default: throw new org.apache.avro.AvroRuntimeException("Bad index");
    }
  }
  // Used by DatumReader.  Applications should not call.
  @SuppressWarnings(value="unchecked")
  public void put(int field$, java.lang.Object value$) {
    switch (field$) {
    default: throw new org.apache.avro.AvroRuntimeException("Bad index");
    }
  }

  /** Creates a new Log RecordBuilder */
  public static org.kaaproject.kaa.schema.base.Log.Builder newBuilder() {
    return new org.kaaproject.kaa.schema.base.Log.Builder();
  }

  /** Creates a new Log RecordBuilder by copying an existing Builder */
  public static org.kaaproject.kaa.schema.base.Log.Builder newBuilder(org.kaaproject.kaa.schema.base.Log.Builder other) {
    return new org.kaaproject.kaa.schema.base.Log.Builder(other);
  }

  /** Creates a new Log RecordBuilder by copying an existing Log instance */
  public static org.kaaproject.kaa.schema.base.Log.Builder newBuilder(org.kaaproject.kaa.schema.base.Log other) {
    return new org.kaaproject.kaa.schema.base.Log.Builder(other);
  }

  /**
   * RecordBuilder for Log instances.
   */
  public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<Log>
    implements org.apache.avro.data.RecordBuilder<Log> {

    /** Creates a new Builder */
    private Builder() {
      super(org.kaaproject.kaa.schema.base.Log.SCHEMA$);
    }

    /** Creates a Builder by copying an existing Builder */
    private Builder(org.kaaproject.kaa.schema.base.Log.Builder other) {
      super(other);
    }

    /** Creates a Builder by copying an existing Log instance */
    private Builder(org.kaaproject.kaa.schema.base.Log other) {
            super(org.kaaproject.kaa.schema.base.Log.SCHEMA$);
    }

    @Override
    public Log build() {
      try {
        Log record = new Log();
        return record;
      } catch (Exception e) {
        throw new org.apache.avro.AvroRuntimeException(e);
      }
    }
  }
}


text:
import os
from unittest.mock import patch
from unittest.mock import MagicMock

import cauldron
from cauldron.cli.commands import save
from cauldron.environ.response import Response
from cauldron.test import support
from cauldron.test.support import scaffolds

class TestSave(scaffolds.ResultsTest):

    def test_fails_no_project(self):
        """Should fail if there is no open project."""
        path = self.get_temp_path('save-fail-1')
        r = support.run_command('save "{}"'.format(path))
        self.assertTrue(r.failed)
        self.assertGreater(len(r.errors), 0)
        self.assertEqual(r.errors[0].code, 'NO_PROJECT')

    @patch('cauldron.cli.commands.save.write_file')
    def test_fails_write(self, write_func):
        """Should fail when the write function raises an exception."""
        write_func.side_effect = IOError('Write failed')

        support.create_project(self, 'rex')
        path = self.get_temp_path('save-fail-2')
        r = support.run_command('save "{}"'.format(path))
        self.assertTrue(r.failed)
        self.assertGreater(len(r.errors), 0)
        self.assertEqual(r.errors[0].code, 'WRITE_SAVE_ERROR')

    def test_save_directory_success(self):
        """Should write a cauldron file."""

        support.create_project(self, 'triceratops')
        path = self.get_temp_path('save-success-1')
        r = support.run_command('save "{}"'.format(path))
        self.assertFalse(r.failed)
        self.assertTrue(os.path.exists(r.data['path']))

        project = cauldron.project.get_internal_project()
        self.assertTrue(
            r.data['path'].endswith('{}.cauldron'.format(project.title))
        )

    def test_save_file_no_extension_success(self):
        """Should write a cauldron file."""

        support.create_project(self, 'tyrannosaurus')
        path = self.get_temp_path('save-success-2', 'project')
        r = support.run_command('save "{}"'.format(path))
        self.assertFalse(r.failed)
        self.assertTrue(os.path.exists(r.data['path']))
        self.trace('PATH:', r.data['path'])
        self.assertTrue(r.data['path'].endswith('project.cauldron'))

    def test_save_file_success(self):
        """Should write a cauldron file."""

        support.create_project(self, 'apatosaurus')
        path = self.get_temp_path(
            'save-success-3',
            'folder',
            'project.cauldron'
        )
        r = support.run_command('save "{}"'.format(path))
        self.assertFalse(r.failed)
        self.assertTrue(os.path.exists(r.data['path']))
        self.assertTrue(r.data['path'].endswith('project.cauldron'))

    def test_remote_save_no_project(self):
        """..."""

        response = support.run_remote_command('save')
        self.assertTrue(response.failed)

    @patch('cauldron.cli.sync.comm.download_file')
    def test_remote_download_error(self, download_file: MagicMock):
        """..."""
        download_file.return_value = Response().fail().response

        support.create_project(self, 'apophis')
        project = cauldron.project.get_internal_project()

        support.run_remote_command(
            'open "{}" --forget'.format(project.source_directory)
        )

        response = support.run_remote_command('save')
        self.assertTrue(response.failed)

    @patch('cauldron.cli.sync.comm.download_file')
    def test_remote(self, download_file: MagicMock):
        """..."""
        download_file.return_value = Response()

        support.create_project(self, 'apophis')
        project = cauldron.project.get_internal_project()

        support.run_remote_command(
            'open "{}" --forget'.format(project.source_directory)
        )

        response = support.run_remote_command('save')
        self.assert_has_success_code(response, 'DOWNLOAD_SAVED')

    def test_get_default_path_no_project(self):
        """..."""

        path = save.get_default_path()
        self.assertTrue(os.path.exists(path))


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

<title>Overview (Openfire 3.10.2 Javadoc)</title>
<meta name="date" content="2015-06-22">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Openfire 3.10.2 Javadoc

Prev

Next

Frames

No Frames

All Classes

                Openfire 3.10.2 Javadoc

Openfire is an open-source XMPP server.

See: Description

Packages

Package
Description

org.jivesoftware.admin

Supporting classes and tags for the admin console.

org.jivesoftware.database

Database connection code.

org.jivesoftware.database.bugfix

org.jivesoftware.openfire

org.jivesoftware.openfire.admin

org.jivesoftware.openfire.audit

Service that records XMPP traffics.

org.jivesoftware.openfire.audit.spi

org.jivesoftware.openfire.auth

Authentication and Authorization service interfaces and classes.

org.jivesoftware.openfire.carbons

Provides packet extensions for XEP-0280: Message Carbons.

org.jivesoftware.openfire.clearspace

org.jivesoftware.openfire.cluster

org.jivesoftware.openfire.commands

Ad-Hoc Commands implementation (XEP-0050).

org.jivesoftware.openfire.commands.admin

org.jivesoftware.openfire.commands.admin.group

org.jivesoftware.openfire.commands.admin.muc

org.jivesoftware.openfire.commands.admin.user

org.jivesoftware.openfire.commands.clearspace

org.jivesoftware.openfire.commands.event

org.jivesoftware.openfire.component

org.jivesoftware.openfire.container

The microkernel core of the server is a simple, flexible, nested
 container framework defined in this package.

org.jivesoftware.openfire.crowd

org.jivesoftware.openfire.crowd.jaxb

org.jivesoftware.openfire.disco

Service discovery implementation (XEP-0030).

org.jivesoftware.openfire.entitycaps

Implementation of Entity Capabilities (XEP-0115).

org.jivesoftware.openfire.event

Event system.

org.jivesoftware.openfire.filetransfer

Implementation of SOCKS5 Bytestreams (XEP-0065).

org.jivesoftware.openfire.filetransfer.proxy

org.jivesoftware.openfire.forms

Data forms implementation (XEP-0004).

org.jivesoftware.openfire.forms.spi

org.jivesoftware.openfire.forward

Provides packet extensions for XEP-0297: Stanza Forwarding.

org.jivesoftware.openfire.group

Groups, which are used to organize users together.

org.jivesoftware.openfire.handler

IQ class implementations.

org.jivesoftware.openfire.http

Provides classes for XEP-0124: Bidirectional-streams Over Synchronous HTTP (BOSH).

org.jivesoftware.openfire.interceptor

Provides classes for intercepting packets.

org.jivesoftware.openfire.launcher

Laucher classes for Openfire.

org.jivesoftware.openfire.ldap

LDAP code for authentication and user profile information.

org.jivesoftware.openfire.lockout

org.jivesoftware.openfire.mediaproxy

org.jivesoftware.openfire.muc

Implementation of Multi-User Chat (XEP-0045).

org.jivesoftware.openfire.muc.cluster

org.jivesoftware.openfire.muc.spi

Implementation of Multi-User Chat (XEP-0045).

org.jivesoftware.openfire.multiplex

Connection Manager implementation.

org.jivesoftware.openfire.net

org.jivesoftware.openfire.nio

org.jivesoftware.openfire.pep

Implementation of Personal Eventing via Pubsub (XEP-0163).

org.jivesoftware.openfire.privacy

Implementation of Blocking Communication.

org.jivesoftware.openfire.pubsub

Implementation of Publish-Subscribe (XEP-0060).

org.jivesoftware.openfire.pubsub.cluster

org.jivesoftware.openfire.pubsub.models

Defines policies that define who is allowed to subscribe and retrieve items or policies that
 define who is allowed to publish items to nodes (XEP-0060).

org.jivesoftware.openfire.resultsetmanager

org.jivesoftware.openfire.roster

Provides classes for managing the roster.

org.jivesoftware.openfire.sasl

Provides classes for SASL.

org.jivesoftware.openfire.security

org.jivesoftware.openfire.server

Classes used for server-to-server communication.

org.jivesoftware.openfire.session

org.jivesoftware.openfire.spi

org.jivesoftware.openfire.starter

org.jivesoftware.openfire.stats

org.jivesoftware.openfire.transport

org.jivesoftware.openfire.update

Classes that provide the "check for update" service or the "get available plugins" service.

org.jivesoftware.openfire.user

Provides the interfaces and classes necessary to create custom
 user account data providers for Openfire.

org.jivesoftware.openfire.vcard

org.jivesoftware.openfire.webdav

org.jivesoftware.util

Utility classes.

org.jivesoftware.util.cache

org.jivesoftware.util.log.util

Openfire is an open-source XMPP server.

Overview

Package

Class

Tree

Deprecated

Index

Help

Openfire 3.10.2 Javadoc

Prev

Next

Frames

No Frames

All Classes

Copyright © 2003-2008 Jive Software.


text:
"""
    SeisAddNoise(d, snr; <keyword arguments>)

Add noise at a given signal-to-noise ratio level `snr` to an N-dimensional input
data `d`. Noise can be band limited using kewyord `L`.

# Arguments
* `d::Array{Real, N}`: N-dimensional data.
* `snr::Real`: signal-to-noise ratio.

# Keyword arguments
* `db::Bool=false`: `db=false` if `snr` is given by amplitude, `db=true` if
snr is given in dB.
* `pdf::AbstractString="gaussian"`: random noise probability distribution:
`"gaussian"` or `"uniform"`.
* `L::Int=1`: averaging operator length to band-limit the random noise.

# Examples
```
julia> w = Ricker(); wn = SeisAddNoise(w, 2); plot(w); plot(wn);
MeasureSNR(w, wn)

julia> d, extent = SeisHypEvents(); dn = SeisAddNoise(d, 1.0, db=true, L=9);
SeisPlot([d dn], extent); MeasureSNR(d, dn, db=true)
```
Credits: Juan I. Sabbione, 2016
"""

function SeisAddNoise{T<:Real, N}(d::Array{T, N}, snr::Real; db::Bool=false,
                                  pdf::AbstractString="gaussian", L::Int=1)

    noise = GenNoise(size(d), pdf, L=L)
    if db==false
        noise = noise/vecnorm(noise) * vecnorm(d)/snr
    elseif db==true
        noise = noise/vecnorm(noise) * vecnorm(d)/10.0^(0.05*snr)
    end
    noisy = d + noise
    assert(abs(MeasureSNR(d, noisy, db=db) - snr) < 1e10*eps(AbstractFloat(snr)))
    return noisy

end

# Generate the noise
function GenNoise(dims::Tuple, pdf::AbstractString; L::Int=1)
    N = length(dims)
    n1 = dims[1]
    N == 1 ? nx = 1 : nx = *(dims[2:end]...)
    hamm = Hamming(L)
    L2 = floor(Int,L/2)
    if pdf=="gaussian"
        noise = randn(n1, nx)
    elseif pdf=="uniform"
        noise = -1 + 2*rand(n1, nx)
    else
        error("pdf must be gussian or uniform")
    end
    for j = 1:nx
     noise[:,j] = conv(noise[:,j], hamm)[L2+1:n1+L2]
    end
    reshape(noise, dims...)
end


text:
module Devices
  module Seeders
    class ExpressXlOneZero < AbstractExpress
      def settings_device_name
        device.update!(name: "FarmBot Express XL")
      end

      def settings_firmware
        device
          .fbos_config
          .update!(firmware_hardware: FbosConfig::EXPRESS_K10)
      end

      def settings_default_map_size_x
        device.web_app_config.update!(map_size_x: 6_000)
      end

      def settings_default_map_size_y
        device.web_app_config.update!(map_size_y: 2_400)
      end
    end
  end
end


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

import { EventsService, EventSwapService, EventModel, EventItemModel } from '../../../../shared';

@Component({
  selector: 'eventitem',
  templateUrl: 'eventitem.component.html',
  styleUrls: ['eventitem.scss']
})
export class EventItem implements  OnInit {

  private _event:EventModel;
  private _eventItemsModel:Array<EventItemModel>;

  constructor(private _eventsService:EventsService,
              private _eventSwapService:EventSwapService) {}

  ngOnInit() {
    this._eventItemsModel = [];
    this._event = new EventModel();
    this._eventSwapService.emitter$.subscribe((event:EventModel) => {
      this._event = event;
      this.getEventItems(event);

      if (!this.isOpen('.open-event-container')) {
        this.toggleEvent();
      } else {
        var container = $('.open-event-container');
        container.css('opacity', 0);
        container.animate({opacity: 1}, {queue: false, duration: 'slow'});
      }

      if (this.isOpen('.event-menu')) {
        this.toggleEventMenu();
      }

    });
  }

  private addItem():void {

  }

  private getEventItems(event:EventModel):void {
    this._eventsService.getEventItems(event)
      .then((data:Array<EventItemModel>) => {
        this._eventItemsModel = data;
      });
  }

  private toggleEventMenu() {
    var container = $('.event-menu');
    container.stop().animate({width: 'toggle'}, 'fast');
  }

  private toggleEvent() {
    var cssClass = '.open-event-container';
    var container = $(cssClass);
    container.animate({opacity: this.isOpen(cssClass) ? 0 : 1},
                      {queue: false, duration: 'slow'});
    container.animate({width: 'toggle'}, 'slow');
  }

  private isOpen(cssClass:String):boolean {
    var display = $(cssClass).css('display');
    return display != 'none';
  }

}


text:
package com.helger.commons.codec;

import java.io.IOException;
import java.io.OutputStream;

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.WillNotClose;

import com.helger.commons.CGlobal;
import com.helger.commons.string.StringHelper;

/**
 * Decoder for ASCII Hex encoding
 *
 * @author Philip Helger
 */
public class ASCIIHexCodec implements IByteArrayStreamDecoder
{
  public ASCIIHexCodec ()
  {}

  public void decode (@Nullable final byte [] aEncodedBuffer,
                      @Nonnegative final int nOfs,
                      @Nonnegative final int nLen,
                      @Nonnull @WillNotClose final OutputStream aOS)
  {
    if (aEncodedBuffer == null || nLen == 0)
      return;

    try
    {
      boolean bFirstByte = true;
      int nFirstByte = 0;
      for (int i = 0; i < nLen; ++i)
      {
        final byte nEncByte = aEncodedBuffer[nOfs + i];
        if (nEncByte == '>')
          break;

        // Ignore whitespaces
        if (Character.isWhitespace (nEncByte))
          continue;

        final byte nDecByte = (byte) StringHelper.getHexValue ((char) nEncByte);
        if (nDecByte == CGlobal.ILLEGAL_UINT)
          throw new DecodeException ("Failed to convert byte '" + nEncByte + "/" + ((char) nEncByte) + "' to hex value in ASCIIHexDecode");
        if (bFirstByte)
          nFirstByte = nDecByte;
        else
          aOS.write ((byte) (nFirstByte << 4 | nDecByte & 0xff));
        bFirstByte = !bFirstByte;
      }

      // Write trailing byte
      if (!bFirstByte)
        aOS.write ((byte) (nFirstByte << 4));
    }
    catch (final IOException ex)
    {
      throw new DecodeException ("Failed to decode ASCII Hex", ex);
    }
  }
}


text:
package org.jenkinsci.plugins.p4.workspace;

import java.io.InputStream;
import java.util.List;
import java.util.logging.Logger;

import org.apache.commons.io.IOUtils;
import org.jenkinsci.plugins.p4.client.ConnectionFactory;
import org.jenkinsci.plugins.p4.client.NavigateHelper;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;

import com.perforce.p4java.client.IClient;
import com.perforce.p4java.core.file.FileSpecBuilder;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.impl.mapbased.client.Client;
import com.perforce.p4java.option.server.GetFileContentsOptions;
import com.perforce.p4java.server.IOptionsServer;

import hudson.Extension;
import hudson.model.AutoCompletionCandidates;
import hudson.util.FormValidation;

public class SpecWorkspaceImpl extends Workspace {

	private final String name;
	private final String specPath;

	private static Logger logger = Logger.getLogger(SpecWorkspaceImpl.class.getName());

	@Override
	public String getName() {
		return name;
	}

	public String getSpecPath() {
		return specPath;
	}

	@Override
	public WorkspaceType getType() {
		return WorkspaceType.SPEC;
	}

	@DataBoundConstructor
	public SpecWorkspaceImpl(String charset, boolean pinHost, String name, String specPath) {
		super(charset, pinHost);
		this.name = name;
		this.specPath = specPath;
	}

	@Override
	public IClient setClient(IOptionsServer connection, String user) throws Exception {
		// expands Workspace name if formatters are used.
		String clientName = getFullName();

		IClient iclient = connection.getClient(clientName);
		if (iclient == null) {
			logger.info("P4: Creating client from spec: " + clientName);
			Client implClient = new Client(connection);
			implClient.setName(clientName);
			implClient.setOwnerName(user);
			connection.createClient(implClient);
			iclient = connection.getClient(clientName);
		}

		// Owner set for use with p4maven
		iclient.setOwnerName(user);

		List<IFileSpec> file = FileSpecBuilder.makeFileSpecList(specPath);
		GetFileContentsOptions printOpts = new GetFileContentsOptions();
		printOpts.setNoHeaderLine(true);
		InputStream ins = connection.getFileContents(file, printOpts);

		String spec = IOUtils.toString(ins, "UTF-8");
		connection.execInputStringMapCmd("client", new String[] { "-i" }, spec);
		iclient.refresh();

		return iclient;
	}

	@Extension
	public static final class DescriptorImpl extends WorkspaceDescriptor {

		@Override
		public String getDisplayName() {
			return "Spec File (load workspace spec from file in Perforce)";
		}

		/**
		 * Provides auto-completion for workspace names. Stapler finds this
		 * method via the naming convention.
		 *
		 * @param value
		 *            The text that the user entered.
		 */
		public AutoCompletionCandidates doAutoCompleteName(@QueryParameter String value) {
			return autoCompleteName(value);
		}

		public FormValidation doCheckName(@QueryParameter String value) {
			return checkClientName(value);
		}

		/**
		 * Provides auto-completion for workspace names. Stapler finds this
		 * method via the naming convention.
		 *
		 * @param value
		 *            The text that the user entered.
		 */
		public AutoCompletionCandidates doAutoCompleteSpecPath(@QueryParameter String value) {
			return NavigateHelper.getPath(value);
		}

		public FormValidation doCheckSpecPath(@QueryParameter String value) {
			try {
				IOptionsServer p4 = ConnectionFactory.getConnection();
				List<IFileSpec> file = FileSpecBuilder.makeFileSpecList(value);
				GetFileContentsOptions printOpts = new GetFileContentsOptions();
				InputStream ins = p4.getFileContents(file, printOpts);

				if (ins != null) {
					return FormValidation.ok();
				}
				return FormValidation.error("Unknown file: " + value);
			} catch (Exception e) {
				return FormValidation.error(e.getMessage());
			}
		}
	}
}


text:
using static STULib.Types.Generic.Common;

namespace STULib.Types.Dump {
    [STU(0x5C5EA990)]
    public class STU_5C5EA990 : STUStatescriptState {
        [STUField(0xBB16810A, "m_priority", EmbeddedInstance = true)]
        public STULib.Types.STUConfigVar Priority;

        [STUField(0x00D49978, EmbeddedInstance = true)]
        public STULib.Types.STUConfigVar m_00D49978;
    }
}


text:
Opennebula Configuiration instructions

# Setup Front-End OpenNebula:

https://docs.opennebula.org/5.6/deployment/opennebula_installation/frontend_installation.html#

## Follow instructions to install OpenNebula-Node + Master
~~~bash

wget -q -O- https://downloads.opennebula.org/repo/repo.key | apt-key add -

echo "deb https://downloads.opennebula.org/repo/5.6/Ubuntu/16.04 stable opennebula" > /etc/apt/sources.list.d/opennebula.list

sudo apt-get update
sudo apt-get install -y opennebula opennebula-sunstone opennebula-gate opennebula-flow
/usr/share/one/install_gems

cat /var/lib/one/.one/one_auth
oneadmin:password

# Back to root & start opennebula
systemctl start opennebula
systemctl start opennebula-sunstone

# Setup Compute OpenNebula (Can be run in the same node)

https://docs.opennebula.org/5.6/deployment/node_installation/index.html

sudo apt-get install opennebula-node
sudo service libvirt-bin restart #  ubuntu

sudo su oneadmin
cd ~/.ssh
cp id_rsa.pub authorized_keys
ssh oneadmin@localhost
exit -> goes to oneadmin
exit -> goes to root

#Test OpenNebula deployment

oneuser show
~~~

#Login to OpenNebula Admin Area

http://SERVER_IP:9869

# Configuire OpenNebula to work with VirtEngine

~~~bash
mkdir /virtengine

cd /virtengine

wget https://virtenginepub.blob.core.windows.net/gulpd/init.sh

chmod 755 /virtengine/init.sh

# Modify init.sh so that it can connect to VirtEngine API's (you can find settings around the bottom)
#  under [meta]
#  vertice_api = # Change to VirtEngine API Location: port 9000
#  nsqd = # Change to VirtEngine NSQD Location: port 4150
#  everything below these settings is updated in the VM Automatically in Deployment.
#  such as api key, account id, assembly id, and hostname.

nano /etc/one/oned.conf
~~~

~~~conf
Ctrl + _ (Line 771)

VM_HOOK = [
 name      = "poweroff_hook",
 on        = "CUSTOM",
 state     = "ACTIVE",
 lcm_state = "SHUTDOWN_POWEROFF",
 command   = "hook_virtengine.rb",
 arguments = "$ID $TEMPLATE poweroff stopped" ]

VM_HOOK = [
 name      = "delete_hook",
 on        = "DONE",
 command   = "hook_virtengine.rb",
 arguments = "$ID $TEMPLATE destroyed destroyed" ]

VM_HOOK = [
 name      = "suspend_hook",
 on        = "CUSTOM",
 state     = "SUSPENDED",
 lcm_state = "LCM_INIT",
 command   = "hook_virtengine.rb",
 arguments = "$ID $TEMPLATE suspended suspended" ]

VM_HOOK = [
 name      = "boot_suspend_hook",
 on        = "CUSTOM",
 state     = "BOOT_SUSPENDED",
 lcm_state = "RUNNING",
 command   = "hook_virtengine.rb",
 arguments = "$ID $TEMPLATE running running" ]

VM_HOOK = [
 name      = "running_hook",
 on        = "CUSTOM",
 state     = "ACTIVE",
 lcm_state = "RUNNING",
 command   = "hook_virtengine.rb",
 arguments = "$ID $TEMPLATE running running" ]
~~~

~~~bash
wget https://raw.githubusercontent.com/VirtEngine/gitpackager/master/support/hook_virtengine.rb

cp hook_virtengine.rb /var/lib/one/remotes/hooks

chmod 755 /var/lib/one/remotes/hooks/hook_virtengine.rb

chown oneadmin:oneadmin /var/lib/one/remotes/hooks/hook_virtengine.rb

Create master_key in /var/lib/detio/:

#### If you want to modify the master key, you must modify the gateway configuiration file and set your own master key (recommended in production) - /var/lib/detio/virtenginegateway/gateway.conf

cat >/var/lib/detio/master_key << EOF
host=http://YOUR_IP:9000/v2
masterkey=3b8eb672aa7c8db82e5d34a0744740b20ed59e1f6814cfb63364040b0994ee3f
EOF

cd /var/tmp

wget https://virtenginepub.blob.core.windows.net/iso/centos.tar.gz

wget https://virtenginepub.blob.core.windows.net/iso/coreos_latest.tar.gz

wget https://virtenginepub.blob.core.windows.net/iso/debian.tar.gz

wget https://virtenginepub.blob.core.windows.net/iso/dockermachine.tar.gz

wget https://virtenginepub.blob.core.windows.net/iso/fedora.tar.gz

wget https://virtenginepub.blob.core.windows.net/iso/ubuntu_16.04.tar.gz

wget https://virtenginepub.blob.core.windows.net/iso/ubuntu14.tar.gz

tar -zxvf ubuntu_16.04.tar.gz

tar -zxvf centos.tar.gz

# centos_7.2.img

tar -zxvf ubuntu14.tar.gz

tar -zxvf coreos_latest.tar.gz
# coreos_latest

tar -zxvf debian.tar.gz
# debian_8.5.img

tar -zxvf dockermachine.tar.gz
# dockermachine.img

tar -zxvf fedora.tar.gz
# fedora_24.img
~~~

The untar them individually and add them to the opennebula datastore with the following slugs (titles)

osname_version

for examples, ubuntu_14.04, windows_2008, centos_7.2, centos_6.8

add image named 'megam' with either ubuntu 16.04 OS or Centos, this will be used for deploying apps.

https://github.com/VirtEngine/gitpackager/tree/master/support

### Setup network bridge from eth0 -> br0
### Add network to OpenNebula
### Add images to OpenNebula
### Add VM Template to OpenNebula

# Add empty template first, update the template with the following settings.

~~~yaml
CONTEXT = [
  FILES = "/virtengine/init.sh",
  NETWORK = "YES",
  NODE_NAME = "$NAME",
  SET_HOSTNAME = "$NAME",
  SSH_PUBLIC_KEY = "$USER[SSH_PUBLIC_KEY]" ]
CPU = "0.5"
CPU_COST = "0.022222"
DESCRIPTION = "common template for all images"
DISK = [
  IMAGE = "megam",
  IMAGE_UNAME = "oneadmin" ]
DISK_COST = "0.0044444"
GRAPHICS = [
  LISTEN = "0.0.0.0",
  TYPE = "VNC" ]
LABELS = ""
MEMORY = "1024"
MEMORY_COST = "0.011111"
NIC = [
  NETWORK = "public-1",
  NETWORK_UNAME = "oneadmin" ]
NIC_DEFAULT = [
  MODEL = "virtio" ]
OS = [
  ARCH = "x86_64" ]
SCHED_REQUIREMENTS = "CLUSTER_ID=\"100\""
VCPU = "1"
~~~


text:
require "formula"

# Please only update to versions that are published on PyPi as there are too
# many releases for us to update to every single one:
# https://pypi.python.org/pypi/youtube_dl
class YoutubeDl < Formula
  desc "Download YouTube videos from the command-line"
  homepage "https://rg3.github.io/youtube-dl/"
  url "https://yt-dl.org/downloads/2015.06.15/youtube-dl-2015.06.15.tar.gz"
  sha256 "5a30bb0e62bbdf7797b61d29678e672d67dddc0d3fa502d133d3017061b67c9a"

  bottle do
    cellar :any
    sha256 "186069f57ae2d66ef27e5bf19180f9c52c8c5c2efc5f112b3839881edeb5c95b" => :yosemite
    sha256 "4f59dd35d4d0c7b16fc758c1e795da8920fa61a15a452f26f314cac97dfcf282" => :mavericks
    sha256 "01a497182331bc99803b2bd58aa9bad22ce3cfafeae03b4823db4bdce1bc19c5" => :mountain_lion
  end

  head do
    url "https://github.com/rg3/youtube-dl.git"
    depends_on "pandoc" => :build
  end

  depends_on "rtmpdump" => :optional

  def install
    system "make", "PREFIX=#{prefix}"
    bin.install "youtube-dl"
    man1.install "youtube-dl.1"
    bash_completion.install "youtube-dl.bash-completion"
    zsh_completion.install "youtube-dl.zsh" => "_youtube-dl"
  end

  def caveats
    "To use post-processing options, `brew install ffmpeg` or `brew install libav`."
  end

  test do
    system "#{bin}/youtube-dl", "--simulate", "https://www.youtube.com/watch?v=he2a4xK8ctk"
  end
end


text:
prepare_recipe

every_enabled_application do |application, _deploy|
  create_deploy_dir(application, File.join('shared'))
  create_deploy_dir(application, File.join('shared', 'config'))
  create_deploy_dir(application, File.join('shared', 'log'))
  create_deploy_dir(application, File.join('shared', 'pids'))
  create_deploy_dir(application, File.join('shared', 'scripts'))
  create_deploy_dir(application, File.join('shared', 'sockets'))
  create_deploy_dir(application, File.join('shared', 'vendor/bundle'))

  databases = []
  every_enabled_rds(self, application) do |rds|
    databases.push(Drivers::Db::Factory.build(self, application, rds: rds))
  end

  scm = Drivers::Scm::Factory.build(self, application)
  framework = Drivers::Framework::Factory.build(self, application, databases: databases)
  appserver = Drivers::Appserver::Factory.build(self, application, databases: databases)
  worker = Drivers::Worker::Factory.build(self, application, databases: databases)
  webserver = Drivers::Webserver::Factory.build(self, application)
  consul_template = Drivers::ConsulTemplate::Worker.new(self, application)

  fire_hook(:configure, items: databases + [scm, framework, appserver, worker, webserver, consul_template])
end


text:
/*
 * Basically from tensorflow/core/platform/default/logging.cc
 * Used in embedded system where there is no glogs.
 */

#include "Logging.h"
#ifndef PADDLE_USE_GLOG
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mutex>
#include <thread>
#include <vector>

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

namespace paddle {

namespace internal {

std::string join(const std::string& part1, const std::string& part2) {
  const char sep = '/';
  if (!part2.empty() && part2.front() == sep) {
    return part2;
  }
  std::string ret;
  ret.reserve(part1.size() + part2.size() + 1);
  ret = part1;
  if (!ret.empty() && ret.back() != sep) {
    ret += sep;
  }
  ret += part2;
  return ret;
}

static inline bool env2bool(const char* envName, bool defaultValue = false) {
  char* envValue = getenv(envName);
  if (envValue == nullptr) {
    return defaultValue;
  } else {
    return memchr("tTyY1\0", envValue[0], 6) != nullptr;
  }
}

static inline int env2int(const char* envName, int defaultValue = 0) {
  char* envValue = getenv(envName);
  if (envValue == nullptr) {
    return defaultValue;
  } else {
    int retValue = defaultValue;
    try {
      retValue = std::stoi(envValue);
    } catch (...) {
      // pass
    }
    return retValue;
  }
}

static inline int env2index(const char* envName,
                            const std::vector<std::string>& options,
                            int defaultValue) {
  char* envValue = getenv(envName);
  if (envValue == nullptr) {
    return defaultValue;
  } else {
    for (size_t i = 0; i < options.size(); ++i) {
      if (options[i] == envValue) {
        return static_cast<int>(i);
      }
    }
    return defaultValue;
  }
}

static bool gLogToStderr = env2bool("PLOG_LOGTOSTDERR", true);
static const std::vector<std::string> gLevelName = {
    "INFO", "WARNING", "ERROR", "FATAL"};
static int gMinLogLevel =
    env2int("PLOG_MINLOGLEVEL", env2index("PLOG_MINLOGLEVEL", gLevelName, 0));

static std::vector<std::vector<int>> gLogFds;
static std::vector<int> gLogFileFds;
static bool gLogInited = false;
static void freeLogFileFds() {
  for (auto fd : gLogFileFds) {
    close(fd);
  }
}

static void initializeLogFds(char* argv0) {
  gLogFds.resize(NUM_SEVERITIES);

  for (int i = gMinLogLevel; i < NUM_SEVERITIES && gLogToStderr;
       ++i) {  // Add stderr
    std::vector<int>& fds = gLogFds[i];
    fds.push_back(STDERR_FILENO);
  }

  char* logDir = getenv("PLOG_LOGDIR");

  for (int i = gMinLogLevel; i < NUM_SEVERITIES && logDir != nullptr; ++i) {
    std::string filename =
        join(logDir, std::string(argv0) + "." + gLevelName[i]);
    int fd = open(filename.c_str(), O_CREAT | O_WRONLY, 0644);
    if (fd == -1) {
      fprintf(stderr, "Open log file error!");
      exit(1);
    }
    gLogFileFds.push_back(fd);

    std::vector<int>& curFds = gLogFds[i];
    curFds.insert(curFds.end(), gLogFileFds.begin(), gLogFileFds.end());
  }

  atexit(freeLogFileFds);
  gLogInited = true;
}

static void (*gFailureFunctionPtr)() ATTR_NORETURN = abort;

LogMessage::LogMessage(const char* fname, int line, int severity)
    : fname_(fname), line_(line), severity_(severity) {}

LogMessage::~LogMessage() { this->generateLogMessage(); }

void LogMessage::generateLogMessage() {
  if (!gLogInited) {
    fprintf(stderr,
            "%c %s:%d] %s\n",
            "IWEF"[severity_],
            fname_,
            line_,
            str().c_str());
  } else {
    for (auto& fd : gLogFds[this->severity_]) {
      dprintf(fd,
              "%c %s:%d] %s\n",
              "IWEF"[severity_],
              fname_,
              line_,
              str().c_str());
    }
  }
}

LogMessageFatal::LogMessageFatal(const char* file, int line)
    : LogMessage(file, line, FATAL) {}

LogMessageFatal::~LogMessageFatal() {
  generateLogMessage();
  gFailureFunctionPtr();
}
}  // namespace internal

void initializeLogging(int argc, char** argv) {
  internal::initializeLogFds(argv[0]);
}

namespace logging {
void setMinLogLevel(int level) { paddle::internal::gMinLogLevel = level; }

void installFailureFunction(void (*callback)() ATTR_NORETURN) {
  paddle::internal::gFailureFunctionPtr = callback;
}

}  // namespace logging

}  // namespace paddle

#else
namespace paddle {
void initializeLogging(int argc, char** argv) {
  (void)(argc);
  if (!getenv("GLOG_logtostderr")) {
    google::LogToStderr();
  }
  google::InstallFailureSignalHandler();
  google::InitGoogleLogging(argv[0]);
}

namespace logging {
void setMinLogLevel(int level) { FLAGS_minloglevel = level; }
void installFailureFunction(void (*callback)()) {
  google::InstallFailureFunction(callback);
}
void installFailureWriter(void (*callback)(const char*, int)) {
  google::InstallFailureWriter(callback);
}
}  // namespace logging
}  // namespace paddle
#endif


text:
package egovframework.com.uss.olh.wor.web;

import java.util.List;

import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.annotation.IncludedInfo;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.uss.olh.wor.service.EgovWordDicaryService;
import egovframework.com.uss.olh.wor.service.WordDicaryDefaultVO;
import egovframework.com.uss.olh.wor.service.WordDicaryVO;

import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springmodules.validation.commons.DefaultBeanValidator;

/**
 *
 * 용어사전을 처리하는 Controller 클래스
 * @author 공통서비스 개발팀 박정규
 * @since 2009.04.01
 * @version 1.0
 * @see
 *
 * <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일      수정자           수정내용
 *  -------    --------    ---------------------------
 *   2009.04.01  박정규          최초 생성
 *   2011.8.26	정진오			IncludedInfo annotation 추가
 *
 * </pre>
 */

@Controller
public class EgovWordDicaryController {

	@Resource(name = "WordDicaryService")
	private EgovWordDicaryService wordDicaryService;

	/** EgovPropertyService */
	@Resource(name = "propertiesService")
	protected EgovPropertyService propertiesService;

	/** EgovMessageSource */
	@Resource(name = "egovMessageSource")
	EgovMessageSource egovMessageSource;

	// Validation 관련
	@Autowired
	private DefaultBeanValidator beanValidator;

	/**
	 * 개별 배포시 메인메뉴를 조회한다.
	 * @param model
	 * @return	"/uss/olh/wor/"
	 * @throws Exception
	 */
	@RequestMapping(value = "/uss/olh/wor/EgovMain.do")
	public String egovMain(ModelMap model) throws Exception {
		return "egovframework/com/uss/olh/wor/EgovMain";
	}

	/**
	 * 메뉴를 조회한다.
	 * @param model
	 * @return	"/uss/olh/wor/EgovLeft"
	 * @throws Exception
	 */
	@RequestMapping(value = "/uss/olh/wor/EgovLeft.do")
	public String egovLeft(ModelMap model) throws Exception {
		return "egovframework/com/uss/olh/wor/EgovLeft";
	}

	/**
	 * 용어사전목록을 조회한다.
	 * @param searchVO
	 * @param model
	 * @return	"/uss/olh/wor/EgovWordDicaryListInqire"
	 * @throws Exception
	 */
	@IncludedInfo(name = "용어사전", order = 530, gid = 50)
	@RequestMapping(value = "/uss/olh/wor/WordDicaryListInqire.do")
	public String selectWordDicaryList(@ModelAttribute("searchVO") WordDicaryDefaultVO searchVO, ModelMap model) throws Exception {

		/** EgovPropertyService.WordDicaryList */
		searchVO.setPageUnit(propertiesService.getInt("pageUnit"));
		searchVO.setPageSize(propertiesService.getInt("pageSize"));

		/** pageing */
		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(searchVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(searchVO.getPageUnit());
		paginationInfo.setPageSize(searchVO.getPageSize());

		searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		searchVO.setLastIndex(paginationInfo.getLastRecordIndex());
		searchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

		List<?> wordDicaryList = wordDicaryService.selectWordDicaryList(searchVO);
		model.addAttribute("resultList", wordDicaryList);

		int totCnt = wordDicaryService.selectWordDicaryListTotCnt(searchVO);
		paginationInfo.setTotalRecordCount(totCnt);
		model.addAttribute("paginationInfo", paginationInfo);

		return "egovframework/com/uss/olh/wor/EgovWordDicaryListInqire";
	}

	/**
	 * 용어사전 목록에 대한 상세정보를 조회한다.
	 * @param wordDicaryVO
	 * @param searchVO
	 * @param model
	 * @return	"/uss/olh/wor/EgovWordDicaryDetailInqire"
	 * @throws Exception
	 */
	@RequestMapping("/uss/olh/wor/WordDicaryDetailInqire.do")
	public String selectWordDicaryDetail(WordDicaryVO wordDicaryVO, @ModelAttribute("searchVO") WordDicaryDefaultVO searchVO, ModelMap model) throws Exception {

		WordDicaryVO vo = wordDicaryService.selectWordDicaryDetail(wordDicaryVO);

		model.addAttribute("result", vo);

		return "egovframework/com/uss/olh/wor/EgovWordDicaryDetailInqire";
	}

	/**
	 * 용어사전정보를 등록하기 위한 첫 화면
	 * @param searchVO
	 * @param model
	 * @return	"/uss/olh/wor/EgovWordDicaryRegist"
	 * @throws Exception
	 */
	@RequestMapping("/uss/olh/wor/addWordDicaryView.do")
	public String addWordDicaryView(@ModelAttribute("searchVO") WordDicaryDefaultVO searchVO, Model model) throws Exception {

		model.addAttribute("wordDicaryVO", new WordDicaryVO());

		return "egovframework/com/uss/olh/wor/EgovWordDicaryRegist";
	}

	/**
	 * 용어사전정보를 등록한다.
	 * @param searchVO
	 * @param wordDicaryVO
	 * @param bindingResult
	 * @param model
	 * @return	"forward:/uss/olh/wor/WordDicaryListInqire.do"
	 * @throws Exception
	 */
	@RequestMapping("/uss/olh/wor/WordDicaryRegist.do")
	public String insertWordDicary(@ModelAttribute("searchVO") WordDicaryDefaultVO searchVO, @ModelAttribute("wordDicaryVO") WordDicaryVO wordDicaryVO,
			BindingResult bindingResult, Model model) throws Exception {

		beanValidator.validate(wordDicaryVO, bindingResult);

		if (bindingResult.hasErrors()) {

			return "egovframework/com/uss/olh/wor/EgovWordDicaryRegist";

		}

		// 로그인VO에서  사용자 정보 가져오기
		LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

		String frstRegisterId = loginVO.getUniqId();

		wordDicaryVO.setFrstRegisterId(frstRegisterId); // 최초등록자ID
		wordDicaryVO.setLastUpdusrId(frstRegisterId); // 최종수정자ID

		wordDicaryService.insertWordDicary(wordDicaryVO);

		return "forward:/uss/olh/wor/WordDicaryListInqire.do";
	}

	/**
	 * 용어사전정보를 수정하기 위한 초기 화면
	 * @param wordId
	 * @param searchVO
	 * @param model
	 * @return	"/uss/olh/wor/EgovWordDicaryUpdt"
	 * @throws Exception
	 */
	@RequestMapping("/uss/olh/wor/WordDicaryUpdtView.do")
	public String wordDicaryUpdtView(@RequestParam("wordId") String wordId, @ModelAttribute("searchVO") WordDicaryDefaultVO searchVO, ModelMap model) throws Exception {

		WordDicaryVO wordDicaryVO = new WordDicaryVO();

		// Primary Key 값 세팅
		wordDicaryVO.setWordId(wordId);

		// JSTL 사용을 위해
		model.addAttribute(selectWordDicaryDetail(wordDicaryVO, searchVO, model));

		// 변수명은 CoC 에 따라
		model.addAttribute("wordDicaryVO", wordDicaryService.selectWordDicaryDetail(wordDicaryVO));

		return "egovframework/com/uss/olh/wor/EgovWordDicaryUpdt";
	}

	/**
	 * 용어사전정보를 수정한다.
	 * @param searchVO
	 * @param wordDicaryVO
	 * @param bindingResult
	 * @param model
	 * @return	"forward:/uss/olh/wor/WordDicaryListInqire.do"
	 * @throws Exception
	 */
	@RequestMapping("/uss/olh/wor/WordDicaryUpdt.do")
	public String updateWordDicary(@ModelAttribute("searchVO") WordDicaryDefaultVO searchVO, @ModelAttribute("wordDicaryVO") WordDicaryVO wordDicaryVO,
			BindingResult bindingResult, Model model) throws Exception {

		// Validation
		beanValidator.validate(wordDicaryVO, bindingResult);

		if (bindingResult.hasErrors()) {

			return "egovframework/com/uss/olh/wor/EgovWordDicaryUpdt";

		}

		// 로그인VO에서  사용자 정보 가져오기
		LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

		String frstRegisterId = loginVO.getUniqId();

		wordDicaryVO.setLastUpdusrId(frstRegisterId); // 최종수정자ID

		wordDicaryService.updateWordDicary(wordDicaryVO);

		return "forward:/uss/olh/wor/WordDicaryListInqire.do";
	}

	/**
	 * 용어사전정보를 삭제한다.
	 * @param wordDicaryVO
	 * @param searchVO
	 * @return	"forward:/uss/olh/wor/WordDicaryListInqire.do"
	 * @throws Exception
	 */
	@RequestMapping("/uss/olh/wor/WordDicaryDelete.do")
	public String deleteWordDicary(WordDicaryVO wordDicaryVO, @ModelAttribute("searchVO") WordDicaryDefaultVO searchVO) throws Exception {

		wordDicaryService.deleteWordDicary(wordDicaryVO);

		return "forward:/uss/olh/wor/WordDicaryListInqire.do";
	}

}


text:
import { Vector } from "./vector.js"

export class Sprite {
    constructor(gameGrid, name, width, height, color, location) {
        this.gameGrid = gameGrid;
        this.name = name;
        this.width = width;
        this.height = height;
        this.color = color;

        this.location = Vector.Clone(location);

        this.buildBoundingBox();

        // Filled in by child class
        this.velocity = null;

        console.log('Sprite: ' + this.name + ' Rezzed');
    }

    changeWidth(width) {
        this.width = width;
    }

    changeHeight(height) {
        this.height = height;
    }

    buildBoundingBox() {
        this.boundingBox = [
            this.location.points[0] - Math.round(this.width / 2),
            this.location.points[1] - Math.round(this.height / 2),
            this.location.points[0] + Math.round(this.width / 2),
            this.location.points[1] + Math.round(this.height / 2) // Bottom
        ];
    }

    bindToGameGrid() {
        const bounded = [0, 0];

        // Top
        if (this.boundingBox[1] < 0) {
            bounded[1] = 1; // Y-axis
            this.location.points[1] = 0 + Math.round(this.height / 2);
        }

        // Bottom
        if (this.boundingBox[3] > this.gameGrid.canvas.height) {
            bounded[1] = 1; // Y-axis
            this.location.points[1] = this.gameGrid.canvas.height - Math.round(this.height / 2);
        }

        // Left
        if (this.boundingBox[0] < 0) {
            bounded[0] = 1; // X-axis
            this.location.points[0] = 0 + Math.round(this.width / 2);
        }

        // Right
        if (this.boundingBox[2] > this.gameGrid.canvas.width) {
            bounded[0] = 1; // X-axis
            this.location.points[0] = this.gameGrid.canvas.width - Math.round(this.width / 2);
        }

        return bounded;
    }

    Collision(sprite) {
        // See if the 2 boxes intersect in any way
        this.gameGrid.context.beginPath();
        this.gameGrid.context.rect(
            sprite.boundingBox[0], sprite.boundingBox[1],
            sprite.width, sprite.height
        );

        return (
            this.gameGrid.context.isPointInPath(this.boundingBox[0], this.boundingBox[1]) ||
            this.gameGrid.context.isPointInPath(this.boundingBox[2], this.boundingBox[1]) ||
            this.gameGrid.context.isPointInPath(this.boundingBox[0], this.boundingBox[3]) ||
            this.gameGrid.context.isPointInPath(this.boundingBox[2], this.boundingBox[3]) ||
            this.gameGrid.context.isPointInPath(this.location.points[0], this.location.points[1])
        );
    }

    TouchLocation(location) {
        this.gameGrid.context.beginPath();
        this.gameGrid.context.rect(
            location.points[0], location.points[1],
            location.points[0], location.points[1]
        );

        return (
            this.gameGrid.context.isPointInPath(this.boundingBox[0], this.boundingBox[1]) ||
            this.gameGrid.context.isPointInPath(this.boundingBox[2], this.boundingBox[1]) ||
            this.gameGrid.context.isPointInPath(this.boundingBox[0], this.boundingBox[3]) ||
            this.gameGrid.context.isPointInPath(this.boundingBox[2], this.boundingBox[3]) ||
            this.gameGrid.context.isPointInPath(this.location.points[0], this.location.points[1])
        );
    }

    DrawSprite() {
        this.buildBoundingBox();

        this.gameGrid.context.fillStyle = this.color;
        this.gameGrid.context.fillRect(
            this.boundingBox[0], this.boundingBox[1],
            this.width, this.height
        );
    }
}