text:
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"

	"github.com/estesp/manifest-tool/v2/pkg/registry"
	"github.com/estesp/manifest-tool/v2/pkg/store"
	"github.com/estesp/manifest-tool/v2/pkg/types"
	"github.com/estesp/manifest-tool/v2/pkg/util"

	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)

const (
	cacheTimeout = time.Hour
)

var (
	tableName  = "imagecache"
	dynaClient dynamodbiface.DynamoDBAPI
)

// ErrorBody is used to encapsulate error responses to the client
type ErrorBody struct {
	ErrorMsg *string `json:"error,omitempty"`
}

// Image represents the cached JSON metadata about the image
type Image struct {
	CacheTS   int64              `json:"cachets"`
	IsList    bool               `json:"islist"`
	ImageName string             `json:"imagename"`
	Digest    string             `json:"digest"`
	MediaType string             `json:"mediatype"`
	ArchList  []ocispec.Platform `json:"archlist"`
}

func main() {
	region := os.Getenv("AWS_REGION")
	awsSession, err := session.NewSession(&aws.Config{
		Region: aws.String(region)},
	)
	if err != nil {
		return
	}
	dynaClient = dynamodb.New(awsSession)
	lambda.Start(handleRequest)
}

func inspectImage(req events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
	imageName := req.QueryStringParameters["image"]
	if len(imageName) == 0 {
		return apiResponse(http.StatusBadRequest, ErrorBody{aws.String("No image name provided")})
	}
	// check cache
	if image, err := checkCache(imageName); err == nil {
		return apiResponse(http.StatusOK, image)
	}
	// inspect image
	image, err := queryRegistry(imageName)
	if err != nil {
		return apiResponse(http.StatusBadRequest, ErrorBody{aws.String(fmt.Sprintf("Error querying image: %s", err))})
	}
	if err = cacheImage(image); err != nil {
		log.Printf("WARN: unable to cache image: %v", err)
	}

	return apiResponse(http.StatusOK, image)
}

func handleRequest(req events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
	switch req.HTTPMethod {
	case "GET":
		return inspectImage(req)
	}
	return apiResponse(http.StatusMethodNotAllowed, "method not allowed")
}

func apiResponse(status int, body interface{}) (*events.APIGatewayProxyResponse, error) {
	resp := events.APIGatewayProxyResponse{Headers: map[string]string{"Content-Type": "application/json"}}
	resp.StatusCode = status

	stringBody, _ := json.Marshal(body)
	resp.Body = string(stringBody)
	return &resp, nil
}

func checkCache(imageName string) (*Image, error) {
	input := &dynamodb.GetItemInput{
		Key: map[string]*dynamodb.AttributeValue{
			"imagename": {
				S: aws.String(imageName),
			},
		},
		TableName: aws.String(tableName),
	}

	result, err := dynaClient.GetItem(input)
	if err != nil {
		return nil, errors.New("failed to find image")
	}

	item := new(Image)
	err = dynamodbattribute.UnmarshalMap(result.Item, item)
	if err != nil {
		return nil, errors.New("failed to unmarshal image cached details")
	}
	cacheTime := time.Unix(item.CacheTS, 0)
	if cacheTime.Add(cacheTimeout).Before(time.Now()) {
		// invalidate
		deleteCache(imageName)
		return nil, errors.New("Cache expired image " + imageName)
	}
	return item, nil
}

func deleteCache(imageName string) {
	input := &dynamodb.DeleteItemInput{
		Key: map[string]*dynamodb.AttributeValue{
			"imagename": {
				S: aws.String(imageName),
			},
		},
		TableName: aws.String(tableName),
	}

	if _, err := dynaClient.DeleteItem(input); err != nil {
		log.Printf("error deleting cache item for %s: %v", imageName, err)
	}
}

func cacheImage(image *Image) error {
	av, err := dynamodbattribute.MarshalMap(image)
	if err != nil {
		return errors.New("could not marshal image data")
	}

	input := &dynamodb.PutItemInput{
		Item:      av,
		TableName: aws.String(tableName),
	}

	_, err = dynaClient.PutItem(input)
	if err != nil {
		return errors.New("could not write to dynamoDB")
	}
	return nil
}

func queryRegistry(name string) (*Image, error) {
	var image *Image
	imageRef, err := util.ParseName(name)
	if err != nil {
		return nil, err
	}

	memoryStore := store.NewMemoryStore()
	resolver := util.NewResolver("", "", false, false, "")

	descriptor, err := registry.FetchDescriptor(resolver, memoryStore, imageRef)
	if err != nil {
		return nil, err
	}

	_, db, _ := memoryStore.Get(descriptor)
	switch descriptor.MediaType {
	case ocispec.MediaTypeImageIndex, types.MediaTypeDockerSchema2ManifestList:
		// this is a multi-platform image descriptor; marshal to Index type
		var idx ocispec.Index
		if err := json.Unmarshal(db, &idx); err != nil {
			return nil, err
		}
		image = generateImage(name, memoryStore, descriptor, idx, ocispec.Image{})
	case ocispec.MediaTypeImageManifest, types.MediaTypeDockerSchema2Manifest:
		var man ocispec.Manifest
		if err := json.Unmarshal(db, &man); err != nil {
			return nil, err
		}
		_, cb, _ := memoryStore.Get(man.Config)
		var conf ocispec.Image
		if err := json.Unmarshal(cb, &conf); err != nil {
			return nil, err
		}
		image = generateImage(name, memoryStore, descriptor, ocispec.Index{}, conf)
		return image, nil
	default:
		return nil, errors.New("Unknown descriptor type: " + descriptor.MediaType)
	}
	return image, nil
}

func generateImage(name string, cs *store.MemoryStore, desc ocispec.Descriptor, index ocispec.Index, imgConfig ocispec.Image) *Image {
	image := new(Image)
	image.Digest = desc.Digest.String()
	image.MediaType = desc.MediaType
	image.ImageName = name
	image.CacheTS = time.Now().Unix()
	switch desc.MediaType {
	case ocispec.MediaTypeImageIndex, types.MediaTypeDockerSchema2ManifestList:
		image.IsList = true
		for _, img := range index.Manifests {
			image.ArchList = append(image.ArchList, *img.Platform)
		}
	default:
		image.ArchList = []ocispec.Platform{{
			OS:           imgConfig.OS,
			Architecture: imgConfig.Architecture,
		}}
	}
	return image
}


text:
from ABE_ExpanderPi import ADC
import time

"""
================================================
ABElectronics Expander Pi | ADC Read Demo
Version 1.0 Created 29/03/2015

run with: python3 demo-adcread.py
================================================

this demo reads the voltage from channel 1 on the ADC inputs
"""

adc = ADC()  # create an instance of the ADC

# set the reference voltage.  this should be set to the exact voltage
# measured on the Expander Pi Vref pin.
adc.set_adc_refvoltage(4.096)

while True:
    # read the voltage from channel 1 and display on the screen
    print (adc.read_adc_voltage(1))
    time.sleep(0.5)

redpajama_set_name: RedPajamaGithub


text:
//
//  TypesetLabel.m
//  TypesettingLabel
//
//  Created by MyMac on 15/10/21.
//  Copyright © 2015年 MyMac. All rights reserved.
//

#import "TypesetLabel.h"
#import "TypesetModelLabel.h"

@interface TypesetLabel ()

/**
 *  带有样式的string
 */
@property (nonatomic,strong) NSMutableAttributedString *attrStringM;

/**
 *  样式
 */
@property (nonatomic,strong) NSMutableParagraphStyle *style;

/**
 *  附件
 */
@property (nonatomic,strong) NSMutableArray *attatchmentsM;

@end

@implementation TypesetLabel

- (instancetype)init
{
    self = [super init];
    if (self) {

    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize{

    self.verticalAlignment = TypesetLabellVerticalAlignmentMiddle;

    self.numberOfLines = 0;
}

#pragma mark - 方法体
- (void)addAttrWithName:(NSString *)name value:(id)value range:(NSRange)range{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.attrStringM addAttribute:name value:value range:range];
        self.attributedText = self.attrStringM;
    });
}

- (void)addAttr:(TypesetLabelAttr)attr value:(id)value range:(NSRange)range{
    switch (attr) {
        case TypesetLabelAttrColor: //颜色
            [self setColor:value range:range];
            break;
        case TypesetLabelAttrFont://字体
            [self setFont:value range:range];
            break;
        case TypesetLabelAttrItalics: //斜体
            [self setAttrItalics:value range:range];
            break;
        case TypesetLabelAttrWordSpacing: //字间距
            [self setKern:value range:range];
            break;
        case TypesetLabelAttrDeleteLine://删除线
            [self setDeleteLineWithColor:value range:range];
            break;
        case TypesetLabelAttrUnderLine: //下划线
            [self setUnderLineWithColor:value range:range];
            break;
        default:
            break;
    }
}

- (void)addImage:(UIImage *)image size:(CGSize)size offset:(UIOffset)offset location:(NSUInteger)location{
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];

    //设置图片
    attachment.image = image;

    if (CGSizeEqualToSize(size, CGSizeZero)) {
        size = CGSizeMake(self.font.lineHeight, self.font.lineHeight);
    }

    //设置大小
    attachment.bounds = (CGRect){CGPointMake(offset.horizontal, offset.vertical),size};

    TypesetModelLabel *labelModel = [TypesetModelLabel labelWithAttachment:attachment index:location];

    [self.attatchmentsM addObject:labelModel];

}

- (void)updateLabelStyle{
    if (self.attrStringM == nil) return;

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.attrStringM addAttribute:NSParagraphStyleAttributeName value:self.style range:NSMakeRange(0, self.attrStringM.length)];

        //添加图片控件
        if (self.attatchmentsM.count != 0) {
            //排序
            NSArray *sortedLabelModels = [TypesetModelLabel sortLabelModels:self.attatchmentsM];

            [sortedLabelModels enumerateObjectsUsingBlock:^(TypesetModelLabel *labelModel, NSUInteger idx, BOOL *stop) {

                NSAttributedString *attrString = labelModel.attrString;
                NSUInteger index = labelModel.index + idx;
                [self.attrStringM insertAttributedString:attrString atIndex:index];

            }];

        }
        self.attributedText = self.attrStringM;
    });

}

#pragma mark - 重写方法
- (void)drawTextInRect:(CGRect)rect{

    CGRect actualRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];

    [super drawTextInRect:actualRect];

}

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines{
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];

    switch (self.verticalAlignment) {
        case TypesetLabellVerticalAlignmentTop: {
            textRect.origin.y = bounds.origin.y;
            break;
        }
        case TypesetLabellVerticalAlignmentBottom: {
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
            break;
        }
        default: {
            textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) * 0.5;
            break;
        }
    }
    return textRect;

}

#pragma mark - getter and setter
- (void)setText:(NSString *)text{
    [super setText:text];

    self.attrStringM = [[NSMutableAttributedString alloc] initWithString:text];

    self.attributedText = self.attrStringM;

}

- (NSMutableArray *)attatchmentsM{
    if (!_attrStringM) {
        _attatchmentsM = [NSMutableArray array];
    }
    return _attatchmentsM;
}

- (void)setVerticalAlignment:(TypesetLabelVerticalAlignment)verticalAlignment{
    _verticalAlignment = verticalAlignment;

    dispatch_async(dispatch_get_main_queue(), ^{
        [self setNeedsDisplay];
    });

}

- (NSMutableParagraphStyle *)style{
    if (!_style) {
        _style = [[NSMutableParagraphStyle alloc] init];

        self.lineSpacing = 0; //设置行间距

        self.paragraphSpacing = 0;  //设置段落间距

        self.firstLineIndent = 0; //首行缩进

        CGFloat height = self.font.pointSize;
        _style.maximumLineHeight=height;
        _style.lineHeightMultiple=0;

    }
    return _style;
}

//首行缩进
- (void)setFirstLineIndent:(CGFloat)firstLineIndent{
    _firstLineIndent = firstLineIndent;
    self.style.firstLineHeadIndent = firstLineIndent;
}

//行间距
- (void)setLineSpacing:(CGFloat)lineSpacing{
    _lineSpacing = lineSpacing;
    self.style.lineSpacing = lineSpacing;
}

//段落之间的间距
- (void)setParagraphSpacing:(CGFloat)paragraphSpacing{
    _paragraphSpacing = paragraphSpacing;
    self.style.paragraphSpacing = paragraphSpacing;
}

//颜色
- (void)setColor:(UIColor *)color range:(NSRange)range{
    [self addAttrWithName:NSForegroundColorAttributeName value:color range:range];
}

//字体
- (void)setFont:(UIFont *)font range:(NSRange)range{
    [self addAttrWithName:NSFontAttributeName value:font range:range];
}

//斜体
- (void)setAttrItalics:(id)italics range:(NSRange)range{
    [self addAttrWithName:NSObliquenessAttributeName value:italics range:range];
}

//字间距
- (void)setKern:(id)kern range:(NSRange)range{
    [self addAttrWithName:NSKernAttributeName value:kern range:range];
}

//删除线
- (void)setDeleteLineWithColor:(UIColor *)color range:(NSRange)range{
    [self addAttrWithName:NSStrikethroughStyleAttributeName value:@(YES) range:range];
    [self addAttrWithName:NSStrikethroughColorAttributeName value:color range:range];
}

//下划线
- (void)setUnderLineWithColor:(UIColor *)color range:(NSRange)range{
    [self addAttrWithName:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range];
    [self addAttrWithName:NSUnderlineColorAttributeName value:color range:range];
}

@end


text:
require File.dirname(__FILE__) + "/../../../test_helper.rb"
require 'ubiquo/filters/link_filter'

class LinkFilterTest < Ubiquo::Filters::UbiquoFilterTestCase

  def setup
    @filter = LinkFilter.new(@model, @context)
    @filter.configure(:title,@model.all)
  end

  test "Should be able to render a Link filter" do
    doc = HTML::Document.new(@filter.render).root
    assert_select doc, 'div#links_filter_content a', 3
  end

  test "Should be able to get a message when the filter is set" do
    @context.params.merge!({ 'filter_title' => 'my_title_text' })
    assert_match /my_title_text/, @filter.message.first
  end

end


text:
(function($) {

	$.fn.printLink = function(options) {
		var iframe = null;
        var settings = $.extend({
            url: null
        }, options);

        // Apply to all elements
        return this.each(function() {

			// Click handler on the link
			$(this).on('click', function(event) {
				event.preventDefault();

				// Target element
				var element = $(this);

				// Get the url from the anchor or overwrite it
				var url = element.attr('href');
				if(settings.url) {
					url = settings.url;
				}

				// Open the url directly when an iframe printing is not supported.
				if(navigator.userAgent.match(/opera/i) || navigator.userAgent.match(/trident/i) || (navigator.userAgent.match(/msie/i) && window.addEventListener)) {
					element.trigger('printLinkError');
					return false;
				}

				// Trigger load
				element.trigger('printLinkInit');

				// Print the url with a hidden iframe
				if(!$('#printLinkIframe')[0]) {
					// Create a new iframe
					var iframe = '<iframe id="printLinkIframe" name="printLinkIframe" src=' + url + ' style="position:absolute;top:-9999px;left:-9999px;border:0px;overfow:none; z-index:-1"></iframe>';
					$('body').append(iframe);

					// Start the printing when the url is loaded
					$('#printLinkIframe').on('load',function() {
						element.trigger('printLinkComplete');
						frames['printLinkIframe'].focus();
						frames['printLinkIframe'].print();
					});
				} else {
					// Change the iframe src in case the iframe already exists
					$('#printLinkIframe').attr('src', url);
				}
			});

		});

        return this;
    };

}(jQuery));


text: export * from './custom-material-module';


text:
<?php
$show_breadcrumbs = true;
require_once 'functions.php';
$section = 8;
$page = 2;
?>
<!DOCTYPE html>

    <?php echo $header ?>
    <title>Mailing List | <?php echo SITENAME ?></title>

<?php require_once 'include.header.php'; ?>

Stay up to date!

    Receive an occasional email with updates from the Metabolism of Cities website! We use Mailchimp
    for sending out the newsletters and they will keep your e-mail safe. You can unsubscribe at any time. Newsletters are sent out about
    3 times per year.

      <link href="//cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">

      <form action="//mfa-tools.us8.list-manage.com/subscribe/post?u=ac623181f98df6ff1b52a1668&id=59a1b98376" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe to our mailing list

        Email Address
        <input type="email" value="<?php echo strip_tags($_POST['email']) ?>" name="EMAIL" class="required email" id="mce-EMAIL">

        First Name
        <input type="text" value="" name="FNAME" class="" id="mce-FNAME">

        Last Name
        <input type="text" value="" name="LNAME" class="" id="mce-LNAME">

<input type="text" name="b_ac623181f98df6ff1b52a1668_59a1b98376" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

      </form>

Newsletter archive

View the archive of our past newsletters below:

View Archive

<?php require_once 'include.footer.php'; ?>


text:
// Copyright (c) MOSA Project. Licensed under the New BSD License.

namespace Mosa.HardwareSystem
{
	/// <summary>
	///
	/// </summary>
	public sealed class IOPortRegion
	{
		/// <summary>
		/// Gets the base IO port.
		/// </summary>
		/// <value>The base IO port.</value>
		public ushort BaseIOPort { get; private set; }

		/// <summary>
		/// Gets the size.
		/// </summary>
		/// <value>The size.</value>
		public ushort Size { get; private set; }

		/// <summary>
		/// Initializes a new instance of the <see cref="IOPortRegion"/> class.
		/// </summary>
		/// <param name="baseIOPort">The base IO port.</param>
		/// <param name="size">The size.</param>
		public IOPortRegion(ushort baseIOPort, ushort size)
		{
			this.BaseIOPort = baseIOPort;
			this.Size = size;
		}
	}
}


text:
<?php

namespace ipinga;

Abstract Class controller
{

    /**
     * @var \ipinga\template
     */
    public $template;

    /**
     * I like having this, but it's really not needed by every controller by any means.
     *
     * @var array
     */
    public $json = array();

    function __construct()
    {
        $this->template = new \ipinga\template();
    }

    /**
     * all controllers must contain an index method
     */
    abstract function index();

    public function SendJSON($arrayToSendAsJson = null)
    {

        // If you get careless, this next line can be uncommented to wipe clean all the output buffer prior to
        // setting the value in the header.   But if you are going to send a json response, it really should be
        // your only response and therefore the buffer shouldn't have anything in it.  Uncommenting this line
        // is only a suggestion for lazy programmers   :)
        //
        // ob_end_clean();

        header("Content-Type:text/json");
        echo json_encode(isset($arrayToSendAsJson) ? $arrayToSendAsJson : $this->json);
        exit();
    }

}


text:
package quota_manager_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestQuota_manager(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Quota Manager Suite")
}


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using int32.Utils.Core.Extensions;
using int32.Utils.Core.Generic.Factory;
using int32.Utils.Web.WebServer.Processors;
using int32.Utils.Web.WebServer.Processors.Contracts;

namespace int32.Utils.Web.WebServer
{
    public class WebServer
    {
        private HttpListener _listener;
        private List<IRequestProcessor> _processors;
        private readonly AutoResetEvent _listenForNextRequest = new AutoResetEvent(false);

        public Bootstrapper Config { get; internal set; }

        #region events

        public Action OnStarted { get; set; }
        public Action OnStopped { get; set; }
        public Action<IRequestProcessor, HttpListenerContext> OnRequestProcessed { get; set; }
        public Action<HttpListenerContext> OnRequestReceived { get; set; }

        #endregion

        public WebServer Start<T>() where T : Bootstrapper
        {
            Config = Factory<T>.Create().ThrowIfNull("bootstrapper");
            Setup();
            return this;
        }

        public void Stop()
        {
            _listener.Stop();
            OnStopped.Execute();
        }

        private void Setup()
        {
            _listener = new HttpListener();
            _listener.Prefixes.Add(Config.Url + "/");
            _listener.AuthenticationSchemes = Config.Authentication;

            //set the default processors
            _processors = new List<IRequestProcessor>()
            {
                new ApiRequestProcessor(),
                new WebRequestProcessor()
            };

            //add additional ones from the config
            _processors.AddRange(Config.Processors);

            RunServer();
        }

        private void RunServer()
        {
            _listener.Start();

            ThreadPool.QueueUserWorkItem(state =>
            {
                while (_listener.IsListening)
                {
                    _listener.BeginGetContext(result =>
                    {
                        var listener = result.AsyncState as HttpListener;

                        try
                        {
                            if (listener == null)
                                return;

                            var context = listener.EndGetContext(result);

                            ProcessRequest(context);
                        }
                        catch
                        {
                        }
                        finally
                        {
                            _listenForNextRequest.Set();
                        }
                    }, _listener);

                    _listenForNextRequest.WaitOne();
                }
            });

            OnStarted.Execute();
        }

        private void ProcessRequest(HttpListenerContext context)
        {
            try
            {
                OnRequestReceived.Execute(context);

                foreach (var processor in _processors)
                {
                    //when the first processor managed the request
                    //do not proceed with other processors
                    if (processor.IsNotNull() && processor.Process(context))
                    {
                        OnRequestProcessed.Execute(processor, context);
                        break;
                    }
                }
            }
            finally
            {
                //close the response
                context.Response.OutputStream.Close();
            }
        }
    }
}


text:
#include "test.h"

/*
 * Create NUMTHREADS threads in addition to the Main thread.
 */
enum {
  NUMTHREADS = 2
};

typedef struct bag_t_ bag_t;
struct bag_t_ {
  int threadnum;
  int started;
  /* Add more per-thread state variables here */
};

static bag_t threadbag[NUMTHREADS + 1];

void *
mythread(void * arg)
{
  bag_t * bag = (bag_t *) arg;

  assert(bag == &threadbag[bag->threadnum]);
  assert(bag->started == 0);
  bag->started = 1;

  /* ... */
  {
    int oldstate;
    int oldtype;

    assert(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate) == 0);
    assert(oldstate == PTHREAD_CANCEL_ENABLE); /* Check default */
    assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0);
    assert(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) == 0);
    assert(pthread_setcancelstate(oldstate, &oldstate) == 0);
    assert(oldstate == PTHREAD_CANCEL_DISABLE); /* Check setting */

    assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype) == 0);
    assert(oldtype == PTHREAD_CANCEL_DEFERRED); /* Check default */
    assert(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) == 0);
    assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0);
    assert(pthread_setcanceltype(oldtype, &oldtype) == 0);
    assert(oldtype == PTHREAD_CANCEL_ASYNCHRONOUS); /* Check setting */
  }

  return 0;
}

int
main()
{
  int failed = 0;
  int i;
  pthread_t t[NUMTHREADS + 1];

  assert((t[0] = pthread_self()).p != NULL);

  for (i = 1; i <= NUMTHREADS; i++)
    {
      threadbag[i].started = 0;
      threadbag[i].threadnum = i;
      assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0);
    }

  /*
   * Code to control or munipulate child threads should probably go here.
   */

  /*
   * Give threads time to run.
   */
  Sleep(NUMTHREADS * 100);

  /*
   * Standard check that all threads started.
   */
  for (i = 1; i <= NUMTHREADS; i++)
    {
      failed = !threadbag[i].started;

      if (failed)
	{
	  fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started);
	}
    }

  assert(!failed);

  /*
   * Check any results here. Set "failed" and only print ouput on failure.
   */
  for (i = 1; i <= NUMTHREADS; i++)
    {
      /* ... */
    }

  assert(!failed);

  /*
   * Success.
   */
  return 0;
}


text:
'use strict'

module.exports = function (adapter) {
  return require(`./${adapter}`)
}


text:
TFiOSAppBrandingTemplate
========================


text:
layout: organization
category: local

title: Wishing Well Garden
impact_area: Environment
keywords:
location_services:
location_offices:
website:

description:
mission: |
  Community Garden in the Bronx

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: Bronx
state: NY
address: |
  888 James A. Polite Avenue
  Bronx NY 10459
lat: 40.824643
lng: -73.892923
phone: 718-617-4626
ext:
fax:
email:
preferred_contact:
contact_person_intro:
---


text:
<template>
  <require from="components/footer-main/footer-main"></require>
  <require from="components/svg-icon/svg-icon"></require>

        <svg-icon icon-id="sad"></svg-icon>

Oh no! This shouldn't have happened.

The page you are trying to access doesn't exist. May we kindly ask you to check the URL for typos or to send us an angry message complaining about the bug?

</template>


text:
package org.apache.harmony.security.tests.java.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;

public class Provider2Test extends junit.framework.TestCase {

	class TestProvider extends Provider {
		TestProvider(String name, double version, String info) {
			super(name, version, info);
		}
	}

    class MyEntry implements java.util.Map.Entry {
         public Object getKey() {
             return null;
         }

         public Object getValue() {
             return null;
         }

         public Object setValue(Object value) {
             return null;
         }
    }

	TestProvider provTest = new TestProvider("provTest", 1.2,
			"contains nothings, purely for testing the class");

	/**
	 * @tests java.security.Provider#entrySet()
	 */
	public void test_entrySet() {
		// test method of java.security.provider.entrySet
		provTest.put("test.prop", "this is a test property");
		try {
            //make it compilable on 1.5
			provTest.entrySet().add(new MyEntry());
			fail("was able to modify the entrySet");
		} catch (UnsupportedOperationException e) {
			// expected
		}
	}

	/**
	 * @tests java.security.Provider#getInfo()
	 */
	public void test_getInfo() {
		// test method of java.security.provider.getInfo
		assertEquals("the information of the provider is not stored properly",
				"contains nothings, purely for testing the class", provTest
						.getInfo());
	}

	/**
	 * @tests java.security.Provider#getName()
	 */
	public void test_getName() {
		// test method of java.security.provider.getName
		assertEquals("the name of the provider is not stored properly",
				"provTest", provTest.getName());
	}

	/**
	 * @tests java.security.Provider#getVersion()
	 */
	public void test_getVersion() {
		// test method of java.security.provider.getVersion
		assertEquals("the version of the provider is not stored properly",
				1.2, provTest.getVersion(), 0);
	}

	/**
	 * @tests java.security.Provider#keySet()
	 */
	public void test_keySet() {
		// test method of java.security.provider.keySet
		provTest.put("test.prop", "this is a test property");
		try {
			provTest.keySet().add("another property key");
			fail("was able to modify the keySet");
		} catch (UnsupportedOperationException e) {
			// expected
		}
	}

	/**
	 * @tests java.security.Provider#values()
	 */
	public void test_values() {
		// test method of java.security.provider.values
		provTest.put("test.prop", "this is a test property");
		try {
			provTest.values().add("another property value");
			fail("was able to modify the values collection");
		} catch (UnsupportedOperationException e) {
			// expected
		}
	}

    /**
     * @tests java.security.Provider#toString()
     */
    public void test_toString() {
        // Regression for HARMONY-3734
        assertEquals("provTest version 1.2", provTest.toString());
    }

    // Regression Test for Provider.Service.getAlias(), which is an package
    // private method but will lead to NPE thrown at
    // Secure.SecurityDorr.getAliases
    public void test_getAlias() throws Exception {
        MockProvider mockProvider = new MockProvider("MOCKNAME", 1.0,
                "MOCKINFO");
        Provider.Service service = new Provider.Service(mockProvider,
                "MOCKTYPE", "MOCKALGORITHM", "TESTCLASSNAME", null, null);
        mockProvider.putService(service);
        Security.addProvider(mockProvider);
        try {
            MessageDigest messageDigest = MessageDigest
                    .getInstance("NOTEXISTS");
        }

        catch (NoSuchAlgorithmException e) {
            // expected
        } finally {
            Security.removeProvider("MOCKNAME");
        }
    }

    public static class MockProvider extends Provider {

        private static final long serialVersionUID = 1L;

        public MockProvider(String name, double version, String info) {
            super(name, version, info);

        }

        public void putService(Provider.Service service) {
            super.putService(service);
        }

        public void removeService(Provider.Service service) {
            super.removeService(service);
        }
    }
}


text:
package org.asynchttpclient.websocket;

import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.websocket.WebSocket;
import org.asynchttpclient.websocket.WebSocketCloseCodeReasonListener;
import org.asynchttpclient.websocket.WebSocketListener;
import org.asynchttpclient.websocket.WebSocketUpgradeHandler;
import org.testng.annotations.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

public abstract class CloseCodeReasonMessageTest extends TextMessageTest {

    @Test(timeOut = 60000)
    public void onCloseWithCode() throws Throwable {
        AsyncHttpClient c = getAsyncHttpClient(null);
        try {
            final CountDownLatch latch = new CountDownLatch(1);
            final AtomicReference<String> text = new AtomicReference<String>("");

            WebSocket websocket = c.prepareGet(getTargetUrl()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new Listener(latch, text)).build()).get();

            websocket.close();

            latch.await();
            assertTrue(text.get().startsWith("1000"));
        } finally {
            c.close();
        }
    }

    @Test(timeOut = 60000)
    public void onCloseWithCodeServerClose() throws Throwable {
        AsyncHttpClient c = getAsyncHttpClient(null);
        try {
            final CountDownLatch latch = new CountDownLatch(1);
            final AtomicReference<String> text = new AtomicReference<String>("");

            c.prepareGet(getTargetUrl()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new Listener(latch, text)).build()).get();

            latch.await();
            final String[] parts = text.get().split(" ");
            assertEquals(parts.length, 5);
            assertEquals(parts[0], "1000-Idle");
            assertEquals(parts[1], "for");
            assertTrue(Integer.parseInt(parts[2].substring(0, parts[2].indexOf('m'))) > 10000);
            assertEquals(parts[3], ">");
            assertEquals(parts[4], "10000ms");
        } finally {
            c.close();
        }
    }

    public final static class Listener implements WebSocketListener,
            WebSocketCloseCodeReasonListener {

        final CountDownLatch latch;
        final AtomicReference<String> text;

        public Listener(CountDownLatch latch, AtomicReference<String> text) {
            this.latch = latch;
            this.text = text;
        }

        // @Override
        public void onOpen(WebSocket websocket) {
        }

        // @Override
        public void onClose(WebSocket websocket) {
        }

        public void onClose(WebSocket websocket, int code, String reason) {
            text.set(code + "-" + reason);
            latch.countDown();
        }

        // @Override
        public void onError(Throwable t) {
            t.printStackTrace();
            latch.countDown();
        }
    }
}


text:
<?php
//modif Francois: redirect to resources directly
switch($_REQUEST['to']) {

case 'videohelp':
	$redir_url = 'http://go.centresis.org/videohelp/index.php';
	break;

case 'forums':
	$redir_url = 'http://centresis.org/forums/index.php';
	break;

case 'translate':
	$redir_url = 'http://translate.centresis.org/';
	break;
}
echo '<form name="RosarioArgs" method="post"  action="'.$redir_url.'">';
?>
</form>

You must have JavaScript enabled to use the RosarioSIS Online Resources.


text:
- [[Actions, Controllers and Results | ScalaActions]]
- [[HTTP routing | ScalaRouting]]
- [[Manipulating results | ScalaResults]]
- [[Session and Flash scopes | ScalaSessionFlash]]
- [[Body parsers | ScalaBodyParsers]]
- [[Actions composition | ScalaActionsComposition]]
- [[Content negotiation | ScalaContentNegotiation]]

### Main concepts

- [[HTTP programming | ScalaActions]]
- [[Asynchronous HTTP programming | ScalaAsync]]
- [[The template engine | ScalaTemplates]]
- [[HTTP form submission and validation | ScalaForms]]
- [[Working with JSON | ScalaJson]]
- [[Working with XML | ScalaXmlRequests]]
- [[Handling file upload | ScalaFileUpload]]
- [[Accessing an SQL database | ScalaDatabase]]
- [[Using the Cache | ScalaCache]]
- [[Calling WebServices | ScalaWS]]
- [[Integrating with Akka | ScalaAkka]]
- [[Internationalization | ScalaI18N]]
- [[The application Global object | ScalaGlobal]]
- [[Testing your application | ScalaTest]]

### Advanced topics

- [[Handling data streams reactively | Iteratees]]

### Tutorials

- [[Your first application | ScalaTodoList]]


text:
prefix="${HOME}/libs"
user="justinmooser"
name=$1

createRepoArgs={\"name\":\"${name}\"}

mkdir ${prefix}/$name

rm -rf ${HOME}/libs/lib-base
git clone https://github.com/webinverters/lib-base.git

# TODO: pull from lib-base first just incase there are updates.
cd ${prefix}/lib-base
curl -u ${user} https://api.github.com/orgs/webinverters/repos -d $createRepoArgs
git remote add ${name} git@github-${user}:webinverters/${name}.git
git push ${name} master

cd ${prefix}/$name
git clone git@github-${user}:webinverters/${name}.git .


text:
using namespace std;

class Window {

private:

    static Scene *scene; // current scene
    static int sceneId; // current scene id
    static int width; // window width
    static int height; // window height
    static int mode; // window mode

    Window(){}

public:

    static Scene *getScene(); // get scene

    static void setScene(Scene *scene); // set scene

    static int getSceneId(); // get sceneId

    static void setSceneId(int sceneId); // set sceneId

    static int getWidth(); // get window width

    static void setWidth(int width); // set window width

    static int getHeight(); // get window height

    static void setHeight(int height); // set window height

    static void getMode(int mode); // get window mode

    static void setMode(int mode); // set window mode

    static void changeMode(); // change window mode

    static void display(); // display window

    static void keyboard(unsigned char key, int x, int y); // keyboard window functions

    static void reshape(int w, int h); // reshape window

    static void init(); // window init setup

};

#endif //LABYRINTH_OPENGL_CPP_WINDOW_H


text:
package org.greencheek.related.indexing.web.bootstrap;

import org.greencheek.related.indexing.requestprocessorfactory.IndexRequestProcessorFactory;
import org.greencheek.related.util.config.Configuration;

/**
 *
 */
public interface ApplicationCtx {
    public IndexRequestProcessorFactory getIndexRequestProcessorFactory();
    public Configuration getConfiguration();
}


text:
package com.umeng.comm.ui.presenter.impl;

import java.util.concurrent.atomic.AtomicBoolean;

import android.text.TextUtils;

import com.umeng.comm.core.listeners.Listeners.SimpleFetchListener;
import com.umeng.comm.core.nets.responses.LikesResponse;
import com.umeng.comm.core.nets.uitls.NetworkUtils;
import com.umeng.comm.ui.mvpview.MvpLikeUserView;
import com.umeng.comm.ui.presenter.BasePresenter;

public class LikeUserActivityPresenter extends BasePresenter {

    MvpLikeUserView mView;
    String mFeedId;
    String mNextPageUrl;
    volatile AtomicBoolean mFromRefresh = new AtomicBoolean(true); //【此时在下拉刷新,然后立即滑动到底部加载更多可能出现问题】

    public LikeUserActivityPresenter(MvpLikeUserView view, String feedId) {
        mView = view;
        mFeedId = feedId;
    }

    public void loadLikeUserFromServer() {
        mFromRefresh.set(true); // 刷新不需要更新下一页地址
        mCommunitySDK.fetchFeedLikes(mFeedId, mFetchListener);
    }

    public void loadMoreLikeUser() {
        if (TextUtils.isEmpty(mNextPageUrl)) {
            mView.onRefreshEnd();
            return;
        }
        mFromRefresh.set(false);// 加载更多需要更新下一页地址
        mCommunitySDK.fetchNextPageData(mNextPageUrl, LikesResponse.class, mFetchListener);
    }

    public void setNextPageUrl(String url) {
        mNextPageUrl = url ;
    }

    private SimpleFetchListener<LikesResponse> mFetchListener = new SimpleFetchListener<LikesResponse>() {

        @Override
        public void onComplete(LikesResponse response) {
            if ( NetworkUtils.handleResponseAll(response) ) {
                return ;
            }
            if (!mFromRefresh.get()) {
                mNextPageUrl = response.nextPageUrl;
            }
            if (NetworkUtils.handleResponseAll(response)) {
                return;
            }
            mView.fetchLikeUsers(response.result);
            mView.onRefreshEnd();
        }
    };
}


text:
package com.castleby.presenter;

import javax.inject.Inject;

import com.castleby.event.LoginEvent;
import com.castleby.event.LoginEventHandler;
import com.castleby.shared.eventbus.EventBus;
import com.google.gwt.user.client.ui.DialogBox;

public class TestModulePresenter {

    private EventBus eventBus;

    @Inject
    public TestModulePresenter(EventBus eventBus) {
        super();
        this.eventBus = eventBus;
        final DialogBox dialogBox = new DialogBox();
        eventBus.addHandler(LoginEvent.TYPE, new LoginEventHandler() {

            @Override
            public void onEvent(LoginEvent event) {
                dialogBox.setText("Remote Procedure Call");
//                serverResponseLabel.removeStyleName("serverResponseLabelError");
//              serverResponseLabel.setHTML(result);
                dialogBox.center();
//                closeButton.setFocus(true);
            }
        });
    }
}


text:
package com.amazonaws.services.managedblockchain.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.managedblockchain.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * Member JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MemberJsonUnmarshaller implements Unmarshaller<Member, JsonUnmarshallerContext> {

    public Member unmarshall(JsonUnmarshallerContext context) throws Exception {
        Member member = new Member();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("NetworkId", targetDepth)) {
                    context.nextToken();
                    member.setNetworkId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Id", targetDepth)) {
                    context.nextToken();
                    member.setId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Name", targetDepth)) {
                    context.nextToken();
                    member.setName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Description", targetDepth)) {
                    context.nextToken();
                    member.setDescription(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("FrameworkAttributes", targetDepth)) {
                    context.nextToken();
                    member.setFrameworkAttributes(MemberFrameworkAttributesJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("Status", targetDepth)) {
                    context.nextToken();
                    member.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("CreationDate", targetDepth)) {
                    context.nextToken();
                    member.setCreationDate(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return member;
    }

    private static MemberJsonUnmarshaller instance;

    public static MemberJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new MemberJsonUnmarshaller();
        return instance;
    }
}


text:
namespace PhimHang.Models
{
    using System;
    using System.Collections.Generic;

    public partial class StatusWindow
    {
        public long Id { get; set; }
        public string CtrId { get; set; }
        public string WindowName { get; set; }
        public string LeftPosition { get; set; }
        public string TopPosition { get; set; }
        public string UserName { get; set; }
        public string KeyWindowName { get; set; }
    }
}


text:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {
    hello: path.resolve(__dirname, 'src/js/hello.jsx'),
    tick: path.resolve(__dirname, 'src/js/tick.jsx'),
    comment: path.resolve(__dirname, 'src/js/comment.jsx'),
    toggle: path.resolve(__dirname, 'src/js/toggle.jsx'),
    loginout: path.resolve(__dirname, 'src/js/loginout.jsx'),
    list: path.resolve(__dirname, 'src/js/list.jsx'),
    form: path.resolve(__dirname, 'src/js/form.jsx'),
    select: path.resolve(__dirname, 'src/js/select.jsx'),
    input: path.resolve(__dirname, 'src/js/input.jsx'),
    temperature: path.resolve(__dirname, 'src/js/temperature.jsx'),
    commerce: path.resolve(__dirname, 'src/js/commerce.jsx'),
    react: ['react', 'react-dom']
  },
  module: {
    rules: [{
      test: /\.(jsx|js)$/,
      exclude: /(node_modules)/,
      use: ['babel-loader']
    },
    {
      test: /\.css$/,
      include: path.resolve(__dirname, 'src/css'),
      use: ExtractTextWebpackPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader'
      })
    }]
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].[chunkhash:7].js'
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'react',
      minChunks: Infinity
    }),
    new ExtractTextWebpackPlugin({
      filename: 'css/[name].[chunkhash:7].css'
    }),
    new HtmlWebpackPlugin({
      chunks: ['hello', 'react'],
      filename: 'html/hello.html',
      title: 'HelloReact',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['tick', 'react'],
      filename: 'html/tick.html',
      title: 'Tick',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['comment', 'react'],
      filename: 'html/comment.html',
      title: 'Comment',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['toggle', 'react'],
      filename: 'html/toggle.html',
      title: 'Toggle',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['loginout', 'react'],
      filename: 'html/loginout.html',
      title: 'Loginout',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['list', 'react'],
      filename: 'html/list.html',
      title: 'List',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['form', 'react'],
      filename: 'html/form.html',
      title: 'Form',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['select', 'react'],
      filename: 'html/select.html',
      title: 'Select',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['input', 'react'],
      filename: 'html/input.html',
      title: 'Input',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['temperature', 'react'],
      filename: 'html/temperature.html',
      title: 'Temperature',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    }),
    new HtmlWebpackPlugin({
      chunks: ['commerce', 'react'],
      filename: 'html/commerce.html',
      title: 'Commerce',
      minify: {
        collapseWhitespace: false,
        removeComments: true
      },
      template: path.resolve(__dirname, 'src/html/base.html')
    })
  ]
};


text:
"""

# skchem.filters.simple

Simple filters for compounds.

"""

from collections import Counter

import numpy as np
import pandas as pd

from ..resource import ORGANIC, PERIODIC_TABLE
from .base import Filter

class ElementFilter(Filter):

    """ Filter by elements.

        Examples:

            Basic usage on molecules:

            >>> import skchem
            >>> hal_f = skchem.filters.ElementFilter(['F', 'Cl', 'Br', 'I'])

            Molecules with one of the atoms transform to `True`.

            >>> m1 = skchem.Mol.from_smiles('ClC(Cl)Cl', name='chloroform')
            >>> hal_f.transform(m1)
            True

            Molecules with none of the atoms transform to `False`.

            >>> m2 = skchem.Mol.from_smiles('CC', name='ethane')
            >>> hal_f.transform(m2)
            False

            Can see the atom breakdown by passing `agg` == `False`:
            >>> hal_f.transform(m1, agg=False)
            has_element
            F     0
            Cl    3
            Br    0
            I     0
            Name: ElementFilter, dtype: int64

            Can transform series.

            >>> ms = [m1, m2]
            >>> hal_f.transform(ms)
            chloroform     True
            ethane        False
            dtype: bool

            >>> hal_f.transform(ms, agg=False)
            has_element  F  Cl  Br  I
            chloroform   0   3   0  0
            ethane       0   0   0  0

            Can also filter series:

            >>> hal_f.filter(ms)
            chloroform    <Mol: ClC(Cl)Cl>
            Name: structure, dtype: object

            >>> hal_f.filter(ms, neg=True)
            ethane    <Mol: CC>
            Name: structure, dtype: object

        """
    def __init__(self, elements=None, as_bits=False, agg='any', n_jobs=1,
                 verbose=True):

        """ Initialize an ElementFilter object.

        Args:
            elements (list[str]):
                A list of elements to filter with.  If an element not in the
                list is found in a molecule, return False, else return True.

            as_bits (bool):
                Whether to return integer counts or booleans for atoms if mode
                is `count`.

            agg (str or callable):
                The callable to combine rows to produce the predicate.

            n_jobs (int):
                How many processes to use.

            verbose(bool):
                Whether to output a progress bar.
        """

        self._elements = None

        self.elements = elements
        self.as_bits = as_bits
        super(ElementFilter, self).__init__(agg=agg, n_jobs=n_jobs,
                                            verbose=verbose)

    @property
    def elements(self):
        return self._elements

    @elements.setter
    def elements(self, val):
        if val is None:
            self._elements = PERIODIC_TABLE.symbol.tolist()
        else:
            self._elements = val

    @property
    def columns(self):
        return pd.Index(self.elements, name='has_element')

    def _transform_mol(self, mol):

        counter = Counter(atom.symbol for atom in mol.atoms)
        res = pd.Series(counter)

        res = res[self.elements].fillna(0).astype(int)

        if self.as_bits:
            res = (res > 0).astype(np.uint8)

        return res

class OrganicFilter(ElementFilter):

    """ Whether a molecule is organic.

        For the purpose of this function, an organic molecule is defined as
        having atoms with elements only in the set H, B, C, N, O, F, P, S, Cl,
        Br, I.

        Examples:
                Basic usage as a function on molecules:
                >>> import skchem
                >>> of = skchem.filters.OrganicFilter()
                >>> benzene = skchem.Mol.from_smiles('c1ccccc1', name='benzene')

                >>> of.transform(benzene)
                True

                >>> ferrocene = skchem.Mol.from_smiles('[cH-]1cccc1.[cH-]1cccc1.[Fe+2]',
                ...                                    name='ferrocene')
                >>> of.transform(ferrocene)
                False

                More useful on collections:

                >>> sa = skchem.Mol.from_smiles('CC(=O)[O-].[Na+]', name='sodium acetate')
                >>> norbornane = skchem.Mol.from_smiles('C12CCC(C2)CC1', name='norbornane')

                >>> data = [benzene, ferrocene, norbornane, sa]
                >>> of.transform(data)
                benzene            True
                ferrocene         False
                norbornane         True
                sodium acetate    False
                dtype: bool

                >>> of.filter(data)
                benzene          <Mol: c1ccccc1>
                norbornane    <Mol: C1CC2CCC1C2>
                Name: structure, dtype: object

                >>> of.filter(data, neg=True)
                ferrocene         <Mol: [Fe+2].c1cc[cH-]c1.c1cc[cH-]c1>
                sodium acetate                  <Mol: CC(=O)[O-].[Na+]>
                Name: structure, dtype: object
        """

    def __init__(self, n_jobs=1, verbose=True):

        """ Initialize an Organic Filter object.

        Args:
            n_jobs (int):
                The number of processes to run the filter in.
            verbose (bool):
                Whether to output a progress bar.
        """

        super(OrganicFilter, self).__init__(elements=None, agg='not any',
                                            n_jobs=n_jobs, verbose=verbose)
        self.elements = [element for element in self.elements
                         if element not in ORGANIC]

def n_atoms(mol, above=2, below=75, include_hydrogens=False):

    """ Whether the number of atoms in a molecule falls in a defined interval.

    ``above <= n_atoms < below``

    Args:
        mol: (skchem.Mol):
            The molecule to be tested.
        above (int):
            The lower threshold number of atoms (exclusive).
        below (int):
            The higher threshold number of atoms (inclusive).
        include_hydrogens (bool):
            Whether to consider hydrogens in the atom count.

    Returns:
        bool:
            Whether the molecule has more atoms than the threshold.

    Examples:

        Basic usage as a function on molecules:

        >>> import skchem
        >>> m = skchem.Mol.from_smiles('c1ccccc1') # benzene has 6 atoms.

        Lower threshold:

        >>> skchem.filters.n_atoms(m, above=3)
        True
        >>> skchem.filters.n_atoms(m, above=8)
        False

        Higher threshold:

        >>> skchem.filters.n_atoms(m, below=8)
        True
        >>> skchem.filters.n_atoms(m, below=3)
        False

        Bounds work like Python slices - inclusive lower, exclusive upper:

        >>> skchem.filters.n_atoms(m, above=6)
        True
        >>> skchem.filters.n_atoms(m, below=6)
        False

        Both can be used at once:

        >>> skchem.filters.n_atoms(m, above=3, below=8)
        True

        Can include hydrogens:

        >>> skchem.filters.n_atoms(m, above=3, below=8, include_hydrogens=True)
        False
        >>> skchem.filters.n_atoms(m, above=9, below=14, include_hydrogens=True)
        True
    """

    assert above < below, 'Interval {} < a < {} undefined.'.format(above,
                                                                   below)

    n_a = len(mol.atoms)
    if include_hydrogens:
        n_a += sum(atom.GetNumImplicitHs() + atom.GetNumExplicitHs()
                   for atom in mol.atoms)

    return above <= n_a < below

class AtomNumberFilter(Filter):

    """Filter whether the number of atoms in a Mol falls in a defined interval.

    `above <= n_atoms < below`

    Examples:
        >>> import skchem

        >>> data = [
        ...         skchem.Mol.from_smiles('CC', name='ethane'),
        ...         skchem.Mol.from_smiles('CCCC', name='butane'),
        ...         skchem.Mol.from_smiles('NC(C)C(=O)O', name='alanine'),
        ...         skchem.Mol.from_smiles('C12C=CC(C=C2)C=C1', name='barrelene')
        ... ]

        >>> af = skchem.filters.AtomNumberFilter(above=3, below=7)

        >>> af.transform(data)
        ethane       False
        butane        True
        alanine       True
        barrelene    False
        Name: num_atoms_in_range, dtype: bool

        >>> af.filter(data)
        butane            <Mol: CCCC>
        alanine    <Mol: CC(N)C(=O)O>
        Name: structure, dtype: object

        >>> af = skchem.filters.AtomNumberFilter(above=5, below=15, include_hydrogens=True)

        >>> af.transform(data)
        ethane        True
        butane        True
        alanine       True
        barrelene    False
        Name: num_atoms_in_range, dtype: bool
    """

    def __init__(self, above=3, below=60, include_hydrogens=False, n_jobs=1,
                 verbose=True):

        """ Initialize an AtomNumberFilter object.

        Args:
            mol: (skchem.Mol):
                The molecule to be tested.
            above (int):
                The lower threshold on the mass.
            below (int):
                The higher threshold on the mass.
            n_jobs (int):
                The number of processes to run the filter in.
            verbose (bool):
                Whether to output a progress bar.
        """

        assert above < below, 'Interval {} < a < {} undefined.'.format(above,
                                                                       below)
        self.above = above
        self.below = below
        self.include_hydrogens = include_hydrogens

        super(AtomNumberFilter, self).__init__(agg='any', n_jobs=n_jobs,
                                               verbose=verbose)

    def _transform_mol(self, mol):
        return n_atoms(mol, above=self.above, below=self.below,
                       include_hydrogens=self.include_hydrogens)

    @property
    def columns(self):
        return pd.Index(['num_atoms_in_range'])

def mass(mol, above=10, below=900):

    """ Whether a the molecular weight of a molecule is lower than a threshold.

    `above <= mass < below`

    Args:
        mol: (skchem.Mol):
            The molecule to be tested.
        above (float):
            The lower threshold on the mass.
            Defaults to None.
        below (float):
            The higher threshold on the mass.
            Defaults to None.

    Returns:
        bool:
            Whether the mass of the molecule is lower than the threshold.

    Examples:
        Basic usage as a function on molecules:

        >>> import skchem
        >>> m = skchem.Mol.from_smiles('c1ccccc1') # benzene has M_r = 78.
        >>> skchem.filters.mass(m, above=70)
        True
        >>> skchem.filters.mass(m, above=80)
        False
        >>> skchem.filters.mass(m, below=80)
        True
        >>> skchem.filters.mass(m, below=70)
        False
        >>> skchem.filters.mass(m, above=70, below=80)
        True
    """

    return above <= mol.mass < below

class MassFilter(Filter):

    """ Filter whether the molecular weight of a molecule is outside a range.

    `above <= mass < below`

    Examples:

        >>> import skchem

        >>> data = [
        ...         skchem.Mol.from_smiles('CC', name='ethane'),
        ...         skchem.Mol.from_smiles('CCCC', name='butane'),
        ...         skchem.Mol.from_smiles('NC(C)C(=O)O', name='alanine'),
        ...         skchem.Mol.from_smiles('C12C=CC(C=C2)C=C1', name='barrelene')
        ... ]

        >>> mf = skchem.filters.MassFilter(above=31, below=100)

        >>> mf.transform(data)
        ethane       False
        butane        True
        alanine       True
        barrelene    False
        Name: mass_in_range, dtype: bool

        >>> mf.filter(data)
        butane            <Mol: CCCC>
        alanine    <Mol: CC(N)C(=O)O>
        Name: structure, dtype: object

    """

    def __init__(self, above=3, below=900, n_jobs=1, verbose=True):

        """ Initialize a MassFilter object.

        Args:
            mol: (skchem.Mol):
                The molecule to be tested.
            above (float):
                The lower threshold on the mass.
            below (float):
                The higher threshold on the mass.
            n_jobs (int):
                The number of processes to run the filter in.
            verbose (bool):
                Whether to output a progress bar.
        """

        assert above < below, 'Interval {} < a < {} undefined.'.format(above,
                                                                       below)
        self.above = above
        self.below = below

        super(MassFilter, self).__init__(agg='any', n_jobs=n_jobs,
                                         verbose=verbose)

    def _transform_mol(self, mol):
        return mass(mol, above=self.above, below=self.below)

    @property
    def columns(self):
        return pd.Index(['mass_in_range'])


text:
package main

import (
  "fmt"
  "os"
  "github.com/satori/go.uuid"
)

func main() {
  scientifi_name := os.Args[1]
  gn_name_space := uuid.NewV5(uuid.NamespaceDNS, "globalnames.org")
  gn_uuid := uuid.NewV5(gn_name_space, scientifi_name)
  fmt.Println("Scientific name: " + scientifi_name)
  fmt.Printf("GlobalNames UUID: %s\n", gn_uuid)
}


text:
<?php

// @todo default config must be set here
use phmLabs\Components\Annovent\Event\Event;
use LiveTest\MandatoryParameterException;
use LiveTest\Event\Dispatcher;
use LiveTest\Packages\Runner\Listeners\Help;

include_once __DIR__.'/version.php';
include_once __DIR__.'/bootstrap.php';

$exitStatusCode = 1;

try
{
  $converter = new Base\Cli\ArgumentConverter($_SERVER['argv'], '--');

  // @todo this should be done in another class/function
  if ($converter->hasArgument('bootstrap'))
  {
    $bootstrapFile = $converter->getArgument('bootstrap');

    if (file_exists(getcwd() . DIRECTORY_SEPARATOR . $bootstrapFile) && $bootstrapFile != '')
    {
      include_once $converter->getArgument('bootstrap');
    }
    else
    {
      echo '  Bootstrap file (' . $converter->getArgument('bootstrap') . ') not found.' . "\n\n";
    }
  }

  $dispatcher = new LiveTest\Event\Dispatcher();

  $runner = new LiveTest\Cli\Runner($converter->getArguments(), $dispatcher);
  if ($runner->isRunAllowed())
  {
    $runner->run();
  }
  $exitStatusCode = 0;
}
catch ( Livetest\ConfigurationException $e )
{
  $dispatcher->simpleNotify('LiveTest.Configuration.Exception', array ('exception' => $e ));
}
catch ( Exception $e )
{
  $event = new phmLabs\Components\Annovent\Event\Event('LiveTest.Runner.Error', array ('exception' => $e ));
  $dispatcher->notify($event);
  if (!$event->isProcessed())
  {
    echo 'An error occured: ' . $e->getMessage() . '(' . get_class($e) . ')';
  }
}
echo "\n\n";
exit($exitStatusCode);


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.glaf.base.modules.sys.model">
	<class name="SysRole" table="sys_role" dynamic-update="true"
		dynamic-insert="true" lazy="true">

		<id name="id" type="long" unsaved-value="0">
			<column name="id" not-null="true" />
			<generator class="native" />
		</id>

		<property name="name" type="string" column="name" />
		<property name="desc" type="string" column="roleDesc" />
		<property name="code" type="string" column="code" />
		<property name="sort" type="integer" column="sort" />
	</class>
</hibernate-mapping>


text:
FROM amancevice/pandas:0.18.1-python3
MAINTAINER smallweirdnum@gmail.com

# Install
ENV CARAVEL_VERSION 0.13.1
RUN apk add --no-cache \
        curl \
        libffi-dev \
        cyrus-sasl-dev \
        mariadb-dev \
        postgresql-dev && \
    pip3 install \
        caravel==$CARAVEL_VERSION \
        mysqlclient==1.3.7 \
        psycopg2==2.6.1 \
        redis==2.10.5 \
        sqlalchemy-redshift==0.5.0

# Default config
ENV LANG=C.UTF-8 \
    LC_ALL=C.UTF-8 \
    PATH=$PATH:/home/caravel/.bin \
    PYTHONPATH=/home/caravel/caravel_config.py:$PYTHONPATH

# Run as caravel user
WORKDIR /home/caravel
COPY caravel .
RUN addgroup caravel && \
    adduser -h /home/caravel -G caravel -D caravel && \
    mkdir /home/caravel/db && \
    chown -R caravel:caravel /home/caravel
USER caravel

# Deploy
EXPOSE 8088
HEALTHCHECK CMD ["curl", "-f", "http://localhost:8088/health"]
ENTRYPOINT ["caravel"]
CMD ["runserver"]


text:
import $ from "jquery";
import TemplateManager from "./TemplateManager";
import PowerShellManager from "./PowerShellManager";
import FormValidator from "./FormValidator";
import UI from "./UI";
import Strings from "./Strings";

export default {
    InitForm: function() {
        UI.RegisterEvent(UI.Document(), "ready", function() {
            UI.HideElement("questionErrorFlag");
            UI.HideElement("configErrorFlag");
            UI.HideElement("globalValidationMessage");
            UI.HideElement("QuestionnaireEditor");
        });
    },
    ValidateForm: function(submitAfterValidate) {
        var formValid = true;
        if (FormValidator.ValidateConfigData() === false) {
            formValid = false;
        }
        if (FormValidator.ValidateAllNodeData() === false) {
            formValid = false;
        }

        var questionsValid = true;
        DscStudio.CurrentTemplate.questions.forEach(function(question) {
            var valid = FormValidator.ValidateQuestion(question);
            if (valid === false) {
                questionsValid = false;
            }
        });

        if (questionsValid === true) {
            UI.HideElement("questionErrorFlag");
        } else {
            UI.ShowElement("questionErrorFlag");
            formValid = false;
        }

        if (submitAfterValidate === true && formValid === true) {
            TemplateManager.StoreQuestionResponses();
            TemplateManager.StoreLCMSettings();
            PowerShellManager.UpdateCurrentScript();
            UI.SwitchView(UI.Views.Output);
        }

        return formValid;
    },
    ValidateQuestion: function(question) {
        var questionValid = true;
        if (UI.IsElementVisible(`#question-${question.id}`) === false) {
            return true;
        }
        switch (question.type) {
            case "text":
                var textValue = UI.GetValue(`#question-${question.id}-value`);
                if (textValue === null || textValue === "") {
                    questionValid = false;
                }
                break;
            case "number":
                var numberValue = UI.GetValue(`#question-${question.id}-value`);
                if (numberValue === null || numberValue === "" || isNaN(numberValue)) {
                    questionValid = false;
                } else {
                    if (question.minValue !== null && numberValue < question.minValue) {
                        questionValid = false;
                    } else if(question.maxValue !== null && numberValue > question.maxValue) {
                        questionValid = false;
                    }
                }
                break;
            case "filepath":
                var filevalue = UI.GetValue(`#question-${question.id}-value`);
                if (filevalue === null || filevalue === "") {
                    questionValid = false;
                } else {
                    if (filevalue.match(/^(?:[\w]\:|\\)(\\[a-zA-Z_\-\s0-9\.]+)+\\*$/g) === null) {
                        questionValid = false;
                    }
                }
                break;
            case "regex":
                var regexvalue = UI.GetValue(`#question-${question.id}-value`);
                if (regexvalue === null || regexvalue === "") {
                    questionValid = false;
                } else {
                    // eval is required here to dynamically pull in the regex.
                    // The ignore comment has been added to pass the linting test
                    if (regexvalue.match(eval(question.pattern)) === null) { // jshint ignore:line
                        questionValid = false;
                    }
                }
                break;
            case "textarray":
                var hasItems = false;
                UI.GetUIElements(`#question-${question.id}-value option`).each(function(item) {
                    hasItems = true;
                });
                if (hasItems === false) {
                    questionValid = false;
                }
                break;
            case "complextype":
                var complextypevalue = UI.GetValue(`#question-${question.id}-value`);
                var object = JSON.parse(complextypevalue);
                if (object.length === 0) {
                    questionValid = false;
                }
                break;
            case "boolean":
            case "choice":
                // no specific validation is required for these types
                break;
            default:
                UI.SendAlert(Strings.ErrorQuestionTypeNotSupported, [question.type]);
                questionValid = false;
                break;
        }
        if (questionValid) {
            UI.HideElement(`question-${question.id}-error`);
        } else {
            UI.ShowElement(`question-${question.id}-error`);
        }
        return questionValid;
    },
    EnableQuestionValidation: function() {
        UI.RegisterEvent("input[id^='question-']", "focusout", function() {
            var questionId = this.id.replace("question-", "").replace("-value","").replace("-newitem","");
            var question = DscStudio.CurrentTemplate.questions.filter(function(item) {
                return item.id == questionId;
            })[0];
            FormValidator.ValidateQuestion(question);
        });
    },
    ValidateConfigData: function() {
        var configValid = true;

        if (DscStudio.CurrentTemplate.configDataSettings.certificateDetails === undefined || DscStudio.CurrentTemplate.configDataSettings.certificateDetails === true) {
            var certPath = UI.GetValue("#CertPath");
            if (certPath === null || certPath === "" || certPath.match(/^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.(cer)$/g) === null) {
                UI.ShowElement("CertPath-Error");
                configValid = false;
            } else {
                UI.HideElement("CertPath-Error");
            }

            var certThumbprint = UI.GetValue("#CertThumbprint");
            if (certThumbprint === null || certThumbprint === "" || certThumbprint.match(/^[A-Fa-f0-9]{40}/g) === null) {
                UI.ShowElement("CertThumbprint-Error");
                configValid = false;
            } else {
                UI.HideElement("CertThumbprint-Error");
            }
        }

        var configModeMins = UI.GetValue("#ConfigModeMins");
        if (configModeMins === null || configModeMins === "" || isNaN(configModeMins)) {
            UI.ShowElement("ConfigModeMins-Error");
            configValid = false;
        } else {
            if (configModeMins < 15) {
                UI.ShowElement("ConfigModeMins-Error");
                configValid = false;
            } else {
                UI.HideElement("ConfigModeMins-Error");
            }
        }

        if (configValid === true) {
            UI.HideElement("configErrorFlag");
        } else {
            UI.ShowElement("configErrorFlag");
        }
        return configValid;
    },
    ValidateAllNodeData: function() {
        var minCount = 1;
        var configValid = true;
        if (DscStudio.CurrentTemplate.configDataSettings.minNodeCount !== undefined) {
            minCount = DscStudio.CurrentTemplate.configDataSettings.minNodeCount;
        }

        UI.HideElement("minNodeCountMessage");
        UI.HideElement("nodeOptionsNotValidMessage");
        UI.EmptyObject("nodeOptionsNotValidContent");

        if (DscStudio.Nodes.length < minCount) {
            UI.ShowElement("minNodeCountMessage");
            UI.SetText("#minNodeCountNumber", minCount);
            return false;
        }
        if (DscStudio.CurrentTemplate.configDataSettings.maxNodeCount !== undefined && DscStudio.Nodes.length > DscStudio.CurrentTemplate.configDataSettings.maxNodeCount) {
            return false;
        }

        var result = true;
        DscStudio.CurrentTemplate.configDataSettings.nodeSettings.forEach(function(nodeSetting) {
            if (nodeSetting.minOccurences !== null) {
                var occurences = 0;
                DscStudio.Nodes.forEach(function(node) {
                    node.additionalProperties.forEach(function(additionalProp) {
                        if (additionalProp.powershellName == nodeSetting.powershellName) {
                            switch(nodeSetting.valueType) {
                                case "text":
                                case "number":
                                case "choice":
                                    if (additionalProp.value.toString() !== null && additionalProp.value.toString() !== "") {
                                        occurences++;
                                    }
                                    break;
                                case "boolean":
                                    if (additionalProp.value === true) {
                                        occurences++;
                                    }
                                break;
                            }
                        }
                    });
                });
                if (occurences < nodeSetting.minOccurences) {
                    UI.ShowElement("nodeOptionsNotValidMessage");
                    var notEnoughRoleMessage = Strings.ErrorNodeSettingsRoleNeeded.replace("{0}", nodeSetting.minOccurences).replace("{1}", nodeSetting.displayName);
                    UI.AppendText("#nodeOptionsNotValidContent", notEnoughRoleMessage + "
");
                    result = false;
                }
                if (occurences > nodeSetting.maxOccurences) {
                    UI.ShowElement("nodeOptionsNotValidMessage");
                    var tooManyRoleMessage = Strings.ErrorNodeSettingsRoleAsMaximum.replace("{0}", nodeSetting.minOccurences).replace("{1}", nodeSetting.displayName);
                    UI.AppendText("#nodeOptionsNotValidContent", tooManyRoleMessage + "
");
                    result = false;
                }
            }
        });

        return result;
    },
    ValidateComplexTypeItem: function(id) {
        var question = null;
        DscStudio.CurrentTemplate.questions.forEach(function(element) {
            if (element.id === id) {
                question = element;
            }
        }, this);

        var returnVal = true;
        question.properties.forEach(function(element) {
            switch(element.type) {
                case "text":
                    var val = UI.GetValue(`#complex-${question.id}-${element.powershellName}`);
                    if (val === null || val === "" || val === undefined) {
                        returnVal = false;
                    }
                    break;
                case "number":
                    var numval = UI.GetValue(`#complex-${question.id}-${element.powershellName}`);
                    if (numval === null || numval === "" || numval === undefined || isNaN(numval)) {
                        returnVal = false;
                    }
                    break;
                case "boolean":

                    break;
            }
            if (returnVal === true)
            {
                UI.RemoveClass(`#complex-${question.id}-${element.powershellName}`, "ms-borderColor-red");
            }
            else
            {
                UI.AddClass(`#complex-${question.id}-${element.powershellName}`, "ms-borderColor-red");
            }
        });
        return returnVal;
    }
};


text:
//------------------------------------------------------------------------------
// <autogenerated>
//     This code was generated by a CodeSmith Template.
//
//     DO NOT MODIFY contents of this file. Changes to this
//     file will be lost if the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;

namespace Tracker.Data.Entities
{
    public partial class User
    {
        public User()
        {
            CreatedDate = DateTime.Now;
            ModifiedDate = DateTime.Now;
            PasswordHash = "";
            PasswordSalt = "";
            IsApproved = true;
            LastLoginDate = DateTime.Now;
            LastActivityDate = DateTime.Now;
            Audits = new HashSet<Audit>();
            AssignedTasks = new HashSet<Task>();
            CreatedTasks = new HashSet<Task>();
            UserRoles = new HashSet<UserRole>();
        }

        public int Id { get; set; }
        public string EmailAddress { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Byte[] Avatar { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime ModifiedDate { get; set; }
        public Byte[] RowVersion { get; set; }
        public string PasswordHash { get; set; }
        public string PasswordSalt { get; set; }
        public string Comment { get; set; }
        public bool IsApproved { get; set; }
        public DateTime? LastLoginDate { get; set; }
        public DateTime LastActivityDate { get; set; }
        public DateTime? LastPasswordChangeDate { get; set; }
        public string AvatarType { get; set; }

        public virtual ICollection<Audit> Audits { get; set; }
        public virtual ICollection<Task> AssignedTasks { get; set; }
        public virtual ICollection<Task> CreatedTasks { get; set; }
        public virtual ICollection<UserRole> UserRoles { get; set; }
    }
}


text:
// This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.

//! Default base class for compiled templates.

use template::api::Template;
use engine::TwigError;
use runtime::{Runtime, Job};
use runtime::api::Execute;
use engine::node;
use api::error::Traced;

#[allow(dead_code)]
#[derive(Debug)]
pub struct Compiled {
    root: node::Module, /* TODO move *some* information from node::Module to template::Compiled
                         *  -> easier accessible for runtime
                         *  -> less accessible for node traverser (optimizer?) ... */
}

impl Compiled {
    pub fn new(root: node::Module) -> Compiled {
        Compiled { root: root }
    }

    #[allow(dead_code)]
    pub fn module(&self) -> &node::Module {
        &self.root
    }
}

impl Template for Compiled {
    fn render(&self, runtime: &Runtime) -> Result<String, Traced<TwigError>> {
        Ok(runtime.run(&self.root))
    }

    fn display(&self, _runtime: &Runtime, _blocks: Option<Vec<()>>) {
        unimplemented!()
    }
}

impl Execute for Compiled {
    fn execute(&self, runtime: &Runtime, job: &mut Job) {
        self.root.execute(runtime, job);
    }
}