text:
<?php
namespace Craft;

class Fffields_CategoriesService extends BaseApplicationComponent
{

    // Public Methods
    // =========================================================================

    /**
     * Returns the required config for an <categories/> custom tag.
     *
     * @param array $params
     *
     * @return array
     */
    public function getConfig(array $params)
    {

        $field = $params['fieldLayoutField']->getField();

        $id = craft()->templates->namespaceInputId($field->handle, $params['namespace']);
        $name = craft()->templates->namespaceInputName($field->handle, $params['namespace']);
        $settings = $field->getFieldType()->getSettings();

        // Sort out the element criteria object
        $criteria = $params['value'];

        if (!($criteria instanceof ElementCriteriaModel))
        {
            $criteria = craft()->elements->getCriteria(ElementType::Category);
            $criteria->id = false;
        }

        $criteria->status = null;
        $criteria->localeEnabled = null;

        // Transform that criteria model to elements our js can understand
        $elements = $this->transformCriteria($criteria, [
            'name' => $name,
            'context' => 'field'
        ]);

        // Work out any weird selection criteria
        $selectionCriteria = [
            'localeEnabled' => null,
            'locale' => craft()->getLanguage()
        ];

        // Return the config
        $config = [
            'id'             => $id,
            'name'           => $name,
            'elements'       => $elements,
            'source'         => $settings->source,
            'criteria'       => $selectionCriteria,
            'limit'          => $settings->limit,
            'fieldId'        => $field->id,
            'selectionLabel' => ($settings->selectionLabel ? Craft::t($settings->selectionLabel) : Craft::t('Add a category'))
        ];

//        'elementType'        => new ElementTypeVariable($this->getElementType()),
//        'storageKey'         => 'field.'.$this->model->id,
//        'sourceElementId'    => (isset($this->element->id) ? $this->element->id : null),

        return $config;

    }

    /**
     * Transforms a criteria object into an array of elements.
     *
     * @param $criteria
     * @param $params
     *
     * @return array
     */
    public function transformCriteria($criteria, $params)
    {
        $elements = [];

        $disabledElementIds = [];
        if (isset($params['disabledElementIds'])) {
            $disabledElementIds = $params['disabledElementIds'];
        }

        if ($criteria) {
            foreach ($criteria as $element) {
                $elements[] = [
                    'id'           => $element->id,
                    'name'         => $params['name'] . '[]',
                    'context'      => $params['context'],
                    'label'        => HtmlHelper::encode($element),
                    'level'        => $element->level,
                    'parent'       => $element->getParent() ? $element->getParent()->id : null,
                    'disabled'     => in_array($element->id, $disabledElementIds),
                ];
            }
        }

        return $elements;
    }

}


text:
<?php

namespace Backap\Console;

use Backap\Backap;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;

class Application extends BaseApplication
{
	private static $logo = '<primary>
    ____  ___   ________ __ ___    ____
   / __ )/   | / ____/ //_//   |  / __ \
  / __  / /| |/ /   / ,<  / /| | / /_/ /
 / /_/ / ___ / /___/ /| |/ ___ |/ ____/
/_____/_/  |_\____/_/ |_/_/  |_/_/
</primary>
';

	public function __construct()
	{
		parent::__construct('Backap', Backap::getVersion());
	}

    /**
     * {@inheritDoc}
     */
    public function run(InputInterface $input = null, OutputInterface $output = null)
    {
        if (null === $output) {
            $output = new ConsoleOutput();
        }
        return parent::run($input, $output);
    }

    public function getHelp()
    {
        return self::$logo . parent::getHelp();
    }
}

redpajama_set_name: RedPajamaGithub


text:
create or replace view vw_dashboard_reservations_interlendingbyauthorityandmonthanditemtype as
select
    to_char(h.date_available, 'YYYYMM') as month_available,
    h.item_authority,
    h.pickup_authority,
    h.item_type,
    count(h.key) as number_of_holds
from vw_holds_interlending h
group by month_available, item_authority, pickup_authority, h.item_type
order by month_available, item_authority, pickup_authority, h.item_type;


text:
/*
+----------------------------------------------------------------------+
| Swoole                                                               |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license,    |
| that is bundled with this package in the file LICENSE, and is        |
| available through the world-wide-web at the following url:           |
| http://www.apache.org/licenses/LICENSE-2.0.html                      |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to       |
| license@swoole.com so we can mail you a copy immediately.            |
+----------------------------------------------------------------------+
| Author: Tianfeng Han  <mikan.tenny@gmail.com>                        |
+----------------------------------------------------------------------+
*/

#include "phpx.h"
#include "strHandle.h"
#include "strRW.h"
#include "iostream"

using namespace php;
using namespace std;

void executeCMD(const char *cmd, char *result);

Array parsePackageInfo(char *infoText);

void Apk_construct(Object &_this, Args &args, Variant &retval);

void Apk_apkInfo(Object &_this, Args &args, Variant &retval);

PHPX_EXTENSION()
{
	Extension *ext = new Extension("test", "0.0.1");

	ext->onStart = [ext]
	{
		Class *apk = new Class("Apk");
		/**
		* 注册构造方法
		*/
		apk->addMethod("__construct", Apk_construct, CONSTRUCT);
		/**
		* 普通方法
		*/
		apk->addMethod(PHPX_ME(Apk, apkInfo));

		ext->registerClass(apk);
	};

	return ext;
}

void Apk_construct(Object &_this, Args &args, Variant &retval)
{
	_this.set("path", args[0]);
}

void Apk_apkInfo(Object &_this, Args &args, Variant &retval)
{
	string apkPath = _this.get("path").toCString();
	string cmd = "";
	string fullPath = "E:\\php-7.1.8\\aapt.exe d badging " + apkPath;
	cout << fullPath << endl;
	Array apkInfo;
	char result[1000000];
	executeCMD(fullPath.c_str(), result);
	apkInfo = parsePackageInfo(result);
	retval = apkInfo;
}

void executeCMD(const char *cmd, char *result)
{
	char buf_ps[1024];
	char ps[1024] = { 0 };
	FILE *ptr;
	strcpy(ps, cmd);
	if ((ptr = popen(ps, "r")) != NULL)
	{
		while (fgets(buf_ps, 1024, ptr) != NULL)
		{
			//         可以通过这行来获取shell命令行中的每一行的输出
			//         printf("%s", buf_ps);
			strcat(result, buf_ps);
			if (strlen(result)>1024)
				break;
		}
		pclose(ptr);
		ptr = NULL;
	}
	else
	{
		printf("popen %s error\n", ps);
	}
}
Array parsePackageInfo(char *infoText) {
	Array packageInfo;
	string infoString = infoText;
	string_replace(infoString, " ", "");
	packageInfo.set("packageNname", getMiddleStr(infoString, "package:name='", "'"));
	packageInfo.set("versionCode", getMiddleStr(infoString, "versionCode='", "'"));
	packageInfo.set("versionName", getMiddleStr(infoString, "versionName='", "'"));
	packageInfo.set("sdkVersion", getMiddleStr(infoString, "sdkVersion:'", "'"));
	packageInfo.set("targetSdkVersion", getMiddleStr(infoString, "targetSdkVersion:'", "'"));
	packageInfo.set("applicationLabel", getMiddleStr(infoString, "application-label:'", "'"));
	packageInfo.set("applicationLabelZhCN", getMiddleStr(infoString, "application-label-zh_CN:'", "'"));
	packageInfo.set("launchableActivityName", getMiddleStr(infoString, "launchable-activity:name='", "'"));
	packageInfo.set("icon", getMiddleStr(infoString, "icon='", "'"));
	return packageInfo;
}


text:
<?php if(!defined('BASEPATH')) exit("No direct script access allowed");

class Edu extends CI_Controller {
    function __construct() {
        parent::__construct();
    }

    public function index() {
        $data['menu'] = 3;

        $this->load->view('templates/header', $data);
        $this->load->view('edu/index');
        $this->load->view('edu/main_content');
        $this->load->view('templates/footer');
    }

    public function main() {
        $data['menu'] = 3;

        $this->load->view('templates/header', $data);
        $this->load->view('edu/main');
        $this->load->view('edu/main_content');
        $this->load->view('templates/footer');
    }

    public function education() {
        $data['menu'] = 3;

        $this->load->view('templates/header', $data);
        $this->load->view('edu/list');
        $this->load->view('templates/footer');
    }
}

?>


text:
/**
* @overview AdvTxt-telnet is a telnet interface for testing AdvTxt on a local
*  network. You know, with friends. Has absolutely no security.
*
* @author Nathan Wittstock <code@fardogllc.com>
* @license MIT License - See file 'LICENSE' in this project.
* @version 0.0.3
*/
'use strict';

var telnet = require('telnet');
var i18n = new (require('i18n-2'))({ locales: ['en']});

var advtxt = {}

/**
 * Constructs a new AdvTxt-telnet server
 *
 * @since 0.0.1
 * @constructor
 * @param {advtxt} advtxt - The advtxt instance to be used.
 * @param {object} opt - An object containing options.
 */
exports = module.exports = advtxt.TelnetClient = function (advtxt, opt) {
	var self = this;

	self.advtxt= advtxt;

	self.telnetserver = telnet.createServer(self.clientConnected.bind(self)).listen(6223);
  console.log("Starting Telnet Server…");
};

/**
 * Processes text that has come in via the telnet. Generates a {command} object.
 *
 * @since 0.0.1
 * @param {string} commandText - The raw text command that was received.
 */
advtxt.TelnetClient.prototype.processCommand = function (commandText, client) {
	var self = this;

	// build the command object
	var command = {
		command: commandText,
		player: client.username,
    replies: [],
		done: function(command) {
      var message = "";
      command.replies.forEach(function (reply) {
        message += reply + " ";
      });
			var messageLength = message.length + 17;
			if (messageLength > 140) messageLength = "!!!" + messageLength + "!!!";
			client.write(message + '(' + messageLength + ')\n');
		}
	};

	// send it off to advtxt's command processor
	self.advtxt.processCommand(command);
};

/**
 * Receives the client when a new person connects to the telnet server.
 *
 * @since 0.0.1
 * @param {client} client - The telnet client that has connected.
 */
advtxt.TelnetClient.prototype.clientConnected = function(client) {
	var self = this;

	// make unicode chars transmit correctly
	client.do.transmit_binary();

	// listen for the actual data from the client
  client.on('data', function (b) {
		var self = this;

		// make the buffer into a string for consumption by advtxt
		b = b.toString('utf8').replace(/\r?\n/g, '\r\n');

		// if we haven't seen a username yet, we need to set one. the client is
		// just trusted here.
		if (typeof client.username === 'undefined') {
			client.username = b;
			client.write('Username is now ' + client.username);
		}
		// otherwise, process the command
		else {
			self.processCommand(b, client);
		}
  }.bind(self));

	// give a friendly message on first connection, and ask for username
  client.write('\nConnected to AdvTxt server!\nUsername? ');
};


text:
static const NSInteger kInvalidSelection = NSIntegerMin;

@interface NIRadioGroup()
@property (nonatomic, readonly, weak) UIViewController* controller;
@property (nonatomic, readonly, strong) NSMutableDictionary* objectMap;
@property (nonatomic, readonly, strong) NSMutableSet* objectSet;
@property (nonatomic, readonly, strong) NSMutableArray* objectOrder;
@property (nonatomic, assign) BOOL hasSelection;
@property (nonatomic, readonly, strong) NSMutableSet* forwardDelegates;
@end

@implementation NIRadioGroup

@synthesize selectedIdentifier = _selectedIdentifier;

- (id)initWithController:(UIViewController *)controller {
    if ((self = [super init])) {
        _controller = controller;
        _objectMap = [[NSMutableDictionary alloc] init];
        _objectSet = [[NSMutableSet alloc] init];
        _objectOrder = [[NSMutableArray alloc] init];
        _forwardDelegates = NICreateNonRetainingMutableSet();

        _tableViewCellSelectionStyle = UITableViewCellSelectionStyleBlue;
    }
    return self;
}

- (id)init {
    return [self initWithController:nil];
}

#pragma mark - Private

- (id)keyForIdentifier:(NSInteger)identifier {
    return [NSNumber numberWithInteger:identifier];
}

#pragma mark - NICellObject

- (Class)cellClass {
    return [NIRadioGroupCell class];
}

- (UITableViewCellStyle)cellStyle {
    return UITableViewCellStyleValue1;
}

#pragma mark - Forward Invocations

- (BOOL)shouldForwardSelector:(SEL)selector {
    struct objc_method_description description;
    description = protocol_getMethodDescription(@protocol(UITableViewDelegate), selector, NO, YES);
    return (description.name != NULL && description.types != NULL);
}

- (BOOL)respondsToSelector:(SEL)selector {
    if ([super respondsToSelector:selector]) {
        return YES;

    } else if ([self shouldForwardSelector:selector]) {
        for (id delegate in self.forwardDelegates) {
            if ([delegate respondsToSelector:selector]) {
                return YES;
            }
        }
    }
    return NO;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
    NSMethodSignature *signature = [super methodSignatureForSelector:selector];
    if (signature == nil) {
        for (id delegate in self.forwardDelegates) {
            if ([delegate respondsToSelector:selector]) {
                signature = [delegate methodSignatureForSelector:selector];
            }
        }
    }
    return signature;
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    BOOL didForward = NO;

    if ([self shouldForwardSelector:invocation.selector]) {
        for (id delegate in self.forwardDelegates) {
            if ([delegate respondsToSelector:invocation.selector]) {
                [invocation invokeWithTarget:delegate];
                didForward = YES;
                break;
            }
        }
    }

    if (!didForward) {
        [super forwardInvocation:invocation];
    }
}

- (id<UITableViewDelegate>)forwardingTo:(id<UITableViewDelegate>)forwardDelegate {
    [self.forwardDelegates addObject:forwardDelegate];
    return self;
}

- (void)removeForwarding:(id<UITableViewDelegate>)forwardDelegate {
    [self.forwardDelegates removeObject:forwardDelegate];
}

#pragma mark - Public

- (id)mapObject:(id)object toIdentifier:(NSInteger)identifier {
    NIDASSERT(nil != object);
    NIDASSERT(identifier != kInvalidSelection);
    NIDASSERT(![self isObjectInRadioGroup:object]);
    if (nil == object) {
        return nil;
    }
    if (kInvalidSelection == identifier) {
        return nil;
    }
    if ([self isObjectInRadioGroup:object]) {
        return nil;
    }
    [self.objectMap setObject:object forKey:[self keyForIdentifier:identifier]];
    [self.objectSet addObject:object];
    [self.objectOrder addObject:object];
    return object;
}

- (void)setSelectedIdentifier:(NSInteger)selectedIdentifier {
    id key = [self keyForIdentifier:selectedIdentifier];
    NIDASSERT(nil != [self.objectMap objectForKey:key]);
    if (nil != [self.objectMap objectForKey:key]) {
        _selectedIdentifier = selectedIdentifier;
        self.hasSelection = YES;
    } else {
        // If we set an invalid identifier then clear the current selection.
        self.hasSelection = NO;
    }
}

- (NSInteger)selectedIdentifier {
    return self.hasSelection ? _selectedIdentifier : kInvalidSelection;
}

- (void)clearSelection {
    self.hasSelection = NO;
}

- (BOOL)isObjectInRadioGroup:(id)object {
    if (nil == object) {
        return NO;
    }
    return [self.objectSet containsObject:object];
}

- (BOOL)isObjectSelected:(id)object {
    if (nil == object) {
        return NO;
    }
    NIDASSERT(nil != object);
    NIDASSERT([self isObjectInRadioGroup:object]);
    NSArray* keys = [self.objectMap allKeysForObject:object];
    NSInteger selectedIdentifier = self.selectedIdentifier;
    for (NSNumber* key in keys) {
        if ([key intValue] == selectedIdentifier) {
            return YES;
        }
    }
    return NO;
}

- (NSInteger)identifierForObject:(id)object {
    if (nil == object) {
        return NO;
    }
    NIDASSERT(nil != object);
    NIDASSERT([self isObjectInRadioGroup:object]);
    NSArray* keys = [self.objectMap allKeysForObject:object];
    return keys.count > 0 ? [[keys objectAtIndex:0] intValue] : kInvalidSelection;
}

- (NSArray *)allObjects {
    return [self.objectOrder copy];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NIDASSERT([tableView.dataSource isKindOfClass:[NITableViewModel class]]);
    if ([tableView.dataSource isKindOfClass:[NITableViewModel class]]) {
        NITableViewModel* model = (NITableViewModel *)tableView.dataSource;
        id object = [model objectAtIndexPath:indexPath];
        if ([self isObjectInRadioGroup:object]) {
            cell.accessoryType = ([self isObjectSelected:object]
                                  ? UITableViewCellAccessoryCheckmark
                                  : UITableViewCellAccessoryNone);
            cell.selectionStyle = self.tableViewCellSelectionStyle;
        }
    }

    // Forward the invocation along.
    for (id<UITableViewDelegate> delegate in self.forwardDelegates) {
        if ([delegate respondsToSelector:_cmd]) {
            [delegate tableView:tableView willDisplayCell:cell forRowAtIndexPath:indexPath];
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NIDASSERT([tableView.dataSource isKindOfClass:[NITableViewModel class]]);
    if ([tableView.dataSource isKindOfClass:[NITableViewModel class]]) {
        NITableViewModel* model = (NITableViewModel *)tableView.dataSource;
        id object = [model objectAtIndexPath:indexPath];

        if (object == self) {
            // You must provide a controller in the initWithController: initializer.
            NIDASSERT(nil != self.controller);

            NIRadioGroupController* controller = [[NIRadioGroupController alloc] initWithRadioGroup:self tappedCell:(id<NICell>)[tableView cellForRowAtIndexPath:indexPath]];
            controller.title = self.controllerTitle;

            BOOL shouldPush = YES;
            // Notify the delegate that the controller is about to appear.
            if ([self.delegate respondsToSelector:@selector(radioGroup:radioGroupController:willAppear:)]) {
                shouldPush = [self.delegate radioGroup:self radioGroupController:controller willAppear:YES];
            }

            if (shouldPush) {
                [self.controller.navigationController pushViewController:controller animated:YES];
            }

        } else if ([self isObjectInRadioGroup:object]) {
            NSInteger newSelection = [self identifierForObject:object];

            if (newSelection != self.selectedIdentifier) {
                [self setSelectedIdentifier:newSelection];

                // It's easiest to simply reload the visible table cells. Reloading only the radio group
                // cells would require iterating through the visible cell objects and determining whether
                // each was in the radio group. This is more complex behavior that should be relegated to
                // the controller.
                [tableView reloadRowsAtIndexPaths:tableView.indexPathsForVisibleRows
                                 withRowAnimation:UITableViewRowAnimationNone];

                // After we reload the table view the selection will be lost, so set the selection again.
                [tableView selectRowAtIndexPath:indexPath
                                       animated:NO
                                 scrollPosition:UITableViewScrollPositionNone];

                [self.delegate radioGroup:self didSelectIdentifier:newSelection];
            }

            // Fade the selection out.
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
        }
    }

    // Forward the invocation along.
    for (id<UITableViewDelegate> delegate in self.forwardDelegates) {
        if ([delegate respondsToSelector:_cmd]) {
            [delegate tableView:tableView didSelectRowAtIndexPath:indexPath];
        }
    }
}

@end

@implementation NIRadioGroupCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
        self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return self;
}

- (void)prepareForReuse {
    [super prepareForReuse];

    self.textLabel.text = nil;
    self.detailTextLabel.text = nil;
}

- (BOOL)shouldUpdateCellWithObject:(NIRadioGroup *)radioGroup {
    self.selectionStyle = radioGroup.tableViewCellSelectionStyle;

    // You should provide a cell title for the radio group.
    NIDASSERT(NIIsStringWithAnyText(radioGroup.cellTitle));
    self.textLabel.text = radioGroup.cellTitle;

    if ([radioGroup.delegate respondsToSelector:@selector(radioGroup:textForIdentifier:)]) {
        self.detailTextLabel.text = [radioGroup.delegate radioGroup:radioGroup
                                                  textForIdentifier:radioGroup.selectedIdentifier];
    }
    return YES;
}

@end


text:
This is an application to demonstrate my understanding and ability with Ruby on Rails. It should be hosted and viewable online [at Heroku.](https://atogapp4ba.herokuapp.com/)

NOTE: Sign up requires email verification and only works in a development environment as Heroku is not currently configured for SMTP. Please use the example user to login: user: example@fakemail.org, pass: password


text:
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import Seo from "../components/seo"
import { MarkdownContent } from "../components/elements"

export default function BlogPost({ data }) {
  const post = data.markdownRemark
  const title = post.frontmatter.title;
  const subtitle = `${post.frontmatter.date} - ${post.fields.readingTime.text}`;

  return (
    <Layout siteTitle={title} siteSubtitle={subtitle}>
      <Seo
        title={title}
        description={post.frontmatter.description || post.excerpt}
      />
      <MarkdownContent dangerouslySetInnerHTML={{ __html: post.html }} />
    </Layout>
  )
}

export const pageQuery = graphql`
  query($path: String!) {
    markdownRemark(fields: { slug: { eq: $path } }) {
      html
      excerpt(pruneLength: 160)
      frontmatter {
        date(formatString: "DD MMMM, YYYY")
        title
      }
      fields {
        slug
        readingTime {
          text
        }
      }
    }
  }
`


text:
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
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.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Spell_FeignInvisibility extends Spell
{
	public String ID() { return "Spell_FeignInvisibility"; }
	public String name(){return "Feign Invisibility";}
	public String displayText(){return "(Improved Invisibility)";}
	public int abstractQuality(){ return Ability.QUALITY_OK_OTHERS;}
	protected int canAffectCode(){return CAN_MOBS;}
	public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_ILLUSION;}

	public void unInvoke()
	{
		// undo the affects of this spell
		if((affected==null)||(!(affected instanceof MOB)))
			return;
		MOB mob=(MOB)affected;
		super.unInvoke();

		if(canBeUninvoked())
			mob.tell("You begin to fade back into view.");
	}

	public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel)
	{
		MOB target=this.getTarget(mob,commands,givenTarget);
		if(target==null) return false;

		// the invoke method for spells receives as
		// parameters the invoker, and the REMAINING
		// command line parameters, divided into words,
		// and added as String objects to a vector.
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		// now see if it worked
		boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			// it worked, so build a copy of this ability,
			// and add it to the affects list of the
			// affected MOB.  Then tell everyone else
			// what happened.
			CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":"^S<S-NAME> cast(s) a spell on <T-NAMESELF>.^?");
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
                target.tell("You fade from view");
				beneficialAffect(mob,target,asLevel,mob.envStats().level()*3);
			}
		}
		else
			return beneficialWordsFizzle(mob,target,"<S-NAME> speak(s) softly to <T-NAMESELF>, but nothing more happens.");

		// return whether it worked
		return success;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Fireloop Documentation | Designed for Modern Real-Time Applications by MEAN Expert.</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="theme-color" content="#C13A00">

    <meta name="keywords" content="undefined">
    <meta name="description" content="FireLoop beautifully integrates some of the most amazing frameworks out there; like the IBM's StrongLoop LoopBack, Google's Angular 2, Telerik's NativeScript, Ionic 2 Frameworks and much more.">
<meta property="og:type" content="website">
<meta property="og:title" content="Fireloop Documentation">
<meta property="og:url" content="http://fireloop.io/index.html">
<meta property="og:site_name" content="Fireloop Documentation">
<meta property="og:description" content="FireLoop beautifully integrates some of the most amazing frameworks out there; like the IBM's StrongLoop LoopBack, Google's Angular 2, Telerik's NativeScript, Ionic 2 Frameworks and much more.">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Fireloop Documentation">
<meta name="twitter:description" content="FireLoop beautifully integrates some of the most amazing frameworks out there; like the IBM's StrongLoop LoopBack, Google's Angular 2, Telerik's NativeScript, Ionic 2 Frameworks and much more.">

        <link rel="alternative" href="/atom.xml" title="Fireloop Documentation" type="application/atom+xml">

    <link rel="shortcut icon" href="/img/favicon.png">
    <link rel="stylesheet" href="/css/style.css?v=1.4.2">

                Getting Started

                Api

                Comparison Table

                Creating Client Applications

                Creating Client SDK

                Creating FireLoop Models

                Handle DC

                Real Time Stats Example

                Scaling Fireloop

                Serving Applications

                Github

Fireloop Documentation

            <input type="text" id="key" class="search-input" autocomplete="off" placeholder=" Search......">

         Choose a Language

        <select id="header-lang-select" class="header-lang-select" onchange="location = this.options[this.selectedIndex].value">

          <option disabled selected value class="hidden">Choose a Language</option>

            <option value="/en" data-href="/en">English</option>

            <option value="/es" data-href="/es">Spanish</option>

        </select>

Docs

                Designed for Modern Real-Time Applications by MEAN Expert.

        <time class="post-time" title="2017-5-4 17:41" datetime="2017-05-04T21:41:26.411Z"  itemprop="datePublished">2017-05-04</time>

      Manejar Desconecciones

                FireLoop.io

Manejar DesconeccionesA veces, cuando se desconecta un usuario del servidor, es...

            hello world

        <time class="post-time" title="2017-5-4 17:41" datetime="2017-05-04T21:41:11.580Z"  itemprop="datePublished">2017-05-04</time>

      Handle Disconnections

                FireLoop.io

Handle DisconnectionsSometimes when a user is disconnected from the server, som...

            hello world

        <time class="post-time" title="2017-5-4 17:13" datetime="2017-05-04T21:13:32.975Z"  itemprop="datePublished">2017-05-04</time>

      Creación de modelos FireLoop

        Cuando empiece a construir un sistema, lo primero que debe hacer justo después de su instalación, es comenzar a crear sus Modelos de API.
Estos modelos son similares a LoopBack Modelos, pero con un...

            hello world

        <time class="post-time" title="2017-5-4 17:13" datetime="2017-05-04T21:13:32.975Z"  itemprop="datePublished">2017-05-04</time>

      Sirviendo Aplicaciones

                FireLoop.io

FireLoop es capaz de ejecutar todas las aplicaciones de su proyecto a la vez (i...

            hello world

        <time class="post-time" title="2017-5-4 17:13" datetime="2017-05-04T21:13:32.975Z"  itemprop="datePublished">2017-05-04</time>

      Escalando FireLoop

                FireLoop.io

Escalando FireLoopConstruir aplicaciones con FireLoop es agradable y fácil, per...

            hello world

        <time class="post-time" title="2017-5-4 17:13" datetime="2017-05-04T21:13:32.975Z"  itemprop="datePublished">2017-05-04</time>

      Ejemplo de Estatisticas RealTime

                Real-Time

Descripción del ProyectoPara demostrar lo que se puede lograr con FireLoop, he de...

            hello world

        <time class="post-time" title="2017-5-4 17:13" datetime="2017-05-04T21:13:32.975Z"  itemprop="datePublished">2017-05-04</time>

      Creando el SDK para el Cliente

        La integración FireLoop se construye en el SDK, por lo que sólo necesita generar uno e instalarlo mediante la herramienta CLI.
1234567891011121314151617181920$ cd myproject$ fireloop     _-----_   ...

            hello world

        <time class="post-time" title="2017-5-4 17:13" datetime="2017-05-04T21:13:32.975Z"  itemprop="datePublished">2017-05-04</time>

      Hola Mundo

        Bienvenido a [Hexo] (https://hexo.io/)! Este es tu primer post. Consulte [documentación] (https://hexo.io/docs/) para obtener más información. Si tienes algún problema al usar Hexo, puedes encontra...

            hello world

        <time class="post-time" title="2017-5-4 17:13" datetime="2017-05-04T21:13:32.975Z"  itemprop="datePublished">2017-05-04</time>

      Inicio Rapido

        FireLoop Es una Plataforma en Real-time para NodeJS que le permite crear aplicaciones modernas y complejas integrando a la perfección las sorprendentes tecnologias de MEAN Stack como frameworks IBM...

            hello world

        <time class="post-time" title="2017-5-4 17:13" datetime="2017-05-04T21:13:32.975Z"  itemprop="datePublished">2017-05-04</time>

      Api

Debería [crear una aplicación] y software development kit utilizando la Herramienta de CLI FireLoop antes de poder utilizar la siguiente API.

Importación de servicio RealTimeEl LoopBack SDK Build...

            hello world

    123Next

        Total number of visitors :

        Site total views :

            Power by Hexo Theme indigo
            Fireloop Documentation © 2016 - 2017

<template id="search-tpl">

{title}

                {tags}

            <time class="flex-col time">{date}</time>

</template>


text:
LFS Test Server
======

[rel]: https://github.com/github/lfs-test-server/releases
[lfs]: https://github.com/github/git-lfs
[api]: https://github.com/github/git-lfs/blob/master/docs/api.md

LFS Test Server is an example server that implements the [Git LFS API][api]. It
is intended to be used for testing the [Git LFS][lfs] client and is not in a
production ready state.

LFS Test Server is written in Go, with pre-compiled binaries available for Mac,
Windows, Linux, and FreeBSD.

See [CONTRIBUTING.md](CONTRIBUTING.md) for info on working on LFS Test Server and
sending patches.

## Installing

Download the [latest version][rel]. It is a single binary file.

Alternatively, use the Go installer:

```
  $ go install github.com/github/lfs-test-server
```

## Building

To build from source, use the Go tools:

```
  $ go get github.com/github/lfs-test-server
```

## Running

Running the binary will start an LFS server on `localhost:8080` by default.
There are few things that can be configured via environment variables:

	LFS_LISTEN      # The address:port the server listens on, default: "tcp://:8080"
	LFS_HOST        # The host used when the server generates URLs, default: "localhost:8080"
	LFS_METADB      # The database file the server uses to store meta information, default: "lfs.db"
	LFS_CONTENTPATH # The path where LFS files are store, default: "lfs-content"
	LFS_ADMINUSER   # An administrator username, default: unset
	LFS_ADMINPASS   # An administrator password, default: unset
	LFS_CERT        # Certificate file for tls
	LFS_KEY         # tls key
	LFS_SCHEME      # set to 'https' to override default http

If the `LFS_ADMINUSER` and `LFS_ADMINPASS` variables are set, a
rudimentary admin interface can be accessed via
`http://$LFS_HOST/mgmt`. Here you can add and remove users.

To use the LFS test server with the Git LFS client, configure it in the repository's `.gitconfig` file:

```
  [lfs]
    url = "http://localhost:8080/janedoe/lfsrepo"

```

HTTPS:

NOTE: If using https with a self signed cert also disable cert checking in the client repo.

```
	[lfs]
		url = "https://localhost:8080/jimdoe/lfsrepo"

	[http]
		sslfverify = false

```

An example usage:

Generate a key pair
```
openssl req -x509 -sha256 -nodes -days 2100 -newkey rsa:2048 -keyout mine.key -out mine.crt
```

Make yourself a run script

```
#!/bin/bash

set -eu
set -o pipefail

LFS_LISTEN="tcp://:9999"
LFS_HOST="127.0.0.1:9999"
LFS_CONTENTPATH="content"
LFS_ADMINUSER="<cool admin user name>"
LFS_ADMINPASS="<better admin password>"
LFS_CERT="mine.crt"
LFS_KEY="mine.key"
LFS_SCHEME="https"

export LFS_LISTEN LFS_HOST LFS_CONTENTPATH LFS_ADMINUSER LFS_ADMINPASS LFS_CERT LFS_KEY LFS_SCHEME

./lfs-test-server

```

Build the server

```
go build

```

Run

```
bash run.sh

```

Check the managment page

browser: https://localhost:9999/mgmt


text:
package pl.genealodzy;

import javax.swing.SwingUtilities;

import pl.genealodzy.gui.MainFrame;

public class IndexValidatorMain {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new MainFrame());
    }

}


text:
require File.dirname(__FILE__) + '/spec_helper'

describe 'resirrc config files' do
  it 'should support the same new syntax changes and improvements that siterc files do'
end

describe 'siterc config files' do

  it 'helpers should have access to request and response objects' do
    site = Resir::Site.new 'examples/siterc_testing/first'
    req  = Rack::MockRequest.new site

    req.get('/request_response').body.should == 'request_response test: req: Rack::Request request.env: Hash resp: Rack::Response'
  end

  it 'should be able to load helpers by passing the name of the helper(s)' do
    site = Resir::Site.new 'examples/siterc_testing/first'
    req  = Rack::MockRequest.new site

    req.get('/example_test').body.should == 'testing example: i am an example helper!'
    req.get('/sample_test').body.should == %{testing sample: hello from sample helper ... you passed me [:hi, \"there\", 5]}
  end

  it 'should be able to load filters by passing the name of the filter(s)' do
    site = Resir::Site.new 'examples/siterc_testing/first'
    req  = Rack::MockRequest.new site

    req.get('/some_path').body.should == 'i am the sample filter!'
    req.get('/another_page').body.should == 'i am sample_two, required when you require sample!  NEATO!!!'
    req.get('/yet_another').body.should == "i'm from more filters ... filter!"
    req.get('/yet_another.more_filters_filter').body.should == "i'm from more filters ... filter!"
  end

  it "it can add filters into site.loaded_filters using a pretty load_filter { erb {} } style syntax" do
    Resir.loaded_filters.keys.should_not include('misc')

    site = Resir::Site.new 'examples/siterc_testing/first'
    req  = Rack::MockRequest.new site

    site.loaded_filters.keys.should include('misc')
    Resir.loaded_filters.keys.should_not include('misc')

    req.get('/blah').body.should == 'i am the misc filter'
    req.get('/blah.misc').body.should == 'i am the misc filter'
  end

  it "it can manually add filters into site.loaded_filters" do
    Resir.loaded_filters.keys.should_not include('manual')

    site = Resir::Site.new 'examples/siterc_testing/first'
    req  = Rack::MockRequest.new site

    site.loaded_filters.keys.should include('manual')
    Resir.loaded_filters.keys.should_not include('manual')

    req.get('/page').body.should == 'manually set this filter in .siterc'
  end

  it "should have access to site (as 'site' or 'self')" do
    site = Resir::Site.new 'examples/siterc_testing/first'

    site.hello.should == 'hello from a new variable added by siterc'
    site.new_site_method.should == 'hello from new site method!'
    site.added_to_site.should == 'added this to var of name site'
  end

  it "can add helper methods by class_eval'ing onto [self.]responder" do
    site = Resir::Site.new 'examples/siterc_testing/first'
    req  = Rack::MockRequest.new site
    req.get('/').body.should == 'calling blah: BLAH'
  end

end


text:
<?php

namespace User;

use Zend\Mvc\MvcEvent;
use Zend\Authentication\AuthenticationService,
    Zend\Authentication\Storage\Session as SessionStorage;
use User\Auth\Adapter as AuthAdapter;
use Zend\ModuleManager\ModuleManager;

class Module {

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

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

    public function getServiceConfig() {
        return array(
            'factories' => array(
                'User\Service\User' => function($sm) {
                    return new Service\User($sm->get('Doctrine\ORM\EntityManager'));
                },
                'User\Auth\Adapter' => function($sm) {
                    return new AuthAdapter($sm->get('Doctrine\ORM\EntityManager'));
                }
            )
        );
    }

    public function init(ModuleManager $moduleManager) {
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();

        $sharedEvents->attach("Zend\Mvc\Controller\AbstractActionController", MvcEvent::EVENT_DISPATCH, array($this, 'validaAuth'), 100);
    }

    public function validaAuth($e) {
        $auth = new AuthenticationService;
        $auth->setStorage(new SessionStorage());

        $controller = $e->getTarget();
        $matchedRoute = $controller->getEvent()->getRouteMatch()->getMatchedRouteName();

        if (!$auth->hasIdentity() and ( $matchedRoute == "user" OR $matchedRoute == "user/paginator"))
            return $controller->redirect()->toRoute("login");
    }

    public function getViewHelperConfig() {
        return array(
            'invokables' => array(
                'UserIdentity' => new View\Helper\UserIdentity()
            )
        );
    }

}


text:
layout: post
title:  "An introduction to minimalism"
date:   2017-03-02 21:17:10 +0530
categories: [minimalism]
author: "Felix Mueller"
---
stuff.


text:
"""
pandas.CategoricalDtype
"""

import pandas as pd

from numba.extending import typeof_impl
from numba.np import numpy_support
from numba import typeof

from . import pandas_support
from .types import Categorical

@typeof_impl.register(pd.CategoricalDtype)
def _typeof_CategoricalDtype(val, c):
    return pandas_support.from_dtype(val)

@typeof_impl.register(pd.Categorical)
def _typeof_Categorical(val, c):
    try:
        dtype = pandas_support.from_dtype(val.dtype)
    except NotImplementedError:
        raise ValueError("Unsupported Categorical dtype: %s" % (val.dtype,))
    codes = typeof(val.codes)
    return Categorical(dtype=dtype, codes=codes)


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Appacitive.Sdk.Services
{
    public class GraphProjectResponse : ApiResponse
    {
        public List<GraphNode> Nodes { get; set; }
    }
}


text:
SDLStreamingEncryptionFlag Enumeration Reference

Section Contents

SDLStreamingEncryptionFlagNone

SDLStreamingEncryptionFlagAuthenticateOnly

SDLStreamingEncryptionFlagAuthenticateAndEncrypt

Overview

A flag determining how video and audio streaming should be encrypted

      SDLStreamingEncryptionFlagNone

It should not be encrypted at all

Objective-C

SDLStreamingEncryptionFlagNone

Swift

case none = 0

      SDLStreamingEncryptionFlagAuthenticateOnly

It should use SSL/TLS only to authenticate

Objective-C

SDLStreamingEncryptionFlagAuthenticateOnly

Swift

case authenticateOnly = 1

      SDLStreamingEncryptionFlagAuthenticateAndEncrypt

All data on these services should be encrypted using SSL/TLS

Objective-C

SDLStreamingEncryptionFlagAuthenticateAndEncrypt

Swift

case authenticateAndEncrypt = 2


text:
const
  api = require('/Users/shaunhoyes/poloniex-api.js'),
  currency = 'STR';

api.Poloniex.STRICT_SSL = false;

api.poloniex.returnLoanOrders(currency, function(err, data) {
  const longRate = data.offers[10].rate * 100;
  const rate = (longRate).toFixed(4) + "%";
  module.exports.rate = rate;
});

module.exports.currency = currency;


text:
package net.myacxy.jgsq.models;

import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import net.myacxy.jgsq.helpers.ServerResponseStatus;
import net.myacxy.jgsq.protocols.BaseProtocol;

import java.util.ArrayList;
import java.util.TreeMap;

public class GameServer
{
    protected transient BaseProtocol protocol;

    @SerializedName("current_clients")
    public int currentClients;
    @SerializedName("game")
    public Game game;
    @SerializedName("ip_address")
    public String ipAddress;
    @SerializedName("online")
    public boolean isOnline;
    @SerializedName("password_protected")
    public boolean isPasswordProtected;
    @SerializedName("map_name")
    public String mapName;
    @SerializedName("max_clients")
    public int maxClients;
    @SerializedName("host_name")
    public String hostName;
    @SerializedName("colored_host_name")
    public String coloredHostName;
    @SerializedName("players")
    public ArrayList<Player> players;
    @SerializedName("port")
    public int port;
    @SerializedName("parameters")
    public TreeMap<String, String> parameters;
    @SerializedName("rcon")
    public String rcon;
    @SerializedName("query_port")
    public String queryPort;
    @SerializedName("ping")
    public int ping;

    public GameServer(Game game, String ipAddress, int port, BaseProtocol protocol)
    {
        this.game = game;
        this.ipAddress = ipAddress;
        this.port = port;
        this.protocol = protocol;

        players = new ArrayList<>();
        parameters = new TreeMap<>();
    }

    public GameServer(Game game, BaseProtocol protocol)
    {
        this.game = game;
        this.protocol = protocol;

        players = new ArrayList<>();
        parameters = new TreeMap<>();
    }

    public ServerResponseStatus connect()
    {
        return connect(ipAddress, port);
    }

    public ServerResponseStatus connect(String ipAddress, int port)
    {
        this.ipAddress = ipAddress;
        this.port = port;

        if(protocol.connect(ipAddress, port) == ServerResponseStatus.CONNECTED)
        {
            this.ipAddress = protocol.ipAddress.getHostAddress();
        }

        return protocol.getResponseStatus();
    }

    public void disconnect()
    {
        isOnline = false;
        protocol.disconnect();
    }

    public ServerResponseStatus update()
    {
        if(protocol.getResponseStatus() == ServerResponseStatus.CONNECTED)
        {
            if(protocol.query("getstatus") == ServerResponseStatus.OK)
            {
                protocol.updateServerInfo(this);
            }
        }
        return protocol.getResponseStatus();
    }

    public BaseProtocol getProtocol()
    {
        return protocol;
    }

    @Override
    public String toString()
    {
        return String.format("(%s:%s, %s, %s)", ipAddress, String.valueOf(port), hostName, game);
    }

    public String toJson()
    {
        return new GsonBuilder().setPrettyPrinting()
                .create()
                .toJson(this);
    }
} // GameServer


text:
"""The parser converts the template language into a usable structured
form.

There are two layers to the parsing: breaking the template down into
blocks (which is done by the :py:mod:`~margate.block_parser` module),
and parsing the expressions that appear in the execution blocks within
the template.

The parser in this module uses a combination of ad hoc parsing,
`funcparserlib <https://pypi.python.org/pypi/funcparserlib>`_ and
`ast.parse
<https://docs.python.org/3/library/ast.html#ast.parse>`_. The
top-level rules in the language (``if``, ``for``, ``endif`` etc.) are
handled ad hoc since they are not recursive. However, the expression
that is given as an argument to ``if`` is an arbitrary expression and
parsed

"""

import re
import ast
from collections import namedtuple
import funcparserlib.parser

from . import code_generation, compiler

IfNode = namedtuple('IfNode', ['expression'])
ForNode = namedtuple('ForNode', ['variable', 'collection'])
ExtendsNode = namedtuple('ExtendsNode', ['template_name'])
BlockNode = namedtuple('BlockNode', ['block_name'])

class UnsupportedElementException(Exception):
    pass

def parse_expression(expression):
    """Parse an expression that appears in an execution node, i.e. a
    block delimited by ``{% %}``.

    This can be a compound expression like a ``for`` statement with
    several sub-expressions, or it can just be a single statement such
    as ``endif``.

    :param list expression: Tokenised expression.

    """
    from funcparserlib.parser import a, skip, some

    # For if expressions, we rely on the Python parser to process the
    # expression rather than using our own parser.
    if expression[0] == 'if':
        return IfNode(ast.parse(' '.join(expression[1:]), mode="eval"))

    variable_name = some(lambda x: re.match(r'[a-zA-Z_]+', x))

    # TODO We use the same function twice, first to match the token
    # and then to extract the value we care about from the token
    # (namely the contents of the quoted string). This smells wrong.
    def extract_quoted_string(x):
        result = re.match(r'\"([^\"]*)\"', x)
        if result:
            return result.groups(1)

    quoted_string = some(extract_quoted_string)

    for_expression = (
        skip(a('for'))
        + (variable_name >> str)
        + skip(a('in'))
        + (variable_name >> str))

    extends_expression = (
        skip(a('extends'))
        + (quoted_string >> extract_quoted_string))

    block_expression = (
        skip(a('block'))
        + (variable_name >> str))

    def make_for_node(x): return ForNode(*x)

    def make_extends_node(x): return ExtendsNode(*x)

    parser = ((for_expression >> make_for_node)
              | (extends_expression >> make_extends_node)
              | (block_expression >> BlockNode))

    try:
        return parser.parse(expression)
    except funcparserlib.parser.NoParseError as e:
        raise Exception("Invalid expression '%s'" % expression)

class Parser:
    """The Parser is responsible for turning a template in "tokenised"
    form into a tree structure from which it is straightforward to
    generate bytecode.

    The input is in the form of a flat list of atomic elements of the
    template, where literal text (of any length) is a single element,
    and a ``{% %}`` or ``{{ }}`` expression is a single element.

    Figuring out nesting of starting and ending of loops happens
    within the parser.

    """

    def __init__(self, template_locator=None):

        def _get_related_template(template_name):
            template = template_locator.find_template(template_name)
            if not template:
                raise FileNotFoundError()
            with open(template) as template_file:
                compiler_obj = compiler.Compiler(template_locator)
                return compiler_obj._get_chunks(template_file.read())

        self._sub_template_locator = _get_related_template

    def parse(self, tokens):
        """Parse a token sequence into a
        :py:class:`~margate.code_generation.Sequence` object.

        """

        sequence = code_generation.Sequence()

        self._parse_into_sequence(sequence, tokens)

        return sequence

    def _parse_into_sequence(self, sequence, tokens,
                             termination_condition=None):
        token_iter = iter(tokens)

        try:
            while True:
                token = next(token_iter)
                if termination_condition and termination_condition(token):
                    return

                if isinstance(token, code_generation.Execution):
                    # An execution node always starts a subsequence
                    # (i.e. a node in the tree with its own
                    # children). Since we've ruled out the case where
                    # this is the termination of an existing block,
                    # any Execution node is the start of a new block.
                    block = self._parse_subsequence(token, token_iter)
                    sequence.add_element(block)
                else:
                    sequence.add_element(token)
        except StopIteration:
            return

    def _parse_subsequence(self, token, token_iter):
        node = parse_expression(
            re.split(r'\s+',
                     token.expression.strip()))

        if isinstance(node, IfNode):
            block = code_generation.IfBlock(node.expression)
            inner_termination_condition = self._end_sequence("endif")
        elif isinstance(node, ForNode):
            block = code_generation.ForBlock(node)
            inner_termination_condition = self._end_sequence("endfor")
        elif isinstance(node, ExtendsNode):
            if self._sub_template_locator is None:
                raise UnsupportedElementException(
                    "Parser is not configured to support "
                    "extending other templates")

            content = self._sub_template_locator(
                node.template_name)
            parsed = self.parse(content)
            block = code_generation.ExtendsBlock(parsed)
            inner_termination_condition = None
        elif isinstance(node, BlockNode):
            block = code_generation.ReplaceableBlock(
                node.block_name)
            inner_termination_condition = self._end_sequence("endblock")
        else:
            raise Exception("Unrecognised block type")

        self._parse_into_sequence(block.sequence,
                                  token_iter,
                                  inner_termination_condition)

        return block

    def _end_sequence(self, end_token):
        def is_end_token(token):
            return (isinstance(token, code_generation.Execution)
                    and token.expression == end_token)

        return is_end_token


text:
package com.jess.arms.di.module;

import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.jess.arms.common.utils.FileUtil;
import com.jess.arms.http.IGlobalHttpHandler;
import com.jess.arms.http.RequestInterceptor;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Named;
import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import io.rx_cache2.internal.RxCache;
import io.victoralbertos.jolyglot.GsonSpeaker;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by jessyan on 2016/3/14.
 */
@Module
public class ClientModule {
    private static final int TIME_OUT = 10;

    /**
     * @param builder
     * @param client
     * @param httpUrl
     * @return
     * @author: jess
     * @date 8/30/16 1:15 PM
     * @description:提供retrofit
     */
    @Singleton
    @Provides
    Retrofit provideRetrofit(Application application, @Nullable RetrofitConfiguration configuration, Retrofit.Builder builder, OkHttpClient client, HttpUrl httpUrl) {
        builder.baseUrl(httpUrl)//域名
                .client(client)//设置okhttp
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//使用rxjava
                .addConverterFactory(GsonConverterFactory.create());//使用Gson
        if (configuration != null)
            configuration.configRetrofit(application, builder);
        return builder.build();
    }

    /**
     * 提供OkhttpClient
     *
     * @param builder
     * @return
     */
    @Singleton
    @Provides
    OkHttpClient provideClient(Application application, @Nullable OkhttpConfiguration configuration, OkHttpClient.Builder builder, Interceptor intercept
            , @Nullable List<Interceptor> interceptors, @Nullable final IGlobalHttpHandler handler) {
        builder
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .addNetworkInterceptor(intercept);

        if (handler != null)
            builder.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(@NonNull Chain chain) throws IOException {
                    return  chain.proceed(handler.onHttpRequestBefore(chain, chain.request()));
                }
            });

        if (interceptors != null) {//如果外部提供了interceptor的集合则遍历添加
            for (Interceptor interceptor : interceptors) {
                builder.addInterceptor(interceptor);
            }
        }

        if (configuration != null)
            configuration.configOkhttp(application, builder);
        return builder.build();
    }

    @Singleton
    @Provides
    Retrofit.Builder provideRetrofitBuilder() {
        return new Retrofit.Builder();
    }

    @Singleton
    @Provides
    OkHttpClient.Builder provideClientBuilder() {
        return new OkHttpClient.Builder();
    }

    @Singleton
    @Provides
    Interceptor provideInterceptor(RequestInterceptor intercept) {
        return intercept;//打印请求信息的拦截器
    }

    /**
     * 提供RXCache客户端
     *
     * @param cacheDirectory RxCache缓存路径
     * @return
     */
    @Singleton
    @Provides
    RxCache provideRxCache(Application application,@Nullable  RxCacheConfiguration configuration, @Named("RxCacheDirectory") File cacheDirectory) {
        RxCache.Builder builder = new RxCache.Builder();
        if (configuration != null)
            configuration.configRxCache(application, builder);
        return builder.persistence(cacheDirectory, new GsonSpeaker());
    }

    /**
     * 需要单独给RxCache提供缓存路径
     * 提供RxCache缓存地址
     */
    @Singleton
    @Provides
    @Named("RxCacheDirectory")
    File provideRxCacheDirectory(File cacheDir) {
        File cacheDirectory = new File(cacheDir, "RxCache");
        FileUtil.createDirs(cacheDirectory);
        return cacheDirectory;
    }

    public interface RetrofitConfiguration {
        void configRetrofit(Context context, Retrofit.Builder builder);
    }

    public interface OkhttpConfiguration {
        void configOkhttp(Context context, OkHttpClient.Builder builder);
    }

    public interface RxCacheConfiguration {
        void configRxCache(Context context, RxCache.Builder builder);
    }

}


text:
This is a boilerplate for your next big Konstruct website / app / rocket! We made it simpler for you to deal with all of the depencies and structuring, so you don't have to worry about it!

## Get Started

Run ./install.sh in your terminal from the _system folder.

Then run gulp to get coding.

## Authors

* Adrian Kirsten - [@traaidmark](https://twitter.com/traaidmark) - [www.traaidmark.com](http://www.traaidmark.com)

## Licensing

**Copyright 2014 Adrian Kirsten**

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

[http://apache.org/licenses/LICENSE-2.0](http://apache.org/licenses/LICENSE-2.0)

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


text:
Template['courses'].helpers({
});

Template['courses'].events({
});


text:
<?php

namespace api\modules\v1\models;
use Yii;

/**
 * This is the model class for table "ee_marketplaces_product_categories".
 *
 * @property integer $id
 * @property integer $c_id
 * @property integer $marketplace_id
 * @property integer $product_id
 */
class EeMarketplacesProductCategories extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'ee_marketplaces_product_categories';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['c_id', 'marketplace_id', 'product_id'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'c_id' => 'C ID',
            'marketplace_id' => 'Marketplace ID',
            'product_id' => 'Product ID',
        ];
    }
}


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(AppGamer.Startup))]
namespace AppGamer
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
"""AFF4 Objects to enforce ACL policies."""

import email
import re
import urllib

from grr.lib import access_control
from grr.lib import aff4
from grr.lib import config_lib
from grr.lib import email_alerts
from grr.lib import events
from grr.lib import flow
from grr.lib import rdfvalue
from grr.lib import utils

from grr.lib.aff4_objects import aff4_grr
from grr.lib.aff4_objects import users as aff4_users

from grr.lib.authorization import client_approval_auth

from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfvalues import structs as rdf_structs

from grr.proto import flows_pb2

class Error(Exception):
  """Base exception class."""

class ErrorClientDoesNotExist(Error):
  """Raised when trying to check approvals on non-existent client."""

class Approval(aff4.AFF4Object):
  """An abstract approval request object.

  This object normally lives within the namespace:
  aff4:/ACL/...

  The aff4:/ACL namespace is not writable by users, hence all manipulation of
  this object must be done via dedicated flows. These flows use the server's
  access credentials for manipulating this object.
  """

  class SchemaCls(aff4.AFF4Object.SchemaCls):
    """The Schema for the Approval class."""
    REQUESTOR = aff4.Attribute("aff4:approval/requestor", rdfvalue.RDFString,
                               "Requestor of the approval.")

    APPROVER = aff4.Attribute("aff4:approval/approver", rdfvalue.RDFString,
                              "An approver for the request.", "approver")

    SUBJECT = aff4.Attribute("aff4:approval/subject", rdfvalue.RDFURN,
                             "Subject of the approval. I.e. the resource that "
                             "requires approved access.")

    REASON = aff4.Attribute("aff4:approval/reason",
                            rdfvalue.RDFString,
                            "The reason for requesting access to this client.")

    EMAIL_MSG_ID = aff4.Attribute("aff4:approval/email_msg_id",
                                  rdfvalue.RDFString,
                                  "The email thread message ID for this"
                                  "approval. Storing this allows for "
                                  "conversation threading.")

    EMAIL_CC = aff4.Attribute("aff4:approval/email_cc", rdfvalue.RDFString,
                              "Comma separated list of email addresses to "
                              "CC on approval emails.")

    NOTIFIED_USERS = aff4.Attribute("aff4:approval/notified_users",
                                    rdfvalue.RDFString,
                                    "Comma-separated list of GRR users "
                                    "notified about this approval.")

  def CheckAccess(self, token):
    """Check that this approval applies to the given token.

    Args:
      token: User's credentials token.
    Returns:
      True if access is granted, raises access_control.UnauthorizedAccess
      otherwise.
    Raises:
      access_control.UnauthorizedAccess: if access is rejected.
    """
    _ = token
    raise NotImplementedError()

  @staticmethod
  def GetApprovalForObject(object_urn, token=None, username=""):
    """Looks for approvals for an object and returns available valid tokens.

    Args:
      object_urn: Urn of the object we want access to.

      token: The token to use to lookup the ACLs.

      username: The user to get the approval for, if "" we get it from the
        token.

    Returns:
      A token for access to the object on success, otherwise raises.

    Raises:
      UnauthorizedAccess: If there are no valid approvals available.

    """
    if token is None:
      raise access_control.UnauthorizedAccess(
          "No token given, cannot authenticate.")

    if not username:
      username = token.username

    approvals_root_urn = aff4.ROOT_URN.Add("ACL").Add(object_urn.Path()).Add(
        username)

    children_urns = list(
        aff4.FACTORY.ListChildren(
            approvals_root_urn, token=token))
    if not children_urns:
      raise access_control.UnauthorizedAccess(
          "No approval found for user %s" % utils.SmartStr(username),
          subject=object_urn)

    last_error = None
    approvals = aff4.FACTORY.MultiOpen(
        children_urns,
        mode="r",
        aff4_type=Approval,
        age=aff4.ALL_TIMES,
        token=token)
    for approval in approvals:
      try:
        test_token = access_control.ACLToken(
            username=username, reason=approval.Get(approval.Schema.REASON))
        approval.CheckAccess(test_token)

        return test_token
      except access_control.UnauthorizedAccess as e:
        last_error = e

    if last_error:
      # We tried all possible approvals, but got no usable results.
      raise access_control.UnauthorizedAccess(last_error, subject=object_urn)
    else:
      # If last error is None, means that none of the URNs in children_urns
      # could be opened. This shouldn't really happen ever, but we have
      # to make sure to provide a meaningful error message.
      raise access_control.UnauthorizedAccess(
          "Couldn't open any of %d approvals "
          "for user %s" % (len(children_urns), utils.SmartStr(username)),
          subject=object_urn)

class ApprovalWithApproversAndReason(Approval):
  """Generic all-purpose base approval class.

  This object normally lives within the aff4:/ACL namespace. Username is
  encoded into this object's urn. Subject's urn (i.e. urn of the object
  which this approval corresponds for) can also be inferred from this approval's
  urn.
  This class provides following functionality:
  * Number of approvers configured by ACL.approvers_required configuration
    parameter is required for this approval's CheckAccess() to succeed.
  * Optional checked_approvers_label attribute may be specified. Then
    at least min_approvers_with_label number of approvers will have to
    have checked_approvers_label label in order for CheckAccess to
    succeed.
  * Break-glass functionality. If this approval's BREAK_GLASS attribute is
    set, user's token is marked as emergency token and CheckAccess() returns
    True.

  The aff4:/ACL namespace is not writable by users, hence all manipulation of
  this object must be done via dedicated flows.
  """

  checked_approvers_label = None
  min_approvers_with_label = 1

  class SchemaCls(Approval.SchemaCls):
    """The Schema for the ClientAccessApproval class."""

    LIFETIME = aff4.Attribute(
        "aff4:approval/lifetime",
        rdfvalue.RDFInteger,
        "The number of seconds an approval is valid for.",
        default=0)
    BREAK_GLASS = aff4.Attribute(
        "aff4:approval/breakglass", rdfvalue.RDFDatetime,
        "The date when this break glass approval will expire.")

  def InferUserAndSubjectFromUrn(self):
    """Infers user name and subject urn from self.urn.

    Returns:
      (username, subject_urn) tuple.
    """
    raise NotImplementedError()

  def GetApprovers(self, now):
    lifetime = rdfvalue.Duration(
        self.Get(self.Schema.LIFETIME) or config_lib.CONFIG["ACL.token_expiry"])

    # Check that there are enough approvers.
    approvers = set()
    for approver in self.GetValuesForAttribute(self.Schema.APPROVER):
      if approver.age + lifetime > now:
        approvers.add(utils.SmartStr(approver))
    return approvers

  def CheckAccess(self, token):
    """Enforce a dual approver policy for access."""
    namespace, _ = self.urn.Split(2)

    if namespace != "ACL":
      raise access_control.UnauthorizedAccess(
          "Approval object has invalid urn %s." % self.urn,
          subject=self.urn,
          requested_access=token.requested_access)

    user, subject_urn = self.InferUserAndSubjectFromUrn()
    if user != token.username:
      raise access_control.UnauthorizedAccess(
          "Approval object is not for user %s." % token.username,
          subject=self.urn,
          requested_access=token.requested_access)

    now = rdfvalue.RDFDatetime.Now()

    # Is this an emergency access?
    break_glass = self.Get(self.Schema.BREAK_GLASS)
    if break_glass and now < break_glass:
      # This tags the token as an emergency token.
      token.is_emergency = True
      return True

    # Check that there are enough approvers.
    approvers = self.GetNonExpiredApprovers()
    if len(approvers) < config_lib.CONFIG["ACL.approvers_required"]:
      msg = ("Requires %s approvers for access." %
             config_lib.CONFIG["ACL.approvers_required"])
      raise access_control.UnauthorizedAccess(
          msg, subject=subject_urn, requested_access=token.requested_access)

    # Check User labels
    if self.checked_approvers_label:
      approvers_with_label = []

      # We need to check labels with high privilege since normal users can
      # inspect other user's labels.
      for approver in approvers:
        try:
          user = aff4.FACTORY.Open(
              "aff4:/users/%s" % approver,
              aff4_type=aff4_users.GRRUser,
              token=token.SetUID())
          if self.checked_approvers_label in user.GetLabelsNames():
            approvers_with_label.append(approver)
        except IOError:
          pass

      if len(approvers_with_label) < self.min_approvers_with_label:
        raise access_control.UnauthorizedAccess(
            "At least %d approver(s) should have '%s' label." %
            (self.min_approvers_with_label, self.checked_approvers_label),
            subject=subject_urn,
            requested_access=token.requested_access)

    return True

  def GetNonExpiredApprovers(self):
    """Returns a list of usernames of approvers who approved this approval."""

    lifetime = rdfvalue.Duration(
        self.Get(self.Schema.LIFETIME) or config_lib.CONFIG["ACL.token_expiry"])

    # Check that there are enough approvers.
    #
    # TODO(user): approvals have to be opened with
    # age=aff4.ALL_TIMES because versioning is used to store lists
    # of approvers. This doesn't seem right and has to be fixed.
    approvers = set()
    now = rdfvalue.RDFDatetime.Now()
    for approver in self.GetValuesForAttribute(self.Schema.APPROVER):
      if approver.age + lifetime > now:
        approvers.add(utils.SmartStr(approver))

    return list(approvers)

class ClientApproval(ApprovalWithApproversAndReason):
  """An approval request for access to a specific client.

  This object normally lives within the namespace:
  aff4:/ACL/client_id/user/approval:<id>

  Hence the client_id and user which is granted access are inferred from this
  object's URN.

  The aff4:/ACL namespace is not writable by users, hence all manipulation of
  this object must be done via dedicated flows. These flows use the server's
  access credentials for manipulating this object:

   - RequestClientApprovalFlow()
   - GrantClientApprovalFlow()
   - BreakGlassGrantClientApprovalFlow()
  """

  def InferUserAndSubjectFromUrn(self):
    """Infers user name and subject urn from self.urn."""
    _, client_id, user, _ = self.urn.Split(4)
    return (user, rdf_client.ClientURN(client_id))

  def CheckAccess(self, token):
    super(ClientApproval, self).CheckAccess(token)
    # If approvers isn't set and super-class checking passed, we're done.
    if not client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.IsActive():
      return True

    now = rdfvalue.RDFDatetime.Now()
    approvers = self.GetApprovers(now)
    requester, client_urn = self.InferUserAndSubjectFromUrn()
    # Open the client object with superuser privs so we can get the list of
    # labels
    try:
      client_object = aff4.FACTORY.Open(
          client_urn,
          mode="r",
          aff4_type=aff4_grr.VFSGRRClient,
          token=token.SetUID())
    except aff4.InstantiationError:
      raise ErrorClientDoesNotExist("Can't check label approvals on client %s "
                                    "that doesn't exist" % client_urn)

    client_labels = client_object.Get(client_object.Schema.LABELS, [])

    for label in client_labels:
      client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.CheckApproversForLabel(
          token, client_urn, requester, approvers, label.name)

    return True

class HuntApproval(ApprovalWithApproversAndReason):
  """An approval request for running a specific hunt.

  This object normally lives within the namespace:
  aff4:/ACL/hunts/hunt_id/user_id/approval:<id>

  Hence the hunt_id and user_id are inferred from this object's URN.

  The aff4:/ACL namespace is not writable by users, hence all manipulation of
  this object must be done via dedicated flows. These flows use the server's
  access credentials for manipulating this object:

   - RequestHuntApprovalFlow()
   - GrantHuntApprovalFlow()
  """

  checked_approvers_label = "admin"

  def InferUserAndSubjectFromUrn(self):
    """Infers user name and subject urn from self.urn."""
    _, hunts_str, hunt_id, user, _ = self.urn.Split(5)

    if hunts_str != "hunts":
      raise access_control.UnauthorizedAccess(
          "Approval object has invalid urn %s." % self.urn,
          requested_access=self.token.requested_access)

    return (user, aff4.ROOT_URN.Add("hunts").Add(hunt_id))

class CronJobApproval(ApprovalWithApproversAndReason):
  """An approval request for managing a specific cron job.

  This object normally lives within the namespace:
  aff4:/ACL/cron/cron_job_id/user_id/approval:<id>

  Hence the hunt_id and user_id are inferred from this object's URN.

  The aff4:/ACL namespace is not writable by users, hence all manipulation of
  this object must be done via dedicated flows. These flows use the server's
  access credentials for manipulating this object:

   - RequestCronJobApprovalFlow()
   - GrantCronJobApprovalFlow()
  """

  checked_approvers_label = "admin"

  def InferUserAndSubjectFromUrn(self):
    """Infers user name and subject urn from self.urn."""
    _, cron_str, cron_job_name, user, _ = self.urn.Split(5)

    if cron_str != "cron":
      raise access_control.UnauthorizedAccess(
          "Approval object has invalid urn %s." % self.urn,
          requested_access=self.token.requested_access)

    return (user, aff4.ROOT_URN.Add("cron").Add(cron_job_name))

class AbstractApprovalWithReasonMixin(object):
  """Abstract class for approval requests/grants."""
  approval_type = None

  def BuildApprovalUrn(self, approval_id):
    """Builds approval object urn."""
    raise NotImplementedError()

  def BuildApprovalSymlinksUrns(self, unused_approval_id):
    """Builds a list of symlinks to the approval object."""
    return []

  def BuildSubjectTitle(self):
    """Returns the string with subject's title."""
    raise NotImplementedError()

  def CreateReasonHTML(self, reason):
    """Creates clickable links in the reason where appropriate.

    Args:
      reason: reason string
    Returns:
      Reason string with HTML hrefs as appropriate.

    Use a regex named group of "link":
      (?P<link>sometext)

    for things that should be turned into links.
    """
    for link_re in config_lib.CONFIG.Get("Email.link_regex_list"):
      reason = re.sub(link_re, r"""<a href="\g<link>">\g<link>""", reason)
    return reason

  @staticmethod
  def ApprovalUrnBuilder(subject, user, approval_id):
    """Encode an approval URN."""
    return aff4.ROOT_URN.Add("ACL").Add(subject).Add(user).Add(approval_id)

  @staticmethod
  def ApprovalSymlinkUrnBuilder(approval_type, subject_id, user, approval_id):
    """Build an approval symlink URN."""
    return aff4.ROOT_URN.Add("users").Add(user).Add("approvals").Add(
        approval_type).Add(subject_id).Add(approval_id)

class RequestApprovalWithReasonFlowArgs(rdf_structs.RDFProtoStruct):
  protobuf = flows_pb2.RequestApprovalWithReasonFlowArgs

class RequestApprovalWithReasonFlow(AbstractApprovalWithReasonMixin,
                                    flow.GRRFlow):
  """Base flow class for flows that request approval of a certain type."""
  args_type = RequestApprovalWithReasonFlowArgs

  def BuildApprovalReviewUrlPath(self, approval_id):
    """Build the url path to the approval review page."""
    raise NotImplementedError()

  @flow.StateHandler()
  def Start(self):
    """Create the Approval object and notify the Approval Granter."""
    approval_id = "approval:%X" % utils.PRNG.GetULong()
    self.state.approval_id = approval_id
    approval_urn = self.BuildApprovalUrn(approval_id)
    self.state.approval_urn = approval_urn

    subject_title = self.BuildSubjectTitle()
    email_msg_id = email.utils.make_msgid()

    with aff4.FACTORY.Create(
        approval_urn, self.approval_type, mode="w",
        token=self.token) as approval_request:
      approval_request.Set(
          approval_request.Schema.SUBJECT(self.args.subject_urn))
      approval_request.Set(
          approval_request.Schema.REQUESTOR(self.token.username))
      approval_request.Set(approval_request.Schema.REASON(self.args.reason))
      approval_request.Set(approval_request.Schema.EMAIL_MSG_ID(email_msg_id))

      cc_addresses = (self.args.email_cc_address,
                      config_lib.CONFIG.Get("Email.approval_cc_address"))
      email_cc = ",".join(filter(None, cc_addresses))

      # When we reply with the approval we want to cc all the people to whom the
      # original approval was sent, to avoid people approving stuff that was
      # already approved.
      if email_cc:
        reply_cc = ",".join((self.args.approver, email_cc))
      else:
        reply_cc = self.args.approver

      approval_request.Set(approval_request.Schema.EMAIL_CC(reply_cc))

      approval_request.Set(
          approval_request.Schema.NOTIFIED_USERS(self.args.approver))

      # We add ourselves as an approver as well (The requirement is that we have
      # 2 approvers, so the requester is automatically an approver).
      approval_request.AddAttribute(
          approval_request.Schema.APPROVER(self.token.username))

    approval_link_urns = self.BuildApprovalSymlinksUrns(approval_id)
    for link_urn in approval_link_urns:
      with aff4.FACTORY.Create(
          link_urn, aff4.AFF4Symlink, mode="w", token=self.token) as link:
        link.Set(link.Schema.SYMLINK_TARGET(approval_urn))

    # Notify to the users.
    for user in self.args.approver.split(","):
      user = user.strip()
      try:
        fd = aff4.FACTORY.Open(
            aff4.ROOT_URN.Add("users").Add(user),
            aff4_type=aff4_users.GRRUser,
            mode="rw",
            token=self.token)
      except aff4.InstantiationError:
        continue

      fd.Notify("GrantAccess", approval_urn,
                "Please grant access to %s" % subject_title, self.session_id)
      fd.Close()

    if not config_lib.CONFIG.Get("Email.send_approval_emails"):
      return

    reason = self.CreateReasonHTML(self.args.reason)

    template = u"""

Approval to access
%(subject_title)s requested.

The user "%(username)s" has requested access to
%(subject_title)s
for the purpose of "%(reason)s".

Please click
here
 to review this request and then grant access.

Thanks,

%(signature)s

%(image)s

"""

    # If you feel like it, add a funny cat picture here :)
    image = config_lib.CONFIG["Email.approval_signature"]

    body = template % dict(
        username=self.token.username,
        reason=reason,
        admin_ui=config_lib.CONFIG["AdminUI.url"],
        subject_title=subject_title,
        approval_url=self.BuildApprovalReviewUrlPath(approval_id),
        image=image,
        signature=config_lib.CONFIG["Email.signature"])

    email_alerts.EMAIL_ALERTER.SendEmail(
        self.args.approver,
        utils.SmartStr(self.token.username),
        u"Approval for %s to access %s." % (self.token.username, subject_title),
        utils.SmartStr(body),
        is_html=True,
        cc_addresses=email_cc,
        message_id=email_msg_id)

class GrantApprovalWithReasonFlowArgs(rdf_structs.RDFProtoStruct):
  protobuf = flows_pb2.GrantApprovalWithReasonFlowArgs

class GrantApprovalWithReasonFlow(AbstractApprovalWithReasonMixin,
                                  flow.GRRFlow):
  """Base flows class for flows that grant approval of a certain type."""
  args_type = GrantApprovalWithReasonFlowArgs

  @flow.StateHandler()
  def Start(self):
    """Create the Approval object and notify the Approval Granter."""

    if not self.args.delegate:
      raise ValueError("Delegate can't be empty.")

    if not self.args.reason:
      raise ValueError("Reason can't be empty.")

    approvals_root_urn = aff4.ROOT_URN.Add("ACL").Add(
        self.args.subject_urn.Path()).Add(self.args.delegate)
    children_urns = list(
        aff4.FACTORY.ListChildren(
            approvals_root_urn, token=self.token))
    if not children_urns:
      raise access_control.UnauthorizedAccess(
          "No approval found for user %s" % utils.SmartStr(self.token.username),
          subject=self.args.subject_urn)

    approvals = aff4.FACTORY.MultiOpen(
        children_urns, mode="r", aff4_type=Approval, token=self.token)
    found_approval_urn = None
    for approval in approvals:
      approval_reason = approval.Get(approval.Schema.REASON)
      if (utils.SmartUnicode(approval_reason) ==
          utils.SmartUnicode(self.args.reason) and
          (not found_approval_urn or
           approval_reason.age > found_approval_urn.age)):
        found_approval_urn = approval.urn
        found_approval_urn.age = approval_reason.age

    if not found_approval_urn:
      raise access_control.UnauthorizedAccess(
          "No approval with reason '%s' found for user %s" %
          (utils.SmartStr(self.args.reason),
           utils.SmartStr(self.token.username)),
          subject=self.args.subject_urn)

    subject_title = self.BuildSubjectTitle()
    access_url = self.BuildAccessUrl()

    # This object must already exist.
    try:
      approval_request = aff4.FACTORY.Open(
          found_approval_urn,
          mode="rw",
          aff4_type=self.approval_type,
          token=self.token)
    except IOError:
      raise access_control.UnauthorizedAccess(
          "Approval object does not exist.", requested_access="rw")

    # We are now an approver for this request.
    approval_request.AddAttribute(
        approval_request.Schema.APPROVER(self.token.username))
    email_msg_id = utils.SmartStr(
        approval_request.Get(approval_request.Schema.EMAIL_MSG_ID))
    email_cc = utils.SmartStr(
        approval_request.Get(approval_request.Schema.EMAIL_CC))

    approval_request.Close(sync=True)

    # Notify to the user.
    fd = aff4.FACTORY.Create(
        aff4.ROOT_URN.Add("users").Add(self.args.delegate),
        aff4_users.GRRUser,
        mode="rw",
        token=self.token)

    fd.Notify("ViewObject", self.args.subject_urn,
              "%s has granted you access to %s." %
              (self.token.username, subject_title), self.session_id)
    fd.Close()

    if not config_lib.CONFIG.Get("Email.send_approval_emails"):
      return

    reason = self.CreateReasonHTML(self.args.reason)

    template = u"""

Access to
%(subject_title)s granted.

The user %(username)s has granted access to
%(subject_title)s for the
purpose of "%(reason)s".

Please click here to access it.

Thanks,

%(signature)s

"""

    body = template % dict(
        subject_title=subject_title,
        username=self.token.username,
        reason=reason,
        admin_ui=config_lib.CONFIG["AdminUI.url"],
        subject_url=access_url,
        signature=config_lib.CONFIG["Email.signature"])

    # Email subject should match approval request, and we add message id
    # references so they are grouped together in a thread by gmail.
    subject = u"Approval for %s to access %s." % (
        utils.SmartStr(self.args.delegate), subject_title)
    headers = {"In-Reply-To": email_msg_id, "References": email_msg_id}
    email_alerts.EMAIL_ALERTER.SendEmail(
        utils.SmartStr(self.args.delegate),
        utils.SmartStr(self.token.username),
        subject,
        utils.SmartStr(body),
        is_html=True,
        cc_addresses=email_cc,
        headers=headers)

class BreakGlassGrantApprovalWithReasonFlow(GrantApprovalWithReasonFlow):
  """Grant an approval in an emergency."""

  @flow.StateHandler()
  def Start(self):
    """Create the Approval object and notify the Approval Granter."""
    approval_id = "approval:%X" % utils.PRNG.GetULong()

    approval_urn = self.BuildApprovalUrn(approval_id)
    subject_title = self.BuildSubjectTitle()

    # Create a new Approval object.
    approval_request = aff4.FACTORY.Create(
        approval_urn, aff4_type=self.approval_type, token=self.token)

    approval_request.Set(approval_request.Schema.REASON(self.args.reason))
    approval_request.AddAttribute(
        approval_request.Schema.APPROVER(self.token.username))

    # This is a break glass approval.
    break_glass = rdfvalue.RDFDatetime.Now()

    # By default a break_glass approval only lasts 24 hours.
    break_glass += rdfvalue.Duration("24h")
    approval_request.Set(approval_request.Schema.BREAK_GLASS, break_glass)
    approval_request.Close(sync=True)

    # Notify the user.
    fd = aff4.FACTORY.Create(
        aff4.ROOT_URN.Add("users").Add(self.token.username),
        aff4_users.GRRUser,
        mode="rw",
        token=self.token)

    fd.Notify("ViewObject", self.args.subject_urn,
              "An Emergency Approval has been granted to access "
              "%s." % subject_title, self.session_id)
    fd.Close()

    template = u"""

Emergency Access Granted.

The user %(username)s has requested emergency access to %(subject_title)s.
for the purpose of: "%(reason)s".

This access has been logged and granted for 24 hours.

Thanks,

%(signature)s

"""

    body = template % dict(
        client_id=self.client_id,
        username=self.token.username,
        subject_title=subject_title,
        reason=self.args.reason,
        signature=config_lib.CONFIG["Email.signature"]),

    email_alerts.EMAIL_ALERTER.SendEmail(
        config_lib.CONFIG["Monitoring.emergency_access_email"],
        self.token.username,
        u"Emergency approval granted for %s." % subject_title,
        utils.SmartStr(body),
        is_html=True,
        cc_addresses=config_lib.CONFIG["Email.approval_cc_address"])

class RequestClientApprovalFlow(RequestApprovalWithReasonFlow):
  """A flow to request approval to access a client."""
  # This flow can run on any client without ACL enforcement (an SUID flow).
  ACL_ENFORCED = False

  approval_type = ClientApproval

  @property
  def subject_urn(self):
    return self.client_id or rdf_client.ClientURN(self.args.subject_urn)

  def BuildApprovalUrn(self, approval_id):
    """Builds approval object urn."""
    event = events.AuditEvent(
        user=self.token.username,
        action="CLIENT_APPROVAL_REQUEST",
        client=self.subject_urn,
        description=self.args.reason)
    events.Events.PublishEvent("Audit", event, token=self.token)

    return self.ApprovalUrnBuilder(self.subject_urn.Path(), self.token.username,
                                   approval_id)

  def BuildApprovalSymlinksUrns(self, approval_id):
    """Builds list of symlinks URNs for the approval object."""
    return [
        self.ApprovalSymlinkUrnBuilder("client",
                                       self.subject_urn.Basename(),
                                       self.token.username, approval_id)
    ]

  def BuildSubjectTitle(self):
    """Returns the string with subject's title."""
    client = aff4.FACTORY.Open(self.subject_urn, token=self.token)
    hostname = client.Get(client.Schema.HOSTNAME)
    return u"GRR client %s (%s)" % (self.subject_urn.Basename(), hostname)

  def BuildApprovalReviewUrlPath(self, approval_id):
    return "/".join([
        "users", self.token.username, "approvals", "client",
        self.subject_urn.Basename(), approval_id
    ])

class GrantClientApprovalFlow(GrantApprovalWithReasonFlow):
  """Grant the approval requested."""
  # This flow can run on any client without ACL enforcement (an SUID flow).
  ACL_ENFORCED = False

  approval_type = ClientApproval

  @property
  def subject_urn(self):
    return self.client_id or rdf_client.ClientURN(self.args.subject_urn)

  def BuildApprovalUrn(self, approval_id):
    """Builds approval object urn."""
    events.Events.PublishEvent(
        "Audit",
        events.AuditEvent(
            user=self.token.username,
            action="CLIENT_APPROVAL_GRANT",
            client=self.subject_urn,
            description=self.args.reason),
        token=self.token)

    return self.ApprovalUrnBuilder(self.subject_urn.Path(), self.args.delegate,
                                   approval_id)

  def BuildAccessUrl(self):
    """Builds the urn to access this object."""
    return urllib.urlencode((("c", self.subject_urn),
                             ("main", "HostInformation")))

  def BuildSubjectTitle(self):
    """Returns the string with subject's title."""
    client = aff4.FACTORY.Open(self.subject_urn, token=self.token)
    hostname = client.Get(client.Schema.HOSTNAME)
    return u"GRR client %s (%s)" % (self.subject_urn.Basename(), hostname)

class BreakGlassGrantClientApprovalFlow(BreakGlassGrantApprovalWithReasonFlow):
  """Grant an approval in an emergency."""
  # This flow can run on any client without ACL enforcement (an SUID flow).
  ACL_ENFORCED = False

  approval_type = ClientApproval

  def BuildApprovalUrn(self, approval_id):
    """Builds approval object urn."""
    event = events.AuditEvent(
        user=self.token.username,
        action="CLIENT_APPROVAL_BREAK_GLASS_REQUEST",
        client=self.client_id,
        description=self.args.reason)
    events.Events.PublishEvent("Audit", event, token=self.token)

    return self.ApprovalUrnBuilder(self.client_id.Path(), self.token.username,
                                   approval_id)

  def BuildSubjectTitle(self):
    """Returns the string with subject's title."""
    client = aff4.FACTORY.Open(self.client_id, token=self.token)
    hostname = client.Get(client.Schema.HOSTNAME)
    return u"GRR client %s (%s)" % (self.client_id.Basename(), hostname)

class RequestHuntApprovalFlow(RequestApprovalWithReasonFlow):
  """A flow to request approval to access a client."""
  # This flow can run on any client without ACL enforcement (an SUID flow).
  ACL_ENFORCED = False

  approval_type = HuntApproval

  def BuildApprovalUrn(self, approval_id):
    """Builds approval object URN."""
    # In this case subject_urn is hunt's URN.
    events.Events.PublishEvent(
        "Audit",
        events.AuditEvent(
            user=self.token.username,
            action="HUNT_APPROVAL_REQUEST",
            urn=self.args.subject_urn,
            description=self.args.reason),
        token=self.token)

    return self.ApprovalUrnBuilder(self.args.subject_urn.Path(),
                                   self.token.username, approval_id)

  def BuildApprovalSymlinksUrns(self, approval_id):
    """Builds list of symlinks URNs for the approval object."""
    return [
        self.ApprovalSymlinkUrnBuilder("hunt",
                                       self.args.subject_urn.Basename(),
                                       self.token.username, approval_id)
    ]

  def BuildSubjectTitle(self):
    """Returns the string with subject's title."""
    return u"hunt %s" % self.args.subject_urn.Basename()

  def BuildApprovalReviewUrlPath(self, approval_id):
    return "/".join([
        "users", self.token.username, "approvals", "hunt",
        self.args.subject_urn.Basename(), approval_id
    ])

class GrantHuntApprovalFlow(GrantApprovalWithReasonFlow):
  """Grant the approval requested."""
  # This flow can run on any client without ACL enforcement (an SUID flow).
  ACL_ENFORCED = False

  approval_type = HuntApproval

  def BuildApprovalUrn(self, approval_id):
    """Builds approval object URN."""
    # In this case subject_urn is hunt's URN.
    events.Events.PublishEvent(
        "Audit",
        events.AuditEvent(
            user=self.token.username,
            action="HUNT_APPROVAL_GRANT",
            urn=self.args.subject_urn,
            description=self.args.reason),
        token=self.token)

    return self.ApprovalUrnBuilder(self.args.subject_urn.Path(),
                                   self.args.delegate, approval_id)

  def BuildSubjectTitle(self):
    """Returns the string with subject's title."""
    return u"hunt %s" % self.args.subject_urn.Basename()

  def BuildAccessUrl(self):
    """Builds the urn to access this object."""
    return urllib.urlencode((("main", "ManageHunts"), ("hunt",
                                                       self.args.subject_urn)))

class RequestCronJobApprovalFlow(RequestApprovalWithReasonFlow):
  """A flow to request approval to manage a cron job."""
  # This flow can run on any client without ACL enforcement (an SUID flow).
  ACL_ENFORCED = False

  approval_type = CronJobApproval

  def BuildApprovalUrn(self, approval_id):
    """Builds approval object URN."""
    # In this case subject_urn is a cron job's URN.
    events.Events.PublishEvent(
        "Audit",
        events.AuditEvent(
            user=self.token.username,
            action="CRON_APPROVAL_REQUEST",
            urn=self.args.subject_urn,
            description=self.args.reason),
        token=self.token)

    return self.ApprovalUrnBuilder(self.args.subject_urn.Path(),
                                   self.token.username, approval_id)

  def BuildApprovalSymlinksUrns(self, approval_id):
    """Builds list of symlinks URNs for the approval object."""
    return [
        self.ApprovalSymlinkUrnBuilder("cron",
                                       self.args.subject_urn.Basename(),
                                       self.token.username, approval_id)
    ]

  def BuildSubjectTitle(self):
    """Returns the string with subject's title."""
    return u"a cron job"

  def BuildApprovalReviewUrlPath(self, approval_id):
    return "/".join([
        "users", self.token.username, "approvals", "cron-job",
        self.args.subject_urn.Basename(), approval_id
    ])

class GrantCronJobApprovalFlow(GrantApprovalWithReasonFlow):
  """Grant approval to manage a cron job."""
  # This flow can run on any client without ACL enforcement (an SUID flow).
  ACL_ENFORCED = False

  approval_type = CronJobApproval

  def BuildApprovalUrn(self):
    """Builds approval object URN."""
    # In this case subject_urn is hunt's URN.
    events.Events.PublishEvent(
        "Audit",
        events.AuditEvent(
            user=self.token.username,
            action="CRON_APPROVAL_GRANT",
            urn=self.args.subject_urn,
            description=self.args.reason),
        token=self.token)

    return self.ApprovalUrnBuilder(self.args.subject_urn.Path(),
                                   self.args.delegate, self.args.reason)

  def BuildSubjectTitle(self):
    """Returns the string with subject's title."""
    return u"a cron job"

  def BuildAccessUrl(self):
    """Builds the urn to access this object."""
    return urllib.urlencode({"main": "ManageCron"})


text:
/* jshint indent: 2 */

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('YliFile', {
    fileId: {
      field: 'file_id',
      primaryKey: true,
      type: DataTypes.BIGINT,
      allowNull: false
    },
    parentId: {
      field: 'parent_id',
      type: DataTypes.BIGINT,
      allowNull: true
    },
    fsFileId: {
      field: 'fs_file_id',
      type: DataTypes.BIGINT,
      allowNull: true
    },
    fileType: {
      field: 'file_type',
      type: DataTypes.STRING,
      allowNull: false
    },
    parentIds: {
      field: 'parent_ids',
      type: DataTypes.STRING,
      allowNull: false
    },
    fileName: {
      field: 'file_name',
      type: DataTypes.STRING,
      allowNull: false
    },
    fileSize: {
      field: 'file_size',
      type: DataTypes.BIGINT,
      allowNull: true
    },
    thumb: {
      field: 'thumb',
      type: DataTypes.STRING,
      allowNull: true
    },
    folder: {
      field: 'folder',
      type: DataTypes.BOOLEAN,
      allowNull: false
    },
    version: {
      field: 'version',
      type: DataTypes.BIGINT,
      allowNull: false
    },
    lastAction: {
      field: 'last_action',
      type: DataTypes.STRING,
      allowNull: false
    },
    convStatus: {
      field: 'conv_status',
      type: DataTypes.INTEGER(11),
      allowNull: false,
      defaultValue: '0'
    },
    indexStatus: {
      field: 'index_status',
      type: DataTypes.INTEGER(11),
      allowNull: false,
      defaultValue: '0'
    },
    indexTime: {
      field: 'index_time',
      type: DataTypes.DATE,
      allowNull: true
    },
    delStatus: {
      field: 'del_status',
      type: DataTypes.INTEGER(4),
      allowNull: false,
      defaultValue: '0'
    },
    createrId: {
      field: 'creater_id',
      type: DataTypes.BIGINT,
      allowNull: false
    },
    createrName: {
      field: 'creater_name',
      type: DataTypes.STRING,
      allowNull: false
    },
    createTime: {
      field: 'create_time',
      type: DataTypes.DATE,
      allowNull: false
    },
    updateUserId: {
      field: 'update_user_id',
      type: DataTypes.BIGINT,
      allowNull: true
    },
    updateUserName: {
      field: 'update_user_name',
      type: DataTypes.STRING,
      allowNull: true
    },
    updateTime: {
      field: 'update_time',
      type: DataTypes.DATE,
      allowNull: true
    }
  } , {
    tableName: 'yli_file',
    timestamps: false,
    freezeTableName: true
  });
};


text:
package olx;

import com.google.gwt.dom.client.Element;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
import ol.Coordinate;

/**
 * @author Dan Moldovan
 */
@JsType(isNative = true)
public interface OverlayOptions {

    @JsProperty
    void setId(String id);

    @JsProperty
    void setElement(Element element);

    @JsProperty
    void setOffset(int[] offset);

    @JsProperty
    void setPosition(Coordinate coordinate);

    @JsProperty
    void setPositioning(String positioning);

    @JsProperty
    void setStopEvent(boolean stopEvent);

    @JsProperty
    void setInsertFirst(boolean insertFirst);

    @JsProperty
    void setAutoPan(boolean autoPan);

    @JsProperty
    void setAutoPanMargin(int autoPanMargin);

}