text:
<?php

namespace app\models\gradeable;

use app\exceptions\ValidationException;
use app\exceptions\NotImplementedException;
use app\libraries\Core;
use app\libraries\Utils;
use app\models\AbstractModel;
use app\libraries\NumberUtils;

/**
 * Class Component
 * @package app\models\gradeable
 *
 * All data describing the configuration of a Gradeable Component
 *
 * @method int getId()
 * @method string getTitle()
 * @method void setTitle($title)
 * @method string getTaComment()
 * @method void setTaComment($ta_comment)
 * @method string getStudentComment()
 * @method void setStudentComment($student_comment)
 * @method float getLowerClamp()
 * @method float getDefault()
 * @method float getMaxValue()
 * @method float getUpperClamp()
 * @method bool isText()
 * @method void setText($is_text)
 * @method bool isPeerComponent()
 * @method void setPeerComponent($is_peer_component)
 * @method int getOrder()
 * @method void setOrder($order)
 * @method int getPage()
 * @method void setIsItempoolLinked($is_linked)
 * @method bool getIsItempoolLinked()
 * @method void setItempool($itempool_name)
 * @method string getItempool()
 * @method Mark[] getMarks()
 */
class Component extends AbstractModel {
    /** @var Gradeable Reference to the gradeable this belongs to */
    private $gradeable = null;
    /** @prop @var int The course-wide unique numeric id of this component */
    protected $id = 0;
    /** @prop @var string The title of this component */
    protected $title = "";
    /** @prop @var string The comment only visible to the TA/manual grader */
    protected $ta_comment = "";
    /** @prop @var string The comment visible to the student */
    protected $student_comment = "";
    /** @prop @var int The minimum points this component can contribute to the score (can be negative) */
    protected $lower_clamp = 0;
    /** @prop @var int The number of points this component is worth with no marks */
    protected $default = 0;
    /** @prop @var int The full value of this component without extra credit */
    protected $max_value = 0;
    /** @prop @var int The maximum number of points this component can contribute to the score (can be > $max_value) */
    protected $upper_clamp = 0;
    /** @prop @var bool If this is a text component (true) or a numeric component (false) for numeric/text components */
    protected $text = false;
    /** @prop @var bool If this is a peer grading component */
    protected $peer_component = false;
    /** @prop @var int The order of this component in the gradeable */
    protected $order = -1;
    /** @prop @var int The pdf page this component will reside in */
    protected $page = -1;

    /** @prop @var bool Whether this component is linked to some itempool or not */
    protected $is_itempool_linked = false;
    /** @prop @var string Name of the itempool item if it is linked to itempool else empty string */
    protected $itempool = "";

    /** @prop @var Mark[] All possible common marks that can be assigned to this component */
    protected $marks = [];

    /** @prop @var Mark[] Array of marks loaded from the database */
    private $db_marks = [];
    /** @prop @var bool If any submitters have grades for this component */
    private $any_grades = false;

    /** @var int Pass to setPage to indicate student-assigned pdf page */
    const PDF_PAGE_STUDENT = -1;
    /** @var int Pass to setPage to indicate no pdf page */
    const PDF_PAGE_NONE = 0;

    /**
     * Component constructor.
     * @param Core $core
     * @param Gradeable $gradeable
     * @param array $details
     * @throws \InvalidArgumentException if any of the details were not found or invalid, or the gradeable was null
     * @throws ValidationException If the provided point details are incompatible
     */
    public function __construct(Core $core, Gradeable $gradeable, $details) {
        parent::__construct($core);

        $this->setGradeable($gradeable);
        $this->setIdInternal($details['id']);
        $this->setTitle($details['title']);
        $this->setTaComment($details['ta_comment']);
        $this->setStudentComment($details['student_comment']);
        $this->setPoints($details);
        $this->setText($details['text']);
        $this->setPeerComponent($details['peer_component'] ?? false);
        $this->setOrder($details['order']);
        $this->setPage($details['page']);
        $this->setIsItempoolLinked($details['is_itempool_linked'] ?? false);
        $this->setItempool($details['itempool'] ?? "");
        $this->any_grades = ($details['any_grades'] ?? false) === true;
        $this->modified = false;
    }

    /**
     * Creates a component with marks from a nested array (from JSON typically)
     * @param Core $core
     * @param Gradeable $gradeable
     * @param array $arr
     * @return Component
     */
    public static function import(Core $core, Gradeable $gradeable, array $arr) {
        $component = new Component($core, $gradeable, $arr);

        $marks_arr = $arr['marks'] ?? [];
        foreach ($marks_arr as $mark_arr) {
            $component->importMark($mark_arr);
        }
        return $component;
    }

    /**
     * Exports the component and its marks to an array
     * @return array
     */
    public function export() {
        $arr = parent::toArray();
        unset($arr['any_grades']);
        unset($arr['id']);
        unset($arr['modified']);
        unset($arr['order']);
        $marks = [];
        foreach ($arr['marks'] as $mark) {
            unset($mark['any_receivers']);
            unset($mark['id']);
            unset($mark['order']);
            unset($mark['modified']);
            $marks[] = $mark;
        }
        $arr['marks'] = $marks;
        return $arr;
    }

    /**
     * Gets the component's gradeable
     * @return Gradeable The component's gradeable
     */
    public function getGradeable() {
        return $this->gradeable;
    }

    /**
     * Gets the mark object with the provided mark id
     * @param int $mark_id
     * @return Mark|null The Mark with the provided id
     * @throws \InvalidArgumentException If the provided mark id isn't part of this component
     */
    public function getMark($mark_id) {
        foreach ($this->marks as $mark) {
            if ($mark->getId() === $mark_id) {
                return $mark;
            }
        }
        throw new \InvalidArgumentException('Component did not contain provided mark id');
    }

    /**
     * Gets an array of marks set to be deleted
     * @return Mark[]
     */
    public function getDeletedMarks() {
        return array_udiff($this->db_marks, $this->marks, Utils::getCompareByReference());
    }

    /**
     * Gets the number of grades required for this component
     *  to be considered 100% graded
     * @return int
     */
    public function getGradingSet() {
        return $this->peer_component ? $this->gradeable->getPeerGradeSet() : 1;
    }

    /**
     * Gets if any submitters have grades for this component yet
     * @return bool
     */
    public function anyGrades() {
        return $this->any_grades;
    }

    /* Overridden setters with validation */

    /**
     * Sets the component's gradeable
     * @param Gradeable $gradeable A non-null gradeable
     */
    private function setGradeable(Gradeable $gradeable) {
        if ($gradeable === null) {
            throw new \InvalidArgumentException('Gradeable Cannot be null!');
        }
        $this->gradeable = $gradeable;
    }

    /**
     * Sets the page number for this component
     * @param int $page
     */
    public function setPage(int $page) {
        $this->page = max($page, -1);
        $this->modified = true;
    }

    const point_properties = [
        'lower_clamp',
        'default',
        'max_value',
        'upper_clamp'
    ];

    /**
     * Parses points from string or float values into all float / null values
     * @param array $points A partial or complete array of floats or numeric strings indexed by component point property
     * @return array A complete array of floats (or nulls) indexed by component point property
     */
    private function parsePoints(array $points) {
        $parsedPoints = [];
        foreach (self::point_properties as $property) {
            if (is_numeric($points[$property])) {
                $parsedPoints[$property] = floatval($points[$property]);
            }
            else {
                $parsedPoints[$property] = null;
            }
        }
        return $parsedPoints;
    }

    /**
     * Asserts that the point values are valid.  See `setPoints` docs for details
     *
     * @param array $points A complete array of floats (or nulls) indexed by component point property
     */
    private function assertPoints(array $points) {
        $errors = [];

        // Give error messages to all null elements
        foreach (self::point_properties as $property) {
            if ($points[$property] === null) {
                $errors[$property] = 'Value must be a number!';
            }
        }

        //
        // NOTE: The function `Utils::compareNullableGt(a,b)` in this context is called so that
        //          it returns TRUE if the two values being compared are incompatible.  If the function
        //          returns FALSE then either the condition a>b is false, or one of the values are null.
        //          THIS NULL CASE MUST BE HANDLED IN SOME OTHER WAY.  As you can see, this is achieved by
        //          null checks in the above foreach loop.
        //
        //    i.e. if 'lower_clamp' > 'default', then set an error, but if 'lower_clamp' <= 'default' there is no error
        //      In the case that either 'lower_clamp' or 'default' are null, the function will return
        //      FALSE.  In the above foreach loop, if any of the properties are null, then an error gets
        //      assigned to that property name.  Any of the below comparisons involving that property are irrelevant
        //      because comparisons involving null values are irrelevant.
        //

        if (Utils::compareNullableGt($points['lower_clamp'], $points['default'])) {
            $errors['lower_clamp'] = 'Lower clamp can\'t be more than default!';
        }
        if (Utils::compareNullableGt($points['default'], $points['max_value'])) {
            $errors['max_value'] = 'Max value can\'t be less than default!';
        }
        if (Utils::compareNullableGt($points['max_value'], $points['upper_clamp'])) {
            $errors['max_value'] = 'Max value can\'t be more than upper clamp!';
        }

        if (count($errors) !== 0) {
            throw new ValidationException('Component point validation failed', $errors);
        }
    }

    /**
     * Sets component point values and ensures they are consistent:
     *  lower_clamp <= default <= max_value <= upper_clamp
     *
     * This will round the parameters to the precision of the gradeable
     *
     * @param array $points A partial or complete array of floats or numeric strings indexed by component point property
     */
    public function setPoints(array $points) {
        // Wrangle the input to ensure that they're all either floats are null
        $points = $this->parsePoints($points);

        // Assert that the point values are valid
        $this->assertPoints($points);

        $precision = $this->gradeable->getPrecision();

        // Round after validation because of potential floating point weirdness
        foreach (self::point_properties as $property) {
            $this->$property = NumberUtils::roundPointValue($points[$property], $precision);
        }
        $this->modified = true;
    }

    /**
     * Sets the array of marks
     * @param Mark[] $marks Must be an array of only Marks
     */
    public function setMarks(array $marks) {
        $marks = array_values($marks);
        // Make sure we're getting only marks
        foreach ($marks as $mark) {
            if (!($mark instanceof Mark)) {
                throw new \InvalidArgumentException('Object in marks array wasn\'t a mark');
            }
        }

        // Get the implied deleted marks from this operation and make sure that we aren't
        //  deleting any marks that are in use.
        $deleted_marks = array_udiff($this->marks, $marks, Utils::getCompareByReference());
        if (
            in_array(
                true,
                array_map(
                    function (Mark $mark) {
                        return $mark->anyReceivers();
                    },
                    $deleted_marks
                )
            )
        ) {
            throw new \InvalidArgumentException('Call to setMarks implied deletion of marks with receivers');
        }

        $this->marks = $marks;

        // sort by order
        usort($this->marks, function (Mark $a, Mark $b) {
            return $a->getOrder() - $b->getOrder();
        });
    }

    /**
     * Adds a new mark to this component with the provided title and point value
     * @param string $title
     * @param float $points
     * @return Mark the created mark
     */
    public function addMark(string $title, float $points, bool $publish) {
        $mark = new Mark($this->core, $this, [
            'title' => $title,
            'points' => $points,
            'order' => count($this->marks),
            'publish' => $publish,
            'id' => 0
        ]);
        $this->marks[] = $mark;
        return $mark;
    }

    /**
     * Imports a mark into the component via array
     * @param array $details
     * @return Mark
     */
    public function importMark($details) {
        $details['id'] = 0;
        $details['order'] = count($this->getMarks());
        $mark = new Mark($this->core, $this, $details);
        $this->marks[] = $mark;
        return $mark;
    }

    /**
     * Base method for deleting marks.  This isn't exposed as public so
     *  its make very clear that a delete mark operation is being forceful.
     * @param Mark $mark
     * @param bool $force true to delete the mark if it has receivers
     * @throws \InvalidArgumentException If this component doesn't own the provided mark or
     *          $force is false and the mark has receivers
     */
    private function deleteMarkInner(Mark $mark, bool $force = false) {
        // Don't delete if the mark has receivers (and we aren't forcing)
        if ($mark->anyReceivers() && !$force) {
            throw new \InvalidArgumentException('Attempt to delete a mark with receivers!');
        }

        // Calculate our marks array without the provided mark
        $new_marks = array_udiff($this->marks, [$mark], Utils::getCompareByReference());

        // If it wasn't removed from our marks, it was either already deleted, or never belonged to us
        if (count($new_marks) === count($this->marks)) {
            throw new \InvalidArgumentException('Attempt to delete mark that did not belong to this component');
        }

        // Finally, set our array to the new one
        $this->marks = $new_marks;
    }

    /**
     * Deletes a mark from this component if it has no receivers
     * @param Mark $mark
     * @throws \InvalidArgumentException If this component doesn't own the provided mark or the mark has receivers
     */
    public function deleteMark(Mark $mark) {
        $this->deleteMarkInner($mark, false);
    }

    /**
     * Deletes a mark from this component without checking if a submitter has received it yet
     * @param Mark $mark
     * @throws \InvalidArgumentException If this component doesn't own the provided mark
     */
    public function forceDeleteMark(Mark $mark) {
        $this->deleteMarkInner($mark, true);
    }

    /**
     * Sets the array of marks, only to be called from the database loading methods
     * @param array $marks
     * @internal
     */
    public function setMarksFromDatabase(array $marks) {
        $this->setMarks($marks);
        $this->db_marks = $this->marks;
    }

    /**
     * Sets the component Id
     * @param int $id Must be a non-negative integer
     */
    private function setIdInternal($id) {
        if ((is_int($id) || ctype_digit($id)) && intval($id) >= 0) {
            $this->id = intval($id);
        }
        else {
            throw new \InvalidArgumentException('Component Id must be a non-negative integer');
        }
    }

    /**
     * Sets the id of the component.
     *  NOTE: this should only be called from database results
     *  to avoid reconstruction of the whole object
     * @param int $id
     * @internal
     */
    public function setIdFromDatabase($id) {
        $this->setIdInternal($id);
    }

    /** @internal */
    public function setId($id) {
        throw new \BadFunctionCallException('Cannot set Id of component');
    }

    /** @internal */
    public function setLowerClamp($lower_clamp) {
        throw new NotImplementedException('Individual setters are disabled, use "setPoints" instead');
    }

    /** @internal */
    public function setDefault($default) {
        throw new NotImplementedException('Individual setters are disabled, use "setPoints" instead');
    }

    /** @internal */
    public function setMaxValue($max_value) {
        throw new NotImplementedException('Individual setters are disabled, use "setPoints" instead');
    }

    /** @internal */
    public function setUpperClamp($upper_clamp) {
        throw new NotImplementedException('Individual setters are disabled, use "setPoints" instead');
    }

    /* Convenience functions for the different types of gradeables */

    public function hasExtraCredit() {
        return $this->upper_clamp > $this->max_value;
    }

    /**
     * Gets if this component is fully extra credit
     * @return bool
     */
    public function isExtraCredit() {
        return $this->max_value === $this->default && $this->hasExtraCredit();
    }

    // Numeric/Text
    public function getNumericScore() {
        return max($this->upper_clamp, $this->max_value);
    }

    // Electronic
    public function isCountUp() {
        return $this->default === 0;
    }

    public function hasPenalty() {
        return $this->lower_clamp < 0;
    }

    public function getExtraCreditPoints() {
        return $this->upper_clamp - $this->max_value;
    }

    public function getPenaltyPoints() {
        return $this->hasPenalty() ? abs($this->lower_clamp) : 0;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PTracker.Core
{
    public interface ILogger
    {
        void Write(string msg);
        void WriteLine(string msg);
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  ZBConfigInfoModel.h
//  ZhiBoLaboratory
//
//  Created by lip on 16/7/12.
//  Copyright © 2016年 ZhiBo. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ZBWebSocketServerModel.h"

@interface ZBConfigInfoModel : NSObject
/** 短信发送验证口令 */
@property (copy, nonatomic) NSString *sendSnsToken;
/** 前段短信发送间隔时间 */
@property (assign, nonatomic) NSInteger snsTimespan;
/** 推流校验口令 */
@property (copy, nonatomic) NSString *validLock;
/** 直播间公告信息 */
@property (strong, nonatomic) NSArray *streamNoticeList;
/** 直播列表请求口令 */
@property (copy, nonatomic) NSString *varPage;
/** 过滤列表 直播清单 */
@property (strong, nonatomic) NSArray *liveFilterList;
/** 过滤列表 回放清单 */
@property (strong, nonatomic) NSArray *replayFilterList;
/** 点赞兑换比例清单 */
@property (strong, nonatomic) NSArray *commendExchangeList;
/** 金币充值兑换比例清单 */
@property (strong, nonatomic) NSArray *goldPayExchangeList;
/** 金币提现兑换比例清单 */
@property (strong, nonatomic) NSArray *goldCashExchangeList;
/** 聊天服务器地址列表 */
@property (strong, nonatomic) NSArray *webSocketServerList;
/** 过滤词替换符号 */
@property (copy, nonatomic) NSString *filterReplaceWord;
/** 敏感词版本号 */
@property (copy, nonatomic) NSString *filterWordVersion;

@end


text:
import * as Promise from 'bluebird';
import * as request from 'request';

import { Cache, FetchOptions, InternalHeaders } from './Cache';
import { BufferStream } from './BufferStream';
import { CacheResult, CachedError } from './CacheResult';
import { Address } from './Address';

export function extend<Type>(dst: Type, src: { [key: string]: any }) {
	for(let key of Object.keys(src)) {
		if(src[key] !== void 0) {
			(dst as { [key: string]: any })[key] = src[key];
		}
	}

	return(dst);
}

export class FetchState implements FetchOptions {
	constructor(options: FetchOptions = {}) {
		this.setOptions(options);

		if(
			!this.retryDelay ||
			!this.retryCount ||
			this.retryDelay < 0 ||
			this.retryCount < 0
		) this.retryCount = 0;

		this.retriesRemaining = this.retryCount;
	}

	setOptions(options: FetchOptions = {}) {
		return(extend(this, options));
	}

	extendRequestConfig(config: request.CoreOptions) {
		return(extend(config, this.requestConfig || {}));
	}

	clone() {
		return(new FetchState(this));
	}

	startStream(result: CacheResult) {
		const ready = Promise.try(
			() => this.onStream(result)
		).then(
			() => { this.isStreaming = true; }
		);

		return(ready);
	}

	abort() {
		this.strategyNum = Infinity;
	}

	retryNow() {
		this.strategyNum = 0;
	}

	retryLater() {
		if(this.retriesRemaining <= 0) return;
		--this.retriesRemaining;

		this.strategyNum = 0;

		// Signal cache to delay before retrying.
		this.strategyDelay = this.retryDelay * (1 + Math.random());
		this.retryDelay *= this.retryBackoffFactor;
	}

	allowLocal = false;
	allowRemote = true;
	allowCacheRead = true;
	allowCacheWrite = true;
	rewrite?: (url: string) => string = void 0;
	username?: string = void 0;
	password?: string = void 0;
	timeout = 0;
	cwd = '.';

	requestConfig?: request.CoreOptions = void 0;

	retryCount = 0;
	retryDelay = 0;
	retryBackoffFactor = 1;
	retriesRemaining: number;

	strategyNum = 0;
	strategyDelay = 0;
	isStreaming = false;

	address: Address<InternalHeaders>;
	onKill: (err?: any) => void;
	onStream: (result: CacheResult) => void;
	errored: (err: CachedError | NodeJS.ErrnoException) => void;

	buffer?: BufferStream;

}


text:
using System;

namespace git.jedinja.monomyo.SDK
{
	public enum MyoPoseMode
	{
		Disabled = 0,
		Enabled = 1,
	}
}


text:
{% extends 'template.html' %}
{% from 'macros.html' import render_stream %}

{% block title %}Post {{ super() }}{% endblock %}

{% block body %}

Post by {{ stream[0].user.username }}

{{ render_stream(stream) }}

{% endblock %}


text:
class Jotta < Cask
  version :latest
  sha256 :no_check

  url 'https://www.jottacloud.com/software/jottacloud/jottacloud.dmg'
  homepage 'https://www.jottacloud.com/'
  license :closed

  app 'Jotta.app'
end


text:
import os
import unittest
from nose.plugins.doctests import Doctest
from nose.plugins import PluginTester

support = os.path.join(os.path.dirname(__file__), 'support')

class TestDoctestPlugin(PluginTester, unittest.TestCase):
    activate = '--with-doctest'
    args = ['-v']
    plugins = [Doctest()]
    suitepath = os.path.join(support, 'dtt')

    def runTest(self):
        print str(self.output)

        assert 'Doctest: some_mod ... ok' in self.output
        assert 'Doctest: some_mod.foo ... ok' in self.output
        assert 'Ran 2 tests' in self.output
        assert str(self.output).strip().endswith('OK')

class TestDoctestFiles(PluginTester, unittest.TestCase):
    activate = '--with-doctest'
    args = ['-v', '--doctest-extension=.txt']
    plugins = [Doctest()]
    suitepath = os.path.join(support, 'dtt', 'docs')

    def runTest(self):
        print str(self.output)

        expect = [
            'Doctest: doc.txt ... ok',
            'Doctest: errdoc.txt ... FAIL'
            ]
        for line in self.output:
            if not line.strip():
                continue
            if line.startswith('='):
                break
            self.assertEqual(line.strip(), expect.pop(0))

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


text:
#import "HUBComponentResizeObservingView.h"

NS_ASSUME_NONNULL_BEGIN

@interface HUBComponentResizeObservingView ()

@property (nonatomic, assign) CGSize previousSize;
@property (nonatomic, weak, nullable) UIView *previousSuperview;

@end

@implementation HUBComponentResizeObservingView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) {
        self.previousSize = frame.size;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.userInteractionEnabled = NO;
        self.hidden = YES;
    }

    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (CGSizeEqualToSize(self.previousSize, self.frame.size)) {
        return;
    }

    self.previousSize = self.frame.size;
    [self.delegate resizeObservingViewDidResize:self];
}

- (void)didMoveToSuperview
{
    [super didMoveToSuperview];

    // This prevents accidental removal of the view by an API user
    if (self.superview == nil) {
        [self.previousSuperview addSubview:self];
    } else {
        self.previousSuperview = self.superview;
    }
}

@end

NS_ASSUME_NONNULL_END


text:
using VocaDb.Model.Domain;
using VocaDb.Model.Domain.Globalization;
using VocaDb.Model.Domain.Images;

namespace VocaDb.Model.DataContracts {

	// Used for activity feed and comments
	// TODO: name isn't actually needed...
	public class EntryWithImageContract : EntryWithNameAndVersionContract, IEntryImageInformation {

		public EntryWithImageContract(IEntryWithNames entry, string mime, string songThumbUrl, ContentLanguagePreference languagePreference)
			: base(entry, languagePreference) {

			Mime = mime;
			SongThumbUrl = songThumbUrl;

		}

		public string Mime { get; set;}

		public string SongThumbUrl { get; set; }

	}

}


text:
<resources>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@color/colorPrimary</item>
    </style>
    <style name="ForecastListStyle">
        <item name="android:choiceMode">singleChoice</item>
    </style>
    <!-- Settings activity theme. -->
        <style name="SettingsTheme" parent="@android:style/Theme.Material.Light.DarkActionBar">
                <item name="android:colorPrimary">@color/colorPrimary</item>
                <item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
            </style>
</resources>


text:
module FcrepoAdmin::DatastreamsHelper
  include FcrepoAdmin::Helpers::DatastreamsHelperBehavior
end


text:
var handler = require('./handler'),
    statusPlugin = {
    register: function (server, options, next) {
        server.route({
            method: 'GET',
            path: '/status/api',
            handler: handler.api
        });
        server.route({
            method: 'GET',
            path: '/status/all',
            handler: handler.all,
            config: {
                bind: {
                    datastore: options.datastore
                }
            }
        });

        next();
    }
};

statusPlugin.register.attributes = {
    name: 'simpleStatusPlugin',
    version: '1.0.0'
};

module.exports = statusPlugin;


text:
package com.planet_ink.coffee_mud.Common.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

/**
 * A LegalWarrant is an important object in the triad of LegalBehavior
 * and Law objects, as a part of the CoffeeMud legal system.  A LegalWarrant
 * is created by the LegalBehavior in response to the Law definitions, when
 * it has determined that a mob or player has broken one of the Laws.  The
 * Warrant is then used as a state object following the specific circumstances
 * around the violated law, and its adjudication.  After adjudication, the
 * object is transferred into an Old Warrants cue under the Law to use as
 * a reference for repeat offenders.
 *
 * @see com.planet_ink.coffee_mud.Behaviors.interfaces.LegalBehavior
 * @see com.planet_ink.coffee_mud.Common.interfaces.Law
 */
public interface LegalWarrant extends CMCommon
{
	/**
	 * If the criminal has been identified by an otherwise unoccupied
	 * officer, this will be that officer.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setArrestingOfficer(Area, MOB)
	 *
	 * @return the actual living mob officer who will enforce the warrant
	 */
	public MOB arrestingOfficer();

	/**
	 * If the criminal has been identified by an otherwise unoccupied
	 * officer, this will set that officer.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#arrestingOfficer()
	 *
	 * @param legalArea the Area governing the law
	 * @param mob the actual living mob officer who will enforce the warrant
	 */
	public void setArrestingOfficer(Area legalArea, MOB mob);

	/**
	 * The actual player/mob criminal accused of the crime.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setCriminal(MOB)
	 *
	 * @return the actual player/mob criminal accused of the crime.
	 */
	public MOB criminal();

	/**
	 * Sets the actual player/mob criminal accused of the crime.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#criminal()
	 *
	 * @param mob the actual player/mob criminal accused of the crime.
	 */
	public void setCriminal(MOB mob);

	/**
	 * If applicable, the victim of the crime (or null)
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setVictim(MOB)
	 *
	 * @return the victim of the crime, or null
	 */
	public MOB victim();

	/**
	 * If applicable, sets the victim of the crime (or null)
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#victim()
	 *
	 * @param mob the victim of the crime, or null
	 */
	public void setVictim(MOB mob);

	/**
	 * If applicable, gets the witness of the crime (or null)
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setWitness(MOB)
	 *
	 * @return the witness of the crime or null
	 */
	public MOB witness();

	/**
	 * If applicable, sets the witness of the crime (or null)
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#witness()
	 *
	 * @param mob the witness of the crime (or null)
	 */
	public void setWitness(MOB mob);

	/**
	 * The crime name
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setCrime(String)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#BIT_CRIMENAME
	 *
	 * @return the crime name
	 */
	public String crime();

	/**
	 * Sets the crime name
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#crime()
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#BIT_CRIMENAME
	 *
	 * @param crime the crime name
	 */
	public void setCrime(String crime);

	/**
	 * Gets the full punishment code for the crime
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setPunishment(int)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#getPunishmentParm(int)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#addPunishmentParm(int, String)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#PUNISHMENT_DESCS
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#PUNISHMENTMASK_DESCS
	 *
	 * @return the full punishment code for the crime
	 */
	public int punishmentCode();

	/**
	 * Sets the full punishment code for the crime
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#punishmentCode()
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#getPunishmentParm(int)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#addPunishmentParm(int, String)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#PUNISHMENT_DESCS
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#PUNISHMENTMASK_DESCS
	 *
	 * @param code the full punishment code for the crime
	 */
	public void setPunishment(int code);

	/**
	 * If applicable, returns any parameters associated with a particular
	 * bitmask on the punishment.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#addPunishmentParm(int, String)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#punishmentCode()
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setPunishment(int)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#PUNISHMENTMASK_DESCS
	 *
	 * @param code the punishment mask bitmap code
	 * @return any parameters needed, or null
	 */
	public String getPunishmentParm(int code);

	/**
	 * If applicable, sets any parameters associated with a particular
	 * bitmask on the punishment.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#getPunishmentParm(int)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#punishmentCode()
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setPunishment(int)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#PUNISHMENTMASK_DESCS
	 *
	 * @param code the punishment mask bitmap code
	 * @param parm the parameter to set
	 */
	public void addPunishmentParm(int code, String parm);

	/**
	 * If applicable, returns the number of ticks the punishment calls
	 * for the criminal to remain in jail.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setJailTime(int)
	 *
	 * @return the number of ticks to be jailed for
	 */
	public int jailTime();

	/**
	 * If applicable, sets the number of ticks the punishment calls
	 * for the criminal to remain in jail.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#jailTime()
	 *
	 * @param time the number of ticks to be jailed for
	 */
	public void setJailTime(int time);

	/**
	 * Returns the current state of adjudication.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setState(int)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#STATE_ARRESTING
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#STATE_SEEKING
	 *
	 * @return the current state of adjudication
	 */
	public int state();

	/**
	 * Sets the current state of adjudication.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#state()
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#getLastStateChangeTime()
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#STATE_DETAINING
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#STATE_EXECUTING
	 *
	 * @param state the current state of adjudication.
	 */
	public void setState(int state);

	/**
	 * Returns the number of times this criminal has done this crime.  This
	 * is usually 0 unless it also exists in the old warrants list.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setOffenses(int)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#oldWarrants()
	 *
	 * @return the number of times this criminal has committed this crime.
	 */
	public int offenses();

	/**
	 * Sets the number of times this criminal has done this crime.  This
	 * is usually 0 unless it also exists in the old warrants list.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#offenses()
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#oldWarrants()
	 *
	 * @param num the number of times this criminal has committed this crime.
	 */
	public void setOffenses(int num);

	/**
	 * Returns the last time, in miliseconds since 1970, the criminal has
	 * committed this crime.  Very useful in oldWarrants
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setLastOffense(long)
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#oldWarrants()
	 *
	 * @return the last time this crime was done, in milis
	 */
	public long lastOffense();

	/**
	 * Sets the last time, in miliseconds since 1970, the criminal has
	 * committed this crime.  Very useful in oldWarrants
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#lastOffense()
	 * @see com.planet_ink.coffee_mud.Common.interfaces.Law#oldWarrants()
	 *
	 * @param last the last time this crime was done, in milis
	 */
	public void setLastOffense(long last);

	/**
	 * Returns the time, in milis since 1970, that a trip to the judge
	 * or to the jail was started.  For housekeeping purposes.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setTravelAttemptTime(long)
	 *
	 * @return the milis time since the trip began
	 */
	public long travelAttemptTime();

	/**
	 * Sets the time, in milis since 1970, that a trip to the judge
	 * or to the jail was started.  For housekeeping purposes.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#travelAttemptTime()
	 *
	 * @param time the milis time since the trip began
	 */
	public void setTravelAttemptTime(long time);

	/**
	 * Returns the warning message given to the criminal by the officer.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setWarnMsg(String)
	 *
	 * @return the warning msg given
	 */
	public String warnMsg();

	/**
	 * Sets the warning message given to the criminal by the officer.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#warnMsg()
	 *
	 * @param msg the warning msg given
	 */
	public void setWarnMsg(String msg);

	/**
	 * Sets the room into which this criminal will be jailed.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#jail()
	 *
	 * @param R the room into which this criminal will be jailed.
	 */
	public void setJail(Room R);

	/**
	 * Returns the room into which this criminal will be jailed.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setJail(Room)
	 *
	 * @return the room into which this criminal will be jailed.
	 */
	public Room jail();

	/**
	 * Returns the room into which this criminal will be released after jail.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setReleaseRoom(Room)
	 *
	 * @return the room into which this criminal will be released after jail.
	 */
	public Room releaseRoom();

	/**
	 * Sets the room into which this criminal will be released after jail.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#releaseRoom()
	 *
	 * @param R the room into which this criminal will be released after jail.
	 */
	public void setReleaseRoom(Room R);

	/**
	 * Returns the real time in ms when the state last changed.
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setState(int)
	 *
	 * @return the real time in ms when the state last changed.
	 */
	public long getLastStateChangeTime();

	/**
	 * Returns the real time in ms when the warrant can no longer be ignored
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#setIgnoreUntilTime(long)
	 *
	 * @return the real time in ms when the warrant can no longer be ignored
	 */
	public long getIgnoreUntilTime();

	/**
	 * Sets the real time in ms when the warrant can no longer be ignored
	 *
	 * @see com.planet_ink.coffee_mud.Common.interfaces.LegalWarrant#getIgnoreUntilTime()
	 *
	 * @param time the real time in ms when the warrant can no longer be ignored
	 */
	public void setIgnoreUntilTime(long time);
}


text:
<!DOCTYPE html>

  {% include head.html %}

      {% include header.html %}

        {{ content }}

      {% include footer.html %}


text:
package fs2

import scala.concurrent.ExecutionContext

import cats.Traverse
import cats.implicits.{catsSyntaxEither => _, _}
import cats.effect.{Effect, IO, Sync}
import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}

/** Provides utilities for asynchronous computations. */
package object async {

  /**
    * Creates a new continuous signal which may be controlled asynchronously,
    * and immediately sets the value to `initialValue`.
    */
  def signalOf[F[_]: Effect, A](initialValue: A)(
      implicit ec: ExecutionContext): F[mutable.Signal[F, A]] =
    mutable.Signal(initialValue)

  /** Creates a `[[mutable.Semaphore]]`, initialized to the given count. */
  def semaphore[F[_]: Effect](initialCount: Long)(
      implicit ec: ExecutionContext): F[mutable.Semaphore[F]] =
    mutable.Semaphore(initialCount)

  /** Creates an unbounded asynchronous queue. See [[mutable.Queue]] for more documentation. */
  def unboundedQueue[F[_]: Effect, A](implicit ec: ExecutionContext): F[mutable.Queue[F, A]] =
    mutable.Queue.unbounded[F, A]

  /**
    * Creates a bounded asynchronous queue. Calls to `enqueue1` will wait until the
    * queue's size is less than `maxSize`. See [[mutable.Queue]] for more documentation.
    */
  def boundedQueue[F[_]: Effect, A](maxSize: Int)(
      implicit ec: ExecutionContext): F[mutable.Queue[F, A]] =
    mutable.Queue.bounded[F, A](maxSize)

  /**
    * Creates a synchronous queue, which always has size 0. Any calls to `enqueue1`
    * block until there is an offsetting call to `dequeue1`. Any calls to `dequeue1`
    * block until there is an offsetting call to `enqueue1`.
    */
  def synchronousQueue[F[_], A](implicit F: Effect[F],
                                ec: ExecutionContext): F[mutable.Queue[F, A]] =
    mutable.Queue.synchronous[F, A]

  /**
    * Creates a queue that functions as a circular buffer. Up to `size` elements of
    * type `A` will accumulate on the queue and then it will begin overwriting
    * the oldest elements. Thus an enqueue process will never wait.
    * @param maxSize The size of the circular buffer (must be > 0)
    */
  def circularBuffer[F[_], A](maxSize: Int)(implicit F: Effect[F],
                                            ec: ExecutionContext): F[mutable.Queue[F, A]] =
    mutable.Queue.circularBuffer[F, A](maxSize)

  /**
    * Converts a discrete stream to a signal. Returns a single-element stream.
    *
    * Resulting signal is initially `initial`, and is updated with latest value
    * produced by `source`. If `source` is empty, the resulting signal will always
    * be `initial`.
    *
    * @param source   discrete stream publishing values to this signal
    */
  def hold[F[_], A](initial: A, source: Stream[F, A])(
      implicit F: Effect[F],
      ec: ExecutionContext): Stream[F, immutable.Signal[F, A]] =
    Stream.eval(signalOf[F, A](initial)).flatMap { sig =>
      Stream(sig).concurrently(source.evalMap(sig.set))
    }

  /** Defined as `[[hold]](None, source.map(Some(_)))` */
  def holdOption[F[_]: Effect, A](source: Stream[F, A])(
      implicit ec: ExecutionContext): Stream[F, immutable.Signal[F, Option[A]]] =
    hold(None, source.map(Some(_)))

  /**
    * Creates an asynchronous topic, which distributes each published `A` to
    * an arbitrary number of subscribers. Each subscriber is guaranteed to
    * receive at least the initial `A` or last value published by any publisher.
    */
  def topic[F[_]: Effect, A](initial: A)(implicit ec: ExecutionContext): F[mutable.Topic[F, A]] =
    mutable.Topic(initial)

  /** Creates an empty `Promise[F, A]` */
  def promise[F[_]: Effect, A](implicit ec: ExecutionContext): F[Promise[F, A]] = Promise.empty

  /** Creates an initialized `SyncRef[F,A]`. */
  def refOf[F[_]: Sync, A](a: A): F[Ref[F, A]] = Ref[F, A](a)

  /** Like `traverse` but each `G[B]` computed from an `A` is evaluated in parallel. */
  def parallelTraverse[F[_], G[_], A, B](fa: F[A])(
      f: A => G[B])(implicit F: Traverse[F], G: Effect[G], ec: ExecutionContext): G[F[B]] =
    F.traverse(fa)(f.andThen(start[G, B])).flatMap(F.sequence(_))

  /** Like `sequence` but each `G[A]` is evaluated in parallel. */
  def parallelSequence[F[_], G[_], A](
      fga: F[G[A]])(implicit F: Traverse[F], G: Effect[G], ec: ExecutionContext): G[F[A]] =
    parallelTraverse(fga)(identity)

  /**
    * Begins asynchronous evaluation of `f` when the returned `F[F[A]]` is
    * bound. The inner `F[A]` will block until the result is available.
    */
  def start[F[_], A](f: F[A])(implicit F: Effect[F], ec: ExecutionContext): F[F[A]] =
    promise[F, Either[Throwable, A]].flatMap { p =>
      fork(f.attempt.flatMap(p.complete)).as(p.get.flatMap(F.fromEither))
    }

  /**
    * Lazily memoize `f`. For every time the returned `F[F[A]]` is
    * bound, the effect `f` will be performed at most once (when the
    * inner `F[A]` is bound the first time).
    *
    * @see `start` for eager memoization.
    */
  def once[F[_], A](f: F[A])(implicit F: Effect[F], ec: ExecutionContext): F[F[A]] =
    refOf[F, Option[Promise[F, Either[Throwable, A]]]](None).map { ref =>
      for {
        p <- promise[F, Either[Throwable, A]]
        ca <- ref.modify2 {
          case None =>
            (Some(p), f.attempt.flatTap(p.complete))
          case s @ Some(other) =>
            (s, other.get)
        }
        ma <- ca._2
        a <- F.fromEither(ma)
      } yield a
    }

  /**
    * Begins asynchronous evaluation of `f` when the returned `F[Unit]` is
    * bound. Like `start` but is more efficient.
    */
  def fork[F[_], A](f: F[A])(implicit F: Effect[F], ec: ExecutionContext): F[Unit] =
    F.liftIO(F.runAsync(F.shift *> f) { _ =>
      IO.unit
    })

  /**
    * Like `unsafeRunSync` but execution is shifted to the supplied execution context.
    * This method returns immediately after submitting execution to the execution context.
    */
  def unsafeRunAsync[F[_], A](fa: F[A])(
      f: Either[Throwable, A] => IO[Unit])(implicit F: Effect[F], ec: ExecutionContext): Unit =
    F.runAsync(F.shift(ec) *> fa)(f).unsafeRunSync

  /**
    * Returns an effect that, when run, races evaluation of `fa` and `fb`,
    * and returns the result of whichever completes first. The losing effect
    * continues to execute in the background though its result will be sent
    * nowhere.
    */
  private[fs2] def race[F[_], A, B](fa: F[A], fb: F[B])(implicit F: Effect[F],
                                                        ec: ExecutionContext): F[Either[A, B]] =
    promise[F, Either[Throwable, Either[A, B]]].flatMap { p =>
      def go: F[Unit] = F.delay {
        val refToP = new AtomicReference(p)
        val won = new AtomicBoolean(false)
        val win = (res: Either[Throwable, Either[A, B]]) => {
          // important for GC: we don't reference the promise directly, and the
          // winner destroys any references behind it!
          if (won.compareAndSet(false, true)) {
            val action = refToP.getAndSet(null).complete(res)
            unsafeRunAsync(action)(_ => IO.unit)
          }
        }

        unsafeRunAsync(fa.map(Left.apply))(res => IO(win(res)))
        unsafeRunAsync(fb.map(Right.apply))(res => IO(win(res)))
      }

      go *> p.get.flatMap(F.fromEither)
    }
}


text:
"""
    This contains all of the classes for specific types of analysis

    (c) 2015 Massachusetts Institute of Technology
"""
# Native
import logging
import multiprocessing
logger = logging.getLogger(__name__)

# LO-PHI
import lophi.globals as G

class AnalysisEngine:
    """
        Abstract class used to implement all of our analysis
    """

    analysis_id = 0
    def __init__(self):
        """
            Ensure this class is never used directly
        """
        # Ensure that this class is never initialized
        if self.__class__ == AnalysisEngine:
            raise("Abstract class initialized directly!")

        self.id = AnalysisEngine.analysis_id
        AnalysisEngine.analysis_id += 1

        self.analysis_engine = None

    def start(self):
        """
            Start the specified analysis
        """
        raise NotImplementedError("ERROR: Unimplemented function.")

    def __del__(self):
        if self.analysis_engine is not None:
            logger.debug("Killing analysis before exiting.")
            # Use try because it may already be dead
            try:
                self.analysis_engine.terminate()
                self.analysis_engine.join()
            except:
                pass

    def stop(self):
        """
            Stop our analysis by killing the spawned process
        """
        if self.analysis_engine is None:
            logger.error("No analysis has been started.")
            return

        logger.debug("Killing analysis engine process...")
        self.command_queue.put(G.CTRL_CMD_STOP)

        # Join process to wait for closure
        self.analysis_engine.join(5)

        self.analysis_engine = None

    def pause(self):
        """
            This will temporarily pause our analysis
        """
        if self.analysis_engine is None:
            logger.error("No analysis has been started.")
            return

        logger.debug("Pausing analysis engine...")
        self.command_queue.put(G.CTRL_CMD_PAUSE)

    def resume(self):
        """
            Resume a previously paused analysis
        """
        if self.analysis_engine is None:
            logger.error("No analysis has been started.")
            return

        logger.debug("Resuming analysis engine...")
        self.command_queue.put(G.CTRL_CMD_UNPAUSE)

class LoPhiAnalysisEngine(AnalysisEngine):

    def __init__(self,running_dict=None,services_host=G.RabbitMQ.AMQP_HOST):
        """
            Initialize our analysis engine
        """
        # Save the amqp host that this analysis engine will use.
        self.services_host = services_host

        # Save our shared dict of running processes
        self.running_dict = running_dict

        self.analysis_engine = None

        AnalysisEngine.__init__(self)

    def start(self,
              AnalysisClass,
              lophi_command=None,
              machine=None,
              machine_list=None,
              machine_name=None,
              machine_queue=None):
        """
            Start our analysis using the class that was passed in as an argument
        """

        # Setup a queue to communicate with the process
        self.command_queue = multiprocessing.Queue()

        # Initialize our analysis
        self.analysis_engine = AnalysisClass(self.command_queue,
                                             lophi_command=lophi_command,
                                             services_host=self.services_host,
                                             machine=machine,
                                             machine_name=machine_name,
                                             machine_queue=machine_queue,
                                             machine_list=machine_list,
                                             running_dict=self.running_dict,
                                             lophi_analysis_id=self.id)
        if self.analysis_engine is None:
            logger.error("Analysis could not be started.")
            return False

        # Spawn a new proccess
        self.analysis_engine.start()

        return True

class DiskAnalysisEngine(AnalysisEngine):
    """
        This small class serves as our analysis engine for disk analysis
    """

    def __init__(self,
                 machine,
                 output_queue):
        """
            Initialize our disk analysis

            @param machine: Machine object that we will be performing analysis on
            @param output_queue: Queue that resulting data will be returned on
        """

        if machine.disk is None:
            logger.error("Machine (%s) does not have a disk sensor associated with it to use for analysis."%machine.config.name)
            return None

        # set our variables for later
        self.machine = machine
        self.output_queue = output_queue

        # Initialize the analysis engine
        self.analysis_engine = None

        AnalysisEngine.__init__(self)

    def start(self):
        """
            Start our analysis by spawning a new process that will bridge the
            semantic gap for disk accesses
        """
        from lophi_semanticgap.disk import DiskEngine

        # Setup a queue to communicate with the process
        self.command_queue = multiprocessing.Queue()

        # Connect to our disk sensor
        self.machine.disk._connect()

        # Initialize our Volatility wrapper
        self.analysis_engine = DiskEngine(self.machine,
                                           self.command_queue,
                                           self.output_queue)
        if self.analysis_engine is None:
            logger.error("Analysis could not be started.")
            return

        # Spawn a new proccess
        logger.debug("Starting DiskAnalysisEngine...")
        self.analysis_engine.start()

    def stop(self):
        """
            Stop any disk analysis nicely
        """
        logger.debug("Stopping disk analysis.")

        # Close our socket for the disk sensor
#         self.machine.disk.sata_disable()
        self.machine.disk._disconnect()

        # terminate the analysis (It could be blocking)
        self.analysis_engine.terminate()

        # Join process to wait for closure
        self.analysis_engine.join(5)

        self.analysis_engine = None

        self.command_queue.close()

class DiskCaptureEngine(DiskAnalysisEngine):

    def start(self):
        """
            Start capturing disk traffic for the specified machine
        """

        from lophi_semanticgap.disk import DcapEngine

        # Setup a queue to communicate with the process
        self.command_queue = multiprocessing.Queue()

        try:
            # Connect to our disk sensor
            self.machine.disk._connect()

            # Initialize our Volatility wrapper
            self.analysis_engine = DcapEngine(self.machine,
                                                 command_queue=self.command_queue,
                                                 output_queue=self.output_queue)

            if self.analysis_engine is None:
                logger.error("Analysis could not be started.")
                return

            # Spawn a new proccess
            logger.debug("Starting DiskCaptureEngine...")
            self.analysis_engine.start()
        except:
            print "Got error!"
            import traceback
            traceback.print_exc()

class MemoryAnalysisEngine(AnalysisEngine):
    """
        This small class serves as our analysis engine for memory
    """

    def __init__(self,
                 machine,
                 output_queue,
                 plugins=None,
                 poll_interval=1):
        """
            Initialize our memory analysis

            @param machine: Machine object that we will be performing analysis on
            @param output_queue: Queue that resulting data will be returned on
            @param plugins: Volatility plugins that we want to execute
            @param poll_interval: Time between analysis
        """

        if machine.memory is None:
            logging.error("Machine (%s) does not have a memory sensor associated with it to use for analysis."%machine.config.name)
            return None

        # set our variables for later
        self.machine = machine
        self.output_queue = output_queue
        self.poll_interval = poll_interval

        from lophi_semanticgap.memory import MODULES_DICTIONARY

        # Figure out what plugins we are using
        if plugins is not None:
            self.plugins = plugins
        elif machine.config.volatility_profile in MODULES_DICTIONARY:
            logger.warn("No memory plugins specified.  Defaulting to base set.")
            self.plugins = MODULES_DICTIONARY[machine.config.volatility_profile]
        else:
            logger.error("No memory plugins were specified, and no default plugins could be found for %s."%machine.config.volatility_profile)
            return False

        # Initialize the analysis engine
        self.analysis_engine = None

        AnalysisEngine.__init__(self)

    def start(self):
        """
            Start our analysis by spawning a new process that will poll memory
            at a fixed interval.
        """
        from lophi_semanticgap.memory import VolatilityEngine

        # Setup a queue to communicate with the process
        self.command_queue = multiprocessing.Queue()

        # Initialize our Volatility wrapper
        self.analysis_engine = VolatilityEngine(self.machine,
                                                 self.plugins,
                                                 self.command_queue,
                                                 self.output_queue,
                                                 poll_interval=self.poll_interval)
        if self.analysis_engine is None:
            logger.error("Analysis could not be started.")
            return

        # Spawn a new proccess
        self.analysis_engine.start()

class NetworkCaptureEngine(AnalysisEngine):

    def __init__(self,machine, output_queue):
        """
            Initialize our network capture engine
        """
        self.machine = machine
        self.output_queue = output_queue

        AnalysisEngine.__init__(self)

    def start(self):
        """
            Start capturing network traffic for the specified machine
            (interface)
        """

        from lophi.sensors.network import NetworkCapture

        # Setup a queue to communicate with the process
        self.command_queue = multiprocessing.Queue()

        # Initialize our Volatility wrapper
        self.analysis_engine = NetworkCapture(self.machine,
                                             command_queue=self.command_queue,
                                             output_queue=self.output_queue)

        if self.analysis_engine is None:
            logger.error("Analysis could not be started.")
            return

        # Spawn a new proccess
        self.analysis_engine.start()

    def stop(self):
        """
            Stop any network analysis nicely
        """
        logger.debug("Stopping network analysis.")
        self.analysis_engine.stop()

        # terminate the analysis (It could be blocking)
#         self.analysis_engine.terminate()

        # Join process to wait for closure
        self.analysis_engine.join(5)

        self.analysis_engine = None

        self.command_queue.close()


text:
/**
 * @file
 * Declares the logger used by the compiler.
 */
#pragma once

#include <boost/format.hpp>
#include <string>
#include <iostream>
#include <functional>

namespace puppet { namespace logging {

    /**
     * Macro for logging messages.
     * @param lvl The log level name.
     * @param message The message to log.
     */
    #define LOG(lvl, message, ...) \
    if (logger.would_log(puppet::logging::level::lvl)) { \
        logger.log(puppet::logging::level::lvl, message, ##__VA_ARGS__); \
    }

    /**
     * Represents the log level.
     */
    enum class level
    {
        /**
         * The debug log level.
         */
        debug,
        /**
         * The info log level.
         */
        info,
        /**
         * The notice log level.
         */
        notice,
        /**
         * The warning log level.
         */
        warning,
        /**
         * The error log level.
         */
        error,
        /**
         * The alert log level.
         */
        alert,
        /**
         * The emergency log level.
         */
        emergency,
        /**
         * The critical error log level.
         */
        critical
    };

    /**
     * Reads a log level from an input stream.
     * This is used in boost::lexical_cast<level>.
     * @param in The input stream.
     * @param level The returned log level.
     * @returns Returns the input stream.
     */
    std::istream& operator>>(std::istream& in, logging::level& level);

    /**
     * Produces the printed representation of the logging level.
     * @param out The stream to write.
     * @param level The logging level to print.
     * @return Returns the stream after writing to it.
     */
    std::ostream& operator<<(std::ostream& out, logging::level level);

    /**
     * Implements the base logger.
     */
    struct logger
    {
        /**
         * Constructs a logger.
         */
        logger();

        /**
         * Logs a message.
         * @param level The log level.
         * @param message The message to log.
         */
        void log(logging::level level, std::string const& message);

        /**
         * Logs a message with source context.
         * @param level The log level.
         * @param line The line of the source context.
         * @param column The column of the source context.
         * @param text The context text.
         * @param path The path of the source file.
         * @param message The message to log.
         */
        void log(logging::level level, size_t line, size_t column, std::string const& text, std::string const& path, std::string const& message);

        /**
         * Logs a message.
         * @tparam TArgs The type of the message formatting arguments.
         * @param level The log level.
         * @param format The format of the message to log.
         * @param args The format arguments.
         */
        template <typename... TArgs>
        void log(logging::level level, std::string const& format, TArgs... args)
        {
            if (!would_log(level)) {
                return;
            }
            boost::format message(format);
            log(level, 0, 0, {}, {}, message, std::forward<TArgs>(args)...);
        }

        /**
         * Logs a message.
         * @tparam TArgs The type of the message formatting arguments.
         * @param level The log level.
         * @param line The line of the source context.
         * @param column The column of the source context.
         * @param text The context text.
         * @param path The path of the source file.
         * @param format The format of the message to log.
         * @param args The format arguments.
         */
        template <typename... TArgs>
        void log(logging::level level, size_t line, size_t column, std::string const& text, std::string const& path, std::string const& format, TArgs... args)
        {
            if (!would_log(level)) {
                return;
            }
            boost::format message(format);
            log(level, line, column, text, path, message, std::forward<TArgs>(args)...);
        }

        /**
         * Gets the number of warnings logged.
         * @return Returns the number of warnings logged.
         */
        size_t warnings() const;

        /**
         * Gets the number of errors logged.
         * @return Returns the number of errors logged.
         */
        size_t errors() const;

        /**
         * Gets the current logging level.
         * @return Returns the current logging level.
         */
        logging::level level() const;

        /**
         * Sets the logging level.
         * @param level The new logging level.
         */
        void level(logging::level level);

        /**
         * Resets the error and warning counts.
         */
        void reset();

        /**
         * Determins if the given log level would be logged.
         * @param level The logging level to check.
         * @return Returns true if the logger would log for the given level or false if not.
         */
        bool would_log(logging::level level);

    protected:
        /**
         * Logs a message.
         * @param level The log level.
         * @param line The line of the source context.
         * @param column The column of the source context.
         * @param text The context text.
         * @param path The path of the source file.
         * @param message The message to log.
         */
        virtual void log_message(logging::level level, size_t line, size_t column, std::string const& text, std::string const& path, std::string const& message) = 0;

     private:
        void log(logging::level level, size_t line, size_t column, std::string const& text, std::string const& path, boost::format& message);

        template <typename T, typename... TArgs>
        void log(logging::level level, size_t line, size_t column, std::string const& text, std::string const& path, boost::format& message, T arg, TArgs... args)
        {
            message % std::forward<T>(arg);
            log(level, line, column, text, path, message, std::forward<TArgs>(args)...);
        }

        size_t _warnings;
        size_t _errors;
        logging::level _level;
    };

    /**
     * Base type for stream loggers.
     */
    struct stream_logger : logger
    {
     protected:
        /**
         * Logs a message.
         * @param level The log level.
         * @param line The line of the source context.
         * @param column The column of the source context.
         * @param text The context text.
         * @param path The path of the source file.
         * @param message The message to log.
         */
        virtual void log_message(logging::level level, size_t line, size_t column, std::string const& text, std::string const& path, std::string const& message) override;

        /**
         * Gets the stream to log to based on the message's log level.
         * @param level The log level.
         * @return Returns the stream to log to.
         */
        virtual std::ostream& get_stream(logging::level level) const = 0;

        /**
         * Colorizes for the given log level.
         * @param level The log level to colorize for.
         */
        virtual void colorize(logging::level level) const;

        /**
         * Resets the colorization.
         * @param level The log level that was colorized.
         */
        virtual void reset(logging::level level) const;
    };

    /**
     * Implements a logger that logs to a console.
     */
    struct console_logger : stream_logger
    {
     public:
        /**
         * Constructs a console logger.
         */
        console_logger();

     protected:
        /**
         * Gets the stream to log to based on the message's log level.
         * @param level The log level.
         * @return Returns the stream to log to.
         */
        virtual std::ostream& get_stream(logging::level level) const override;

        /**
         * Colorizes for the given log level.
         * @param level The log level to colorize for.
         */
        virtual void colorize(logging::level level) const override;

        /**
         * Resets the colorization.
         * @param level The log level that was colorized.
         */
        virtual void reset(logging::level level) const override;

     private:
        bool should_colorize(logging::level level) const;
        bool _colorize_stdout;
        bool _colorize_stderr;
    };

}}  // namespace puppet::logger


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="github.nikhilbhutani.okhttp.MainActivity">

    <Button
        android:id="@+id/btnStart"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:text="@string/description" />

    <TextView
        android:id="@+id/txtBytes"
        android:layout_width="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/imgImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        />
</LinearLayout>


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

<title>DialogFindReplace (ARX GUI Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deidentifier.arx.gui.view.impl.menu

Class DialogFindReplace

java.lang.Object

org.eclipse.jface.window.Window

org.eclipse.jface.dialogs.Dialog

org.eclipse.jface.dialogs.TrayDialog

org.eclipse.jface.dialogs.TitleAreaDialog

org.deidentifier.arx.gui.view.impl.menu.DialogFindReplace

All Implemented Interfaces:

org.eclipse.jface.window.IShellProvider

public class DialogFindReplace
extends org.eclipse.jface.dialogs.TitleAreaDialog

A dialog for finding and replacing data items

Nested Class Summary

Nested classes/interfaces inherited from class org.eclipse.jface.window.Window

org.eclipse.jface.window.Window.IExceptionHandler

Field Summary

Fields inherited from class org.eclipse.jface.dialogs.TitleAreaDialog

DLG_IMG_TITLE_BANNER, DLG_IMG_TITLE_ERROR, INFO_MESSAGE, WARNING_MESSAGE

Fields inherited from class org.eclipse.jface.dialogs.Dialog

blockedHandler, buttonBar, DIALOG_DEFAULT_BOUNDS, DIALOG_PERSISTLOCATION, DIALOG_PERSISTSIZE, dialogArea, DLG_IMG_ERROR, DLG_IMG_HELP, DLG_IMG_INFO, DLG_IMG_MESSAGE_ERROR, DLG_IMG_MESSAGE_INFO, DLG_IMG_MESSAGE_WARNING, DLG_IMG_QUESTION, DLG_IMG_WARNING, ELLIPSIS

Fields inherited from class org.eclipse.jface.window.Window

CANCEL, OK

Constructor Summary

Constructors

Constructor and Description

DialogFindReplace(org.eclipse.swt.widgets.Shell parentShell,
                 Model model,
                 DataHandle handle,
                 int column)

Creates a new instance

Method Summary

Methods

Modifier and Type
Method and Description

protected void
buttonPressed(int buttonId)

protected void
configureShell(org.eclipse.swt.widgets.Shell newShell)

protected void
createButtonsForButtonBar(org.eclipse.swt.widgets.Composite parent)

protected org.eclipse.swt.widgets.Control
createContents(org.eclipse.swt.widgets.Composite parent)

protected org.eclipse.swt.widgets.Control
createDialogArea(org.eclipse.swt.widgets.Composite parent)

protected org.eclipse.swt.widgets.Button
getOkButton()

Returns the ok button.

protected org.eclipse.swt.events.ShellListener
getShellListener()

org.apache.commons.math3.util.Pair<java.lang.String,java.lang.String>
getValue()

Returns a pair containing the string to be found and the string with
 which it is to be replaced

void
setErrorMessage(java.lang.String message)

Methods inherited from class org.eclipse.jface.dialogs.TitleAreaDialog

getErrorMessage, getInitialSize, getMessage, getTitleArea, getTitleImageLabel, setMessage, setMessage, setTitle, setTitleAreaColor, setTitleImage

Methods inherited from class org.eclipse.jface.dialogs.TrayDialog

closeTray, createButtonBar, createHelpControl, getLayout, getTray, handleShellCloseEvent, isDialogHelpAvailable, isHelpAvailable, openTray, setDialogHelpAvailable, setHelpAvailable

Methods inherited from class org.eclipse.jface.dialogs.Dialog

applyDialogFont, cancelPressed, close, convertHeightInCharsToPixels, convertHeightInCharsToPixels, convertHorizontalDLUsToPixels, convertHorizontalDLUsToPixels, convertVerticalDLUsToPixels, convertVerticalDLUsToPixels, convertWidthInCharsToPixels, convertWidthInCharsToPixels, create, createButton, dialogFontIsDefault, getBlockedHandler, getButton, getButtonBar, getCancelButton, getDialogArea, getDialogBoundsSettings, getDialogBoundsStrategy, getImage, getInitialLocation, getOKButton, initializeBounds, initializeDialogUnits, isResizable, okPressed, setBlockedHandler, setButtonLayoutData, setButtonLayoutFormData, shortenText

Methods inherited from class org.eclipse.jface.window.Window

canHandleShellCloseEvent, constrainShellSize, createShell, getConstrainedShellBounds, getContents, getDefaultImage, getDefaultImages, getDefaultOrientation, getParentShell, getReturnCode, getShell, getShellStyle, getWindowManager, handleFontChange, open, setBlockOnOpen, setDefaultImage, setDefaultImages, setDefaultModalParent, setDefaultOrientation, setExceptionHandler, setParentShell, setReturnCode, setShellStyle, setWindowManager

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DialogFindReplace

public DialogFindReplace(org.eclipse.swt.widgets.Shell parentShell,
                 Model model,
                 DataHandle handle,
                 int column)

Creates a new instance

Parameters:

parentShell -

handle -

column -

Method Detail

getValue

public org.apache.commons.math3.util.Pair<java.lang.String,java.lang.String> getValue()

Returns a pair containing the string to be found and the string with
 which it is to be replaced

Returns:

the value

setErrorMessage

public void setErrorMessage(java.lang.String message)

Overrides:

setErrorMessage in class org.eclipse.jface.dialogs.TitleAreaDialog

buttonPressed

protected void buttonPressed(int buttonId)

Overrides:

buttonPressed in class org.eclipse.jface.dialogs.Dialog

configureShell

protected void configureShell(org.eclipse.swt.widgets.Shell newShell)

Overrides:

configureShell in class org.eclipse.jface.window.Window

createButtonsForButtonBar

protected void createButtonsForButtonBar(org.eclipse.swt.widgets.Composite parent)

Overrides:

createButtonsForButtonBar in class org.eclipse.jface.dialogs.Dialog

createContents

protected org.eclipse.swt.widgets.Control createContents(org.eclipse.swt.widgets.Composite parent)

Overrides:

createContents in class org.eclipse.jface.dialogs.TitleAreaDialog

createDialogArea

protected org.eclipse.swt.widgets.Control createDialogArea(org.eclipse.swt.widgets.Composite parent)

Overrides:

createDialogArea in class org.eclipse.jface.dialogs.TitleAreaDialog

getOkButton

protected org.eclipse.swt.widgets.Button getOkButton()

Returns the ok button.

Returns:

the ok button

getShellListener

protected org.eclipse.swt.events.ShellListener getShellListener()

Overrides:

getShellListener in class org.eclipse.jface.window.Window

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
/////////////////////////////////////////////////////////////////////////
//
//
//	Render Preset Interface
//
//	Created 5/14/2003	Tom Burke
//

#ifndef	I_RENDER_PRESETS_H
#define I_RENDER_PRESETS_H

#include "maxheap.h"
#include "bitarray.h"

/*! \defgroup renderPresetCatDef Render Preset Category Defines
\brief Each set of properties that can be saved is called a Category.
\remarks For example, all the properties in the Common tab of the render dialog are
a single category. Each category has both a name and an index number. The possible
numbers range from 0 to RENDER_PRESETS_CATEGORY_COUNT. Note that some of these are
reserved for internal use.\n
Developers wishing to define custom categories should use a category number RENDER_PRESETS_CUSTOM_CATEGORY_INDEX_BEGIN
or higher.\n\n
A list of categories is represented as a bitarray; if bit N is set to true, this means the category with ID number N is present. */
//@{
#define RENDER_PRESETS_CATEGORY_COUNT				64
#define RENDER_PRESETS_CUSTOM_CATEGORY_INDEX_BEGIN	32
//@}

// return values
//
#define RENDER_PRESETS_SUCCESS				0
#define RP_ERROR_OBSOLETE_FILE				1
#define RP_ERROR_INCOMPATABLE_FILE			2
#define RP_ERROR_CATEGORY_NOT_COMPATABLE	3
#define RP_ERROR_SAVING_FILE				4
#define RP_ERROR_LOADING_FILE				5
#define RP_ERROR_CANCEL						6
#define RP_ERROR_FILE_NOT_FOUND				7

class RenderPresetsContext: public MaxHeapOperators {
public:
	RenderPresetsContext( int version, BitArray categories ) { mVersion = version; mCategories = categories; }
	BitArray GetCategories() { return mCategories; }
	int       GetVersion() { return mVersion; }

private:
	int      mVersion;
	BitArray mCategories;
};

/*! \sa Class Renderer, the Render Preset Category Defines
\par Description:
The Render Preset Manager allows for loading and saving of render presets through the SDK. The manager can be obtained as follows:\n\n
GetCOREInterface()->GetRenderPresetsManager(); */
class IRenderPresetsManager: public MaxHeapOperators {
public:
	enum RendererSpecifier {
		kProduction = 0,
		kMaterial,
		kActiveShade
	};

	typedef enum {
		kUnspecified = -1,
		kLoadAll = 0,
		kLoadNonNodeRefMakers = 1,
		kLoadNone = 2,
	} NodeRefAction;
	//! \brief Destructor
	virtual ~IRenderPresetsManager() {;}

    /*! \brief Save selected categories of render presets to the file
	\remarks This function has the same effect as selecting "Save Preset..." in
		"Rendering->Render Setup->Preset" drop-down list in Max
	\param rendSpecifier Which renderer to save the presets of
	\returns RENDER_PRESETS_SUCCESS on success, or one of the RP_ERROR values if an error occurs */
	virtual int      Save( RendererSpecifier rendSpecifier ) = 0;
	/*! \brief Save selected categories of render presets to the file
	\remarks When calling this function, the user will be presented with a dialog to select
		which presets to save for the specified render category.
	\param rendSpecifier Which renderer to save the presets of
	\param fileName The file to save the user-selected presets to.
	\returns RENDER_PRESETS_SUCCESS on success, or one of the RP_ERROR values if an error occurs */
	virtual int      Save( RendererSpecifier rendSpecifier, const MCHAR * fileName ) = 0;
	/*! \brief Save selected categories of render presets to the file
	\param rendSpecifier Which renderer to save the presets of
	\param fileName The file to save the user-selected presets to.
	\param saveCategories A BitArray specifying the presets categories to be saved.
	\returns RENDER_PRESETS_SUCCESS on success, or one of the RP_ERROR values if an error occurs */
	virtual int      Save( RendererSpecifier rendSpecifier, const MCHAR * fileName, BitArray saveCategories ) = 0;

    /*! \brief Load selected categories of render presets from the file
	\remarks Calling this function has the same effect as selecting "Load Preset..." in
		"Rendering->Render Setup->Preset" drop-down list in Max
	\param rendSpecifier Which renderer to load the presets for
	\returns RENDER_PRESETS_SUCCESS on success, or one of the RP_ERROR values if an error occurs */
	virtual int      Load( RendererSpecifier rendSpecifier ) = 0;
	/*! \brief Load selected categories of render presets from the file
	\remarks Calling this function will display a dialog prompting the user to
		select which presets in fileName to load.
	\param rendSpecifier Which renderer to load the presets for
	\param fileName A path to file to load the render presets from
	\returns RENDER_PRESETS_SUCCESS on success, or one of the RP_ERROR values if an error occurs */
	virtual int      Load( RendererSpecifier rendSpecifier, const MCHAR * fileName ) = 0;
	/*! \brief Load selected categories of render presets from the file
	\remarks Calling this function will pop a dialog prompting the user to
		select which presets in fileName to load.
	\param rendSpecifier Which renderer to load the presets for
	\param fileName A path to file to load the render presets from
	\param loadCategories The preset categories to for the specified renderer
	\param nodeRefAction One of the NodeRefAction enum values
	\returns RENDER_PRESETS_SUCCESS on success, or one of the RP_ERROR values if an error occurs */
	virtual int      Load( RendererSpecifier rendSpecifier, const MCHAR * fileName, BitArray loadCategories, NodeRefAction nodeRefAction = kUnspecified ) = 0;

	/*! \brief  Check to see if file is compatable with current renderer
	\remarks For Example: If the user saves a preset for the Default Scanline Renderer,
		but does NOT choose the category called "Default Scanline Renderer", then the preset is
		considered incompatible with any other renderer. This is because the renderer itself will
		not be saved within the preset, so loading the preset will not change which renderer is
		active; but the render-specific parameters in the preset are not compatible with other renderers.
	\param rendSpecifier The category to check compatability for
	\param fileName The saved render preset file
	\return TRUE if the renderer currently assigned to rendSpecifier can load the presets in fileName */
	virtual int      IsFileCompatible( RendererSpecifier rendSpecifier, const MCHAR * fileName ) = 0;

	// Convert between category index and category name for render preset files

	/*! \brief Retrieve a render presets name based on its ID
	\param fileName The file containing the preset we are looking for the name to
	\param catIndex The ID of the category saved in fileName to retrieve the name of
	\return the name of the specified render preset */
	virtual MCHAR *  MapIndexToCategory( const MCHAR * fileName, int catIndex  ) = 0;
	/*! \brief retrieve a render presets ID based on its name
	\param fileName The file containing the preset we are looking for the ID for
	\param category The name of the category saved in fileName to retrieve the ID of
	\return the ID of the specified render preset */
	virtual int      MapCategoryToIndex( const MCHAR * fileName, const MCHAR* category ) = 0;

	/*! \brief retrieve a render presets name based on its ID for the current renderers
	\param rendSpecifier Which current renderer to query for the preset category name.
	\param catIndex The ID of the render preset to retrieve the name of
	\return the name of the specified render preset */
	virtual MCHAR *  MapIndexToCategory( RendererSpecifier rendSpecifier, int catIndex  ) = 0;
	/*! \brief retrieve a render presets ID based on its name for the current renderers
	\param rendSpecifier Which current renderer to query for the preset category ID.
	\param catIndex The name of the category to retrieve the ID of
	\return the ID of the specified render preset if found, else -1 */
	virtual int      MapCategoryToIndex( RendererSpecifier rendSpecifier, const MCHAR* category ) = 0;

	/*! \brief return a list of all preset category ID's saved in a given preset file.
	\param fileName The file to query for saved preset categories */
	virtual BitArray LoadCategories( const MCHAR * fileName ) = 0; // list of categories saved in the file
	/*! \brief return a list of all preset category names saved in a given preset file.
	\param fileName The file to query for saved preset categories */
	virtual Tab<MCHAR *> LoadCategoryNames( const MCHAR * fileName ) = 0;

	/*! \brief return a list of all preset category ID's that are meaningful to the specified renderer.
	\param rendSpecifier Which current renderer to query for meaningful categories
	\return An array specifying the preset categories ID's that are applicable to the current renderer */
	virtual BitArray SaveCategories( RendererSpecifier rendSpecifier ) = 0;
	/*! \brief return a list of all preset category names that are meaningful to the specified renderer.
	\param rendSpecifier Which current renderer to query for meaningful categories
	\return An array specifying the preset categories ID's that are applicable to the current renderer */
	virtual Tab<MCHAR *> SaveCategoryNames( RendererSpecifier rendSpecifier ) = 0;

	/*! \brief Retrieve the current RenderPresetContext.
	\remarks This is provided so that renderers can tailor their
	save and load methods to accomodate the saving and loading of
	any combination of render preset categories.\n\n
	This method will return NULL unless a render preset is currently being loaded or saved.
	An example usage would be to call this inside a Load() method or post-load callback,
	and if not NULL, check for compatibility by looking at the version number and categories
	of the preset context.
	\return the current RenderPresetContext if present, else NULL. */
	virtual RenderPresetsContext * GetContext() = 0;
};

#endif // I_RENDER_PRESETS_H


text:
@interface FWFilter15 : FWSixInputFilter

@end

@interface FWToasterFilter : GPUImageFilterGroup
{
    GPUImagePicture *imageSource1;
    GPUImagePicture *imageSource2;
    GPUImagePicture *imageSource3;
    GPUImagePicture *imageSource4;
    GPUImagePicture *imageSource5;
}

@end


text:
using content::NavigationController;
using content::WebContents;

TabModalConfirmDialogDelegate::TabModalConfirmDialogDelegate(
    WebContents* web_contents)
    : window_(NULL),
      closing_(false) {
  NavigationController* controller = &web_contents->GetController();
  registrar_.Add(this, content::NOTIFICATION_LOAD_START,
                 content::Source<NavigationController>(controller));
  registrar_.Add(this, content::NOTIFICATION_TAB_CLOSING,
                 content::Source<NavigationController>(controller));
}

TabModalConfirmDialogDelegate::~TabModalConfirmDialogDelegate() {
  // If we end up here, the constrained window has been closed, so make sure we
  // don't close it again.
  window_ = NULL;
  // Make sure everything is cleaned up.
  Cancel();
}

void TabModalConfirmDialogDelegate::Cancel() {
  if (closing_)
    return;
  // Make sure we won't do anything when |Cancel()| or |Accept()| is called
  // again.
  closing_ = true;
  OnCanceled();
  CloseDialog();
}

void TabModalConfirmDialogDelegate::Accept() {
  if (closing_)
    return;
  // Make sure we won't do anything when |Cancel()| or |Accept()| is called
  // again.
  closing_ = true;
  OnAccepted();
  CloseDialog();
}

void TabModalConfirmDialogDelegate::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  // Close the dialog if we load a page (because the action might not apply to
  // the same page anymore) or if the tab is closed.
  if (type == content::NOTIFICATION_LOAD_START ||
      type == content::NOTIFICATION_TAB_CLOSING) {
    Cancel();
  } else {
    NOTREACHED();
  }
}

gfx::Image* TabModalConfirmDialogDelegate::GetIcon() {
  return NULL;
}

string16 TabModalConfirmDialogDelegate::GetAcceptButtonTitle() {
  return l10n_util::GetStringUTF16(IDS_OK);
}

string16 TabModalConfirmDialogDelegate::GetCancelButtonTitle() {
  return l10n_util::GetStringUTF16(IDS_CANCEL);
}

const char* TabModalConfirmDialogDelegate::GetAcceptButtonIcon() {
  return NULL;
}

const char* TabModalConfirmDialogDelegate::GetCancelButtonIcon() {
  return NULL;
}

void TabModalConfirmDialogDelegate::OnAccepted() {
}

void TabModalConfirmDialogDelegate::OnCanceled() {
}

void TabModalConfirmDialogDelegate::CloseDialog() {
  if (window_)
    window_->CloseConstrainedWindow();
}


text:
#ifndef EDK_VIEWBUTTON_H
#define EDK_VIEWBUTTON_H

#ifdef printMessages
#warning "Inside ViewButton"
#endif

#pragma once
#include "TypeDefines.h"
#include "GU/GU.h"
#include "ViewSprite.h"
#include "vector/BinaryTree.h"
#include "Camera2D.h"
#include "fonts/FontMap.h"
#include "pack/FilePackage.h"

#ifdef printMessages
#warning "    Compiling ViewButton"
#endif

/*
//EVENT
//event press button
void eventPressButton(edk::uint32 mouseButton){
    //
    //printf("\nPRESS BUTTON %u",mouseButton);
}
//event releaseButton
void eventReleaseButton(edk::uint32 mouseButton,bool inside){
    //
    //printf("\nRELEASE BUTTON %u",mouseButton);
}
//event holdButton
void eventHoldButton(edk::uint32 mouseButton){
    //
    //printf("\nHOLDING BUTTON %u",mouseButton);
}
//Mouse go Inside Outside
void eventMouseEntryInsideView(edk::vec2f32 point){
    //
}
void eventMouseLeftView(edk::vec2f32 point){
    //
}
void eventMouseMovingInsideView(edk::vec2f32 point){
    //
}
*/

namespace edk{

class ViewButton;
class ButtonCallback{
public:
    virtual void pressButton(edk::ViewButton* button,edk::uint32 mouseButton)=0;
    virtual void releaseButton(edk::ViewButton* button,edk::uint32 mouseButton,bool isInside)=0;
    virtual void holdButton(edk::ViewButton* button,edk::uint32 mouseButton)=0;
};
class ViewButton: public edk::ViewSprite{
    public:
        ViewButton();
        virtual ~ViewButton();
        //set borderSize
        bool setBorderSize(edk::uint32 size);
        //set the callback
        bool setCallback(edk::ButtonCallback* callback);
        //remove callback
        void removeCallback();

        //LOAD SPRITES
//        bool loadSprite(const edk::char8* name);
//        bool loadSprite(edk::char8* name);
        //load pressed sprite
        bool loadSpritePressed(const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSpritePressed(edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSpritePressedFromMemory(const edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSpritePressedFromMemory(edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSpritePressedFromPack(edk::pack::FilePackage* pack,const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSpritePressedFromPack(edk::pack::FilePackage* pack,edk::char8* name,edk::uint32 filter = GU_NEAREST);
        //load UP sprite
        bool loadSpriteUp(const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSpriteUp(edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSpriteUpFromMemory(const edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSpriteUpFromMemory(edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSpriteUpFromPack(edk::pack::FilePackage* pack,const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSpriteUpFromPack(edk::pack::FilePackage* pack,edk::char8* name,edk::uint32 filter = GU_NEAREST);

        //Load button symbol normal
        bool loadSymbol(const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSymbol(edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolFromMemory(const edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolFromMemory(edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolFromPack(edk::pack::FilePackage* pack,const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolFromPack(edk::pack::FilePackage* pack,edk::char8* name,edk::uint32 filter = GU_NEAREST);
        //Load button symbol pressed
        bool loadSymbolPressed(const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolPressed(edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolPressedFromMemory(const edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolPressedFromMemory(edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolPressedFromPack(edk::pack::FilePackage* pack,const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolPressedFromPack(edk::pack::FilePackage* pack,edk::char8* name,edk::uint32 filter = GU_NEAREST);
        //Load button symbol up
        bool loadSymbolUp(const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolUp(edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolUpFromMemory(const edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolUpFromMemory(edk::char8* name,edk::uint8* sprite,edk::uint32 size,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolUpFromPack(edk::pack::FilePackage* pack,const edk::char8* name,edk::uint32 filter = GU_NEAREST);
        bool loadSymbolUpFromPack(edk::pack::FilePackage* pack,edk::char8* name,edk::uint32 filter = GU_NEAREST);

        //DELETE
        //delete the spritePressed
        void deleteSpritePressed();
        //delete the spriteUp
        void deleteSpriteUp();
        //delete all the sprites
        void deleteAllSprites();
        //deleteSymbolNormal
        void deleteSymbol();
        //deleteSymbolPressed
        void deleteSymbolPressed();
        //deleteSymbolUp
        void deleteSymbolUp();
        //deleteAllSymbols
        void deleteAllSymbols();

        //scale the symbol
        void scaleInside(edk::size2f32 size);
        void scaleInside(edk::float32 width,edk::float32 height);

        //set the state
        void setState(edk::uint8 state);
        //On and Off the button
        void on();
        void off();
        bool isOn();

        //TEXT
        //add the text to the button
        bool writeText(const edk::char8* str);
        bool writeText(edk::char8* str);
        //load the textFont
        bool loadFontImage(const edk::char8* name,edk::uint32 filter = GU_NEAREST,edk::color4f32 color = edk::color4f32(1,1,1,1));
        bool loadFontImage(edk::char8* name,edk::uint32 filter = GU_NEAREST,edk::color4f32 color = edk::color4f32(1,1,1,1));
        bool loadFontImageFromMemory(const edk::char8* name,
                                     edk::uint8* image,
                                     edk::uint32 size,
                                     edk::uint32 filter = GU_NEAREST,
                                     edk::color4f32 color = edk::color4f32(1,1,1,1)
                );
        bool loadFontImageFromMemory(edk::char8* name,
                                     edk::uint8* image,
                                     edk::uint32 size,
                                     edk::uint32 filter = GU_NEAREST,
                                     edk::color4f32 color = edk::color4f32(1,1,1,1)
                );

        //remove the buttonText
        void deleteButtonText();

        //save if something happen with the button
        bool wasPressed();
        bool wasReleased();
        bool wasHolded();

        //EVENT
        //event press button
        virtual void eventPressButton(edk::uint32 mouseButton);
        //event releaseButton
        virtual void eventReleaseButton(edk::uint32 mouseButton,bool isInside);
        //event holdButton
        virtual void eventHoldButton(edk::uint32 mouseButton);

        //return is a button
        bool isButton();
    protected:
        //draw the polygon on the scene
        void drawPolygon(rectf32 outsideViewOrigin);
        //mouse events
        virtual void eventMousePressed(edk::vec2f32 point,edk::uint32 button);
        virtual void eventMouseMoved(edk::vec2f32 point,edk::uint32 button);
        virtual void eventMouseReleased(edk::vec2f32 point,edk::uint32 button);
        //Mouse go Inside Outside
        virtual void eventMouseEntryInsideView(edk::vec2f32 point);
        virtual void eventMouseLeftView(edk::vec2f32 point);
    private:
        //Events
        //update the view
        void update(edk::WindowEvents* events);
        //save the buttons pressed to hold the buttons
        edk::vector::BinaryTree<edk::uint32> holdButton;
        //mouse is inside
        bool mouseInside;
        //textures list
        edk::Texture2DList list;
        //sprite button pressed
        edk::uint32 spritePressedCode;
        //sprite mouse up button
        edk::uint32 spriteUpCode;
        //symbom button
        edk::uint32 symbolCode;
        //symbom buttonPressed
        edk::uint32 symbolPressedCode;
        //symbom buttonUp
        edk::uint32 symbolUpCode;
        //size of the symbom
        edk::size2ui32 symbolSize;
        //state of the button
        edk::uint8 stateButton;
        bool buttonOn;

        //fontMap to write some text in the button
        edk::fonts::FontMap text;

        //scale the symbol
        edk::size2f32 insideScale;

        //button callBack
        edk::ButtonCallback* buttonCallback;

        //camera
        edk::Camera2D cam;
        edk::Camera2D camTemp;
        edk::float32 borderTemp;
        edk::rectf32 rectButtonSave;

        //save if something happen with the button
        bool buttonPress;
        bool buttonRelease;
        bool buttonHold;
};
}//end namesoace edk

#endif // VIEWBUTTON_H


text:
.. title:: clang-tidy - bugprone-suspicious-string-compare

bugprone-suspicious-string-compare
==================================

Find suspicious usage of runtime string comparison functions.
This check is valid in C and C++.

Checks for calls with implicit comparator and proposed to explicitly add it.

.. code-block:: c++

    if (strcmp(...))       // Implicitly compare to zero
    if (!strcmp(...))      // Won't warn
    if (strcmp(...) != 0)  // Won't warn

Checks that compare function results (i,e, ``strcmp``) are compared to valid
constant. The resulting value is

.. code::

    <  0    when lower than,
    >  0    when greater than,
    == 0    when equals.

A common mistake is to compare the result to `1` or `-1`.

.. code-block:: c++

    if (strcmp(...) == -1)  // Incorrect usage of the returned value.

Additionally, the check warns if the results value is implicitly cast to a
*suspicious* non-integer type. It's happening when the returned value is used in
a wrong context.

.. code-block:: c++

    if (strcmp(...) < 0.)  // Incorrect usage of the returned value.

Options
-------

.. option:: WarnOnImplicitComparison

   When non-zero, the check will warn on implicit comparison. `1` by default.

.. option:: WarnOnLogicalNotComparison

   When non-zero, the check will warn on logical not comparison. `0` by default.

.. option:: StringCompareLikeFunctions

   A string specifying the comma-separated names of the extra string comparison
   functions. Default is an empty string.
   The check will detect the following string comparison functions:
   `__builtin_memcmp`, `__builtin_strcasecmp`, `__builtin_strcmp`,
   `__builtin_strncasecmp`, `__builtin_strncmp`, `_mbscmp`, `_mbscmp_l`,
   `_mbsicmp`, `_mbsicmp_l`, `_mbsnbcmp`, `_mbsnbcmp_l`, `_mbsnbicmp`,
   `_mbsnbicmp_l`, `_mbsncmp`, `_mbsncmp_l`, `_mbsnicmp`, `_mbsnicmp_l`,
   `_memicmp`, `_memicmp_l`, `_stricmp`, `_stricmp_l`, `_strnicmp`,
   `_strnicmp_l`, `_wcsicmp`, `_wcsicmp_l`, `_wcsnicmp`, `_wcsnicmp_l`,
   `lstrcmp`, `lstrcmpi`, `memcmp`, `memicmp`, `strcasecmp`, `strcmp`,
   `strcmpi`, `stricmp`, `strncasecmp`, `strncmp`, `strnicmp`, `wcscasecmp`,
   `wcscmp`, `wcsicmp`, `wcsncmp`, `wcsnicmp`, `wmemcmp`.