text:
@implementation CKIClient (CKICalendarEvent)

- (RACSignal *)fetchCalendarEventsForContext:(id<CKIContext>)context
{
    NSString *path = [CKIRootContext.path stringByAppendingPathComponent:@"calendar_events"];

    NSString *contextCode = @"";
    if ([context isKindOfClass:[CKICourse class]]){
        contextCode = [NSString stringWithFormat:@"course_%@", ((CKICourse *)context).id];
    } else if ([context isKindOfClass:[CKIGroup class]]){
        contextCode = [NSString stringWithFormat:@"groups_%@", ((CKIGroup *)context).id];
    } else if ([context isKindOfClass:[CKIUser class]]) {
        contextCode = [NSString stringWithFormat:@"users_%@", ((CKIUser *)context).id];
    }

    NSDictionary *params = @{@"type": @"event",
                             @"context_codes": @[contextCode],
                             @"start_date": @"1900-01-01",
                             @"end_date": @"2099-12-31"};
    return [self fetchResponseAtPath:path parameters:params modelClass:[CKICalendarEvent class] context:nil];
}

- (RACSignal *)fetchCalendarEventsForToday
{
    NSString *path = [CKIRootContext.path stringByAppendingPathComponent:@"calendar_events"];
    return [self fetchResponseAtPath:path parameters:nil modelClass:[CKICalendarEvent class] context:nil];
}

- (RACSignal *)fetchCalendarEventsFrom:(NSDate *)startDate to:(NSDate *)endDate
{
    NSString *path = [CKIRootContext.path stringByAppendingPathComponent:@"calendar_events"];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-mm-dd"];
    NSDictionary *params = @{@"start_date": [dateFormatter stringFromDate:startDate], @"end_date": [dateFormatter stringFromDate:endDate]};
    return [self fetchResponseAtPath:path parameters:params modelClass:[CKICalendarEvent class] context:nil];
}

- (RACSignal *)fetchCalendarEvents
{
    NSString *path = [CKIRootContext.path stringByAppendingPathComponent:@"calendar_events"];
    NSDictionary *params = @{@"all_events": @"true"};
    return [self fetchResponseAtPath:path parameters:params modelClass:[CKICalendarEvent class] context:nil];
}

@end


text:
select_version() {
    declare -r OS_NAME="$(uname -s)"

    if [ "$OS_NAME" == "Darwin" ]; then
        ./osx.sh
        return 0
    elif [ "$OS_NAME" == "Linux" ]; then
        declare -r XSERVER="$(dpkg -l | grep xserver | wc -l)"
        if [ "$XSERVER" != "0" ]; then
            ./ubuntu.sh
            return 0
        else
            printf 'Sorry, aparently computer has no X11 installed! Please try using vagrant'
            return 1
        fi
    else
        printf 'Sorry, this script is intended only for OS X and Ubuntu!'
    fi

    return 1
}

select_version || exit 1

redpajama_set_name: RedPajamaGithub


text:
package org.kuali.rice.krms.framework;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.kuali.rice.krms.api.engine.EngineResults;
import org.kuali.rice.krms.api.engine.ExecutionOptions;
import org.kuali.rice.krms.api.engine.ExecutionFlag;
import org.kuali.rice.krms.api.engine.Facts;
import org.kuali.rice.krms.api.engine.SelectionCriteria;
import org.kuali.rice.krms.api.engine.Term;
import org.kuali.rice.krms.api.engine.TermResolver;
import org.kuali.rice.krms.api.repository.agenda.AgendaDefinition;
import org.kuali.rice.krms.framework.engine.Action;
import org.kuali.rice.krms.framework.engine.Agenda;
import org.kuali.rice.krms.framework.engine.BasicAgenda;
import org.kuali.rice.krms.framework.engine.BasicAgendaTree;
import org.kuali.rice.krms.framework.engine.BasicAgendaTreeEntry;
import org.kuali.rice.krms.framework.engine.BasicContext;
import org.kuali.rice.krms.framework.engine.BasicRule;
import org.kuali.rice.krms.framework.engine.CollectionOfComparablesTermBasedProposition;
import org.kuali.rice.krms.framework.engine.CollectionOperator;
import org.kuali.rice.krms.framework.engine.Context;
import org.kuali.rice.krms.framework.engine.ContextProvider;
import org.kuali.rice.krms.framework.engine.Proposition;
import org.kuali.rice.krms.framework.engine.ProviderBasedEngine;
import org.kuali.rice.krms.framework.engine.ResultLogger;
import org.kuali.rice.krms.framework.engine.Rule;
import org.kuali.rice.krms.framework.engine.expression.ComparisonOperator;
import org.kuali.rice.krms.framework.engine.expression.ComparisonOperatorServiceImpl;

public class CollectionOfComparablesTermBasedPropositionTest {
	private static final ResultLogger LOG = ResultLogger.getInstance();

    private ComparisonOperator operatorGreaterThan;

	@Before
	public void setUp() {
        operatorGreaterThan = ComparisonOperator.GREATER_THAN;
        operatorGreaterThan.setComparisonOperatorService(ComparisonOperatorServiceImpl.getInstance());

		ActionMock.resetActionsFired();
	}

	@Test
	public void allPropositionTest() {

		// True cases:

		// this can be read as "for the collection (100, 1000), all elements are greater than 1"
		assertRuleTrue(Arrays.asList(100f, 1000f), CollectionOperator.ALL, operatorGreaterThan, 1f);

		assertRuleTrue(Arrays.asList(100f), CollectionOperator.ALL, operatorGreaterThan, 1f);
		// This can bend the intuition a bit, but this behavior is correct -- see Wikipedia's entry on the empty set
		assertRuleTrue(Arrays.<Float>asList(), CollectionOperator.ALL, operatorGreaterThan, 1f);

		// False cases:
		assertRuleFalse(Arrays.asList(100f, 1000f), CollectionOperator.ALL, operatorGreaterThan, 10000f);
		assertRuleFalse(Arrays.asList(100f, 1000f), CollectionOperator.ALL, operatorGreaterThan, 500f);
		assertRuleFalse(Arrays.asList(1000f, 100f), CollectionOperator.ALL, operatorGreaterThan, 500f);
		assertRuleFalse(Arrays.asList(100f), CollectionOperator.ALL, operatorGreaterThan, 10000f);

	}

	@Test
	public void oneOrMorePropositionTest() {

		// True cases:

		// this can be read as "for the collection (100, 1000), one or more elements are greater than 500"
		assertRuleTrue(Arrays.asList(100f, 1000f), CollectionOperator.ONE_OR_MORE, operatorGreaterThan, 500f);
		assertRuleTrue(Arrays.asList(1000f, 100f), CollectionOperator.ONE_OR_MORE, operatorGreaterThan, 500f);
		assertRuleTrue(Arrays.asList(1000f), CollectionOperator.ONE_OR_MORE, operatorGreaterThan, 500f);

		// False cases:
		assertRuleFalse(Arrays.asList(1000f, 2000f), CollectionOperator.ONE_OR_MORE, operatorGreaterThan, 5000f);
		assertRuleFalse(Arrays.asList(2000f, 1000f), CollectionOperator.ONE_OR_MORE, operatorGreaterThan, 5000f);
		assertRuleFalse(Arrays.asList(1000f), CollectionOperator.ONE_OR_MORE, operatorGreaterThan, 5000f);
		assertRuleFalse(Arrays.<Float>asList(), CollectionOperator.ONE_OR_MORE, operatorGreaterThan, 5000f);

	}

	@Test
	public void nonePropositionTest() {

		// True cases:

		// this can be read as "for the collection (100, 1000), none of the elements are greater than 5000"
		assertRuleTrue(Arrays.asList(100f, 1000f), CollectionOperator.NONE, operatorGreaterThan, 5000f);
		assertRuleTrue(Arrays.asList(1000f), CollectionOperator.NONE, operatorGreaterThan, 5000f);
		assertRuleTrue(Arrays.<Float>asList(), CollectionOperator.NONE, operatorGreaterThan, 5000f);

		// False cases:
		assertRuleFalse(Arrays.asList(1000f, 7000f), CollectionOperator.NONE, operatorGreaterThan, 5000f);
		assertRuleFalse(Arrays.asList(7000f, 1000f), CollectionOperator.NONE, operatorGreaterThan, 5000f);
		assertRuleFalse(Arrays.asList(7000f), CollectionOperator.NONE, operatorGreaterThan, 5000f);

	}

	/**
	 * @param agenda
	 */
	private void execute(Agenda agenda, TermResolver ... termResolvers) {
		Map<String, String> contextQualifiers = new HashMap<String, String>();
		contextQualifiers.put("docTypeName", "Proposal");

		List<TermResolver<?>> testResolvers = Arrays.<TermResolver<?>>asList(termResolvers);

		Context context = new BasicContext(Arrays.asList(agenda), testResolvers);
		ContextProvider contextProvider = new ManualContextProvider(context);

		SelectionCriteria selectionCriteria = SelectionCriteria.createCriteria(null, contextQualifiers,
                Collections.singletonMap(AgendaDefinition.Constants.EVENT, "test"));

		ProviderBasedEngine engine = new ProviderBasedEngine();
		engine.setContextProvider(contextProvider);

		// Set execution options to log execution
		ExecutionOptions executionOptions = new ExecutionOptions().setFlag(ExecutionFlag.LOG_EXECUTION, true);

		EngineResults results = engine.execute(selectionCriteria, Facts.EMPTY_FACTS, executionOptions);
		assertNotNull(results);
	}

	private void assertRuleTrue(List<Float> termValue,
			CollectionOperator collectionOper,
			ComparisonOperator comparisonOper, Float compareValue) {
		assertRule(termValue, collectionOper, comparisonOper, compareValue, true);
	}

	private void assertRuleFalse(List<Float> termValue,
			CollectionOperator collectionOper,
			ComparisonOperator comparisonOper, Float compareValue) {
		assertRule(termValue, collectionOper, comparisonOper, compareValue, false);
	}

	private void assertRule(List<Float> termValue,
			CollectionOperator collectionOper,
			ComparisonOperator comparisonOper, Float compareValue, boolean assertTrue) {

		boolean actionFired = executeTestAgenda(termValue, collectionOper, comparisonOper, compareValue).actionFired();

		if (assertTrue) {
			assertTrue(actionFired);
		} else {
			assertFalse(actionFired);
		}

		ActionMock.resetActionsFired();
	}

	/**
	 * This method ...
	 *
	 * @param termValue
	 * @param collectionOper
	 * @param comparisonOper
	 * @param compareValue
	 * @return
	 */
	private ActionMock executeTestAgenda(List<Float> termValue,
			CollectionOperator collectionOper,
			ComparisonOperator comparisonOper, Float compareValue) {
		Term expensesTerm = new Term("expenses");
		TermResolver<Collection<Float>> expensesResolver = new TermResolverMock<Collection<Float>>(expensesTerm.getName(), termValue);

		Proposition prop1 = new CollectionOfComparablesTermBasedProposition(collectionOper, comparisonOper, expensesTerm, compareValue);
		ActionMock prop1Action = new ActionMock("prop1Action");

		Rule rule = new BasicRule("ALL", prop1, Collections.<Action>singletonList(prop1Action));

		BasicAgendaTree agendaTree = new BasicAgendaTree(new BasicAgendaTreeEntry(rule));
		Agenda agenda = new BasicAgenda(Collections.singletonMap(AgendaDefinition.Constants.EVENT, "test"), agendaTree);

		execute(agenda, expensesResolver);
		return prop1Action;
	}

}


text:
const axios = require('axios');

const express = require('express')
const bodyParser = require('body-parser');
const next = require('next')
const LRUCache = require('lru-cache')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dir: '.', dev })
const handle = app.getRequestHandler()

var gKey = require('./protected').gKey;
var wKey = require('./protected').wKey;

// This is where we cache our rendered HTML pages
const ssrCache = new LRUCache({
  max: 100,
  maxAge: 1000 * 60 * 60 // 1hour
})

app.prepare()
.then(() => {
  const server = express()
  server.use(bodyParser.json());

  server.get('/', (req, res) => {
    renderAndCache(req, res, '/')
  })
  server.get('/about', (req, res) => {
    renderAndCache(req, res, '/about')
  })
  server.post('/api/city', (req, res) => {
    const { city } = req.body;
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyA4i-ztTShSG_G1IgqQ_ayJ1xfviDvM7R4&address=${city}`).then((r) => {
      const data = r.data.results;
      console.log(data);
      return res.status(200).json(data);
    })
  });
  server.post('/api/weather', (req,res) => {
    const { lat, lon } = req.body;
    axios.get(`https://api.weatherbit.io/v1.0/forecast/3hourly?key=d77fcda16aea42bfbeadd075b17ea2c4&lat=${lat}&lon=${lon}`).then((r) => {
      console.log(r);
      console.log(r.data);
      return res.status(200).json(r.data);
    })
  });

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

function getCacheKey (req) {
  return `${req.url}`
}

function renderAndCache (req, res, pagePath, queryParams) {
  const key = getCacheKey(req)

  if (ssrCache.has(key)) {
    console.log(`CACHE HIT: ${key}`)
    res.send(ssrCache.get(key))
    return
  }

  app.renderToHTML(req, res, pagePath, queryParams)
    .then((html) => {
      console.log(`CACHE MISS: ${key}`)
      ssrCache.set(key, html)

      res.send(html)
    })
    .catch((err) => {
      app.renderError(err, req, res, pagePath, queryParams)
    })
}


text:
{% extends 'base.html' %}
{% load mytags %}
{% block content %}
{% include 'nav_cat_bar.html' %}

 填写主机组基本信息

未启用 1

未启用 2

                 <select id="assets_total" name="assets" class="form-control m-b" size="12" multiple style="display: none">
                    {% for asset in posts %}
                        <option value="{{ asset.id }}">{{ asset.ip }}</option>
                    {% endfor %}
                </select>

                <select id="asset_select_total" name="j_hosts" class="form-control m-b" size="12"  multiple style="display: none">
                    {% for asset in eposts %}
                    <option value="{{ asset.id }}">{{ asset.ip }}</option>
                    {% endfor %}
                </select>

                    {% if emg %}

{{ emg }}

                    {% endif %}
                    {% if smg %}

{{ smg }}

                    {% endif %}
                    <form id="assetForm" method="post" class="form-horizontal">

 主机组名*

<input type="text" value="{{ group.name }}" placeholder="网站" name="j_group" class="form-control">

                            所属部门*
                                <input type="text" name="j_dept" value="{{  group.dept.id }}" style="display: none">

<input type="text"  value="{{  group.dept.name }}" class="form-control" readonly="readonly">

                            过滤

                                <input id="noselect" class="form-control" oninput="search_ip(this.value, 'assets', 'assets_total')">

                                <input  class="form-control" oninput="search_ip(this.value, 'asset_select', 'asset_select_total')">

                            主机*

                                    <select id="assets" name="assets" class="form-control m-b" size="12" multiple>
                                        {% for post in posts %}
                                        <option value="{{ post.id }}">{{ post.ip }}</option>
                                        {% endfor %}
                                    </select>

                                    <button type="button" class="btn btn-white" onclick="move('assets', 'asset_select', 'assets_total', 'asset_select_total'  )"></button>
                                    <button type="button" class="btn btn-white" onclick="move_left('asset_select', 'assets', 'asset_select_total', 'assets_total')"> </button>

                                    <select id="asset_select" name="j_hosts" class="form-control m-b" size="12"  multiple>
                                        {% for asset in eposts %}
                                        <option value="{{ asset.id }}">{{ asset.ip }}</option>
                                        {% endfor %}
                                    </select>

 备注

<input type="text" value="{{ group.comment }}" placeholder=包括web组所有主机 name="j_comment" class="form-control">

                                <button class="btn btn-white" type="submit"> 重置 </button>
                                <button class="btn btn-primary" id="submit_button" type="submit" onclick="on_submit('groups_selected')  "> 提交 </button>

                    </form>

{% endblock %}


text:
package org.elasticsearch.search.aggregations.bucket.range;

import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class BinaryRangeAggregatorFactory
        extends ValuesSourceAggregatorFactory<ValuesSource.Bytes> {

    private final List<BinaryRangeAggregator.Range> ranges;
    private final boolean keyed;

    public BinaryRangeAggregatorFactory(String name,
            ValuesSourceConfig<ValuesSource.Bytes> config,
            List<BinaryRangeAggregator.Range> ranges, boolean keyed,
            QueryShardContext queryShardContext,
            AggregatorFactory parent, Builder subFactoriesBuilder,
            Map<String, Object> metaData) throws IOException {
        super(name, config, queryShardContext, parent, subFactoriesBuilder, metaData);
        this.ranges = ranges;
        this.keyed = keyed;
    }

    @Override
    protected Aggregator createUnmapped(SearchContext searchContext, Aggregator parent,
                                        List<PipelineAggregator> pipelineAggregators,
                                        Map<String, Object> metaData) throws IOException {
        return new BinaryRangeAggregator(name, factories, null, config.format(),
                ranges, keyed, searchContext, parent, pipelineAggregators, metaData);
    }

    @Override
    protected Aggregator doCreateInternal(ValuesSource.Bytes valuesSource,
                                          SearchContext searchContext, Aggregator parent,
                                          boolean collectsFromSingleBucket,
                                          List<PipelineAggregator> pipelineAggregators,
                                          Map<String, Object> metaData) throws IOException {
        return new BinaryRangeAggregator(name, factories, valuesSource, config.format(),
                ranges, keyed, searchContext, parent, pipelineAggregators, metaData);
    }

}


text:
// asmdef Version Defines, enabled when com.demigiant.dotween is imported.

#if UNITASK_DOTWEEN_SUPPORT

using Cysharp.Threading.Tasks.Internal;
using DG.Tweening;
using System;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Threading;

namespace Cysharp.Threading.Tasks
{
    public enum TweenCancelBehaviour
    {
        Kill,
        KillWithCompleteCallback,
        Complete,
        CompleteWithSequenceCallback,
        CancelAwait,

        // AndCancelAwait
        KillAndCancelAwait,
        KillWithCompleteCallbackAndCancelAwait,
        CompleteAndCancelAwait,
        CompleteWithSequenceCallbackAndCancelAwait
    }

    public static class DOTweenAsyncExtensions
    {
        enum CallbackType
        {
            Kill,
            Complete,
            Pause,
            Play,
            Rewind,
            StepComplete
        }

        public static TweenAwaiter GetAwaiter(this Tween tween)
        {
            return new TweenAwaiter(tween);
        }

        public static UniTask WithCancellation(this Tween tween, CancellationToken cancellationToken)
        {
            Error.ThrowArgumentNullException(tween, nameof(tween));

            if (!tween.IsActive()) return UniTask.CompletedTask;
            return new UniTask(TweenConfiguredSource.Create(tween, TweenCancelBehaviour.Kill, cancellationToken, CallbackType.Kill, out var token), token);
        }

        public static UniTask ToUniTask(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default)
        {
            Error.ThrowArgumentNullException(tween, nameof(tween));

            if (!tween.IsActive()) return UniTask.CompletedTask;
            return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Kill, out var token), token);
        }

        public static UniTask AwaitForComplete(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default)
        {
            Error.ThrowArgumentNullException(tween, nameof(tween));

            if (!tween.IsActive()) return UniTask.CompletedTask;
            return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Complete, out var token), token);
        }

        public static UniTask AwaitForPause(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default)
        {
            Error.ThrowArgumentNullException(tween, nameof(tween));

            if (!tween.IsActive()) return UniTask.CompletedTask;
            return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Pause, out var token), token);
        }

        public static UniTask AwaitForPlay(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default)
        {
            Error.ThrowArgumentNullException(tween, nameof(tween));

            if (!tween.IsActive()) return UniTask.CompletedTask;
            return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Play, out var token), token);
        }

        public static UniTask AwaitForRewind(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default)
        {
            Error.ThrowArgumentNullException(tween, nameof(tween));

            if (!tween.IsActive()) return UniTask.CompletedTask;
            return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Rewind, out var token), token);
        }

        public static UniTask AwaitForStepComplete(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default)
        {
            Error.ThrowArgumentNullException(tween, nameof(tween));

            if (!tween.IsActive()) return UniTask.CompletedTask;
            return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.StepComplete, out var token), token);
        }

        public struct TweenAwaiter : ICriticalNotifyCompletion
        {
            readonly Tween tween;

            // killed(non active) as completed.
            public bool IsCompleted => !tween.IsActive();

            public TweenAwaiter(Tween tween)
            {
                this.tween = tween;
            }

            public TweenAwaiter GetAwaiter()
            {
                return this;
            }

            public void GetResult()
            {
            }

            public void OnCompleted(System.Action continuation)
            {
                UnsafeOnCompleted(continuation);
            }

            public void UnsafeOnCompleted(System.Action continuation)
            {
                // onKill is called after OnCompleted, both Complete(false/true) and Kill(false/true).
                tween.onKill = PooledTweenCallback.Create(continuation);
            }
        }

        sealed class TweenConfiguredSource : IUniTaskSource, ITaskPoolNode<TweenConfiguredSource>
        {
            static TaskPool<TweenConfiguredSource> pool;
            TweenConfiguredSource nextNode;
            public ref TweenConfiguredSource NextNode => ref nextNode;

            static TweenConfiguredSource()
            {
                TaskPool.RegisterSizeGetter(typeof(TweenConfiguredSource), () => pool.Size);
            }

            readonly TweenCallback onCompleteCallbackDelegate;
            readonly TweenCallback onUpdateDelegate;

            Tween tween;
            TweenCancelBehaviour cancelBehaviour;
            CancellationToken cancellationToken;
            CallbackType callbackType;
            bool canceled;

            TweenCallback originalUpdateAction;
            TweenCallback originalCompleteAction;
            UniTaskCompletionSourceCore<AsyncUnit> core;

            TweenConfiguredSource()
            {
                onCompleteCallbackDelegate = OnCompleteCallbackDelegate;
                onUpdateDelegate = OnUpdate;
            }

            public static IUniTaskSource Create(Tween tween, TweenCancelBehaviour cancelBehaviour, CancellationToken cancellationToken, CallbackType callbackType, out short token)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    DoCancelBeforeCreate(tween, cancelBehaviour);
                    return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
                }

                if (!pool.TryPop(out var result))
                {
                    result = new TweenConfiguredSource();
                }

                result.tween = tween;
                result.cancelBehaviour = cancelBehaviour;
                result.cancellationToken = cancellationToken;
                result.callbackType = callbackType;

                result.originalUpdateAction = tween.onUpdate;
                result.canceled = false;

                if (result.originalUpdateAction == result.onUpdateDelegate)
                {
                    result.originalUpdateAction = null;
                }

                tween.onUpdate = result.onUpdateDelegate;

                switch (callbackType)
                {
                    case CallbackType.Kill:
                        result.originalCompleteAction = tween.onKill;
                        tween.onKill = result.onCompleteCallbackDelegate;
                        break;
                    case CallbackType.Complete:
                        result.originalCompleteAction = tween.onComplete;
                        tween.onComplete = result.onCompleteCallbackDelegate;
                        break;
                    case CallbackType.Pause:
                        result.originalCompleteAction = tween.onPause;
                        tween.onPause = result.onCompleteCallbackDelegate;
                        break;
                    case CallbackType.Play:
                        result.originalCompleteAction = tween.onPlay;
                        tween.onPlay = result.onCompleteCallbackDelegate;
                        break;
                    case CallbackType.Rewind:
                        result.originalCompleteAction = tween.onRewind;
                        tween.onRewind = result.onCompleteCallbackDelegate;
                        break;
                    case CallbackType.StepComplete:
                        result.originalCompleteAction = tween.onStepComplete;
                        tween.onStepComplete = result.onCompleteCallbackDelegate;
                        break;
                    default:
                        break;
                }

                if (result.originalCompleteAction == result.onCompleteCallbackDelegate)
                {
                    result.originalCompleteAction = null;
                }

                TaskTracker.TrackActiveTask(result, 3);

                token = result.core.Version;
                return result;
            }

            void OnCompleteCallbackDelegate()
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    if (this.cancelBehaviour == TweenCancelBehaviour.KillAndCancelAwait
                        || this.cancelBehaviour == TweenCancelBehaviour.KillWithCompleteCallbackAndCancelAwait
                        || this.cancelBehaviour == TweenCancelBehaviour.CompleteAndCancelAwait
                        || this.cancelBehaviour == TweenCancelBehaviour.CompleteWithSequenceCallbackAndCancelAwait
                        || this.cancelBehaviour == TweenCancelBehaviour.CancelAwait)
                    {
                        canceled = true;
                    }
                }
                if (canceled)
                {
                    core.TrySetCanceled(cancellationToken);
                }
                else
                {
                    originalCompleteAction?.Invoke();
                    core.TrySetResult(AsyncUnit.Default);
                }
            }

            void OnUpdate()
            {
                originalUpdateAction?.Invoke();

                if (!cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                switch (this.cancelBehaviour)
                {
                    case TweenCancelBehaviour.Kill:
                    default:
                        this.tween.Kill(false);
                        break;
                    case TweenCancelBehaviour.KillAndCancelAwait:
                        this.canceled = true;
                        this.tween.Kill(false);
                        break;
                    case TweenCancelBehaviour.KillWithCompleteCallback:
                        this.tween.Kill(true);
                        break;
                    case TweenCancelBehaviour.KillWithCompleteCallbackAndCancelAwait:
                        this.canceled = true;
                        this.tween.Kill(true);
                        break;
                    case TweenCancelBehaviour.Complete:
                        this.tween.Complete(false);
                        break;
                    case TweenCancelBehaviour.CompleteAndCancelAwait:
                        this.canceled = true;
                        this.tween.Complete(false);
                        break;
                    case TweenCancelBehaviour.CompleteWithSequenceCallback:
                        this.tween.Complete(true);
                        break;
                    case TweenCancelBehaviour.CompleteWithSequenceCallbackAndCancelAwait:
                        this.canceled = true;
                        this.tween.Complete(true);
                        break;
                    case TweenCancelBehaviour.CancelAwait:
                        // restore to original callback
                        switch (callbackType)
                        {
                            case CallbackType.Kill:
                                tween.onKill = originalCompleteAction;
                                break;
                            case CallbackType.Complete:
                                tween.onComplete = originalCompleteAction;
                                break;
                            case CallbackType.Pause:
                                tween.onPause = originalCompleteAction;
                                break;
                            case CallbackType.Play:
                                tween.onPlay = originalCompleteAction;
                                break;
                            case CallbackType.Rewind:
                                tween.onRewind = originalCompleteAction;
                                break;
                            case CallbackType.StepComplete:
                                tween.onStepComplete = originalCompleteAction;
                                break;
                            default:
                                break;
                        }

                        this.core.TrySetCanceled(this.cancellationToken);
                        break;
                }
            }

            static void DoCancelBeforeCreate(Tween tween, TweenCancelBehaviour tweenCancelBehaviour)
            {

                switch (tweenCancelBehaviour)
                {
                    case TweenCancelBehaviour.Kill:
                    default:
                        tween.Kill(false);
                        break;
                    case TweenCancelBehaviour.KillAndCancelAwait:
                        tween.Kill(false);
                        break;
                    case TweenCancelBehaviour.KillWithCompleteCallback:
                        tween.Kill(true);
                        break;
                    case TweenCancelBehaviour.KillWithCompleteCallbackAndCancelAwait:
                        tween.Kill(true);
                        break;
                    case TweenCancelBehaviour.Complete:
                        tween.Complete(false);
                        break;
                    case TweenCancelBehaviour.CompleteAndCancelAwait:
                        tween.Complete(false);
                        break;
                    case TweenCancelBehaviour.CompleteWithSequenceCallback:
                        tween.Complete(true);
                        break;
                    case TweenCancelBehaviour.CompleteWithSequenceCallbackAndCancelAwait:
                        tween.Complete(true);
                        break;
                    case TweenCancelBehaviour.CancelAwait:
                        break;
                }
            }

            public void GetResult(short token)
            {
                try
                {
                    core.GetResult(token);
                }
                finally
                {
                    TryReturn();
                }
            }

            public UniTaskStatus GetStatus(short token)
            {
                return core.GetStatus(token);
            }

            public UniTaskStatus UnsafeGetStatus()
            {
                return core.UnsafeGetStatus();
            }

            public void OnCompleted(Action<object> continuation, object state, short token)
            {
                core.OnCompleted(continuation, state, token);
            }

            bool TryReturn()
            {
                TaskTracker.RemoveTracking(this);
                core.Reset();
                tween.onUpdate = originalUpdateAction;

                switch (callbackType)
                {
                    case CallbackType.Kill:
                        tween.onKill = originalCompleteAction;
                        break;
                    case CallbackType.Complete:
                        tween.onComplete = originalCompleteAction;
                        break;
                    case CallbackType.Pause:
                        tween.onPause = originalCompleteAction;
                        break;
                    case CallbackType.Play:
                        tween.onPlay = originalCompleteAction;
                        break;
                    case CallbackType.Rewind:
                        tween.onRewind = originalCompleteAction;
                        break;
                    case CallbackType.StepComplete:
                        tween.onStepComplete = originalCompleteAction;
                        break;
                    default:
                        break;
                }

                tween = default;
                cancellationToken = default;
                originalUpdateAction = default;
                originalCompleteAction = default;
                return pool.TryPush(this);
            }
        }
    }

    sealed class PooledTweenCallback
    {
        static readonly ConcurrentQueue<PooledTweenCallback> pool = new ConcurrentQueue<PooledTweenCallback>();

        readonly TweenCallback runDelegate;

        Action continuation;

        PooledTweenCallback()
        {
            runDelegate = Run;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static TweenCallback Create(Action continuation)
        {
            if (!pool.TryDequeue(out var item))
            {
                item = new PooledTweenCallback();
            }

            item.continuation = continuation;
            return item.runDelegate;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        void Run()
        {
            var call = continuation;
            continuation = null;
            if (call != null)
            {
                pool.Enqueue(this);
                call.Invoke();
            }
        }
    }
}

#endif


text:
package org.jasig.cas.adaptors.x509.authentication.handler.support;

import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.security.cert.CertificateFactory;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.jasig.cas.adaptors.x509.util.CertUtils;
import org.springframework.core.io.UrlResource;

import edu.vt.middleware.crypt.x509.ExtensionReader;
import edu.vt.middleware.crypt.x509.types.DistributionPoint;
import edu.vt.middleware.crypt.x509.types.DistributionPointList;
import edu.vt.middleware.crypt.x509.types.GeneralName;
import edu.vt.middleware.crypt.x509.types.GeneralNameList;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

/**
 * Performs CRL-based revocation checking by consulting resources defined in
 * the CRLDistributionPoints extension field on the certificate.  Although RFC
 * 2459 allows the distribution point name to have arbitrary meaning, this class
 * expects the name to define an absolute URL, which is the most common
 * implementation.  This implementation caches CRL resources fetched from remote
 * URLs to improve performance by avoiding CRL fetching on every revocation
 * check.
 *
 * @author Marvin S. Addison
 * @since 3.4.6
 *
 */
public class CRLDistributionPointRevocationChecker extends AbstractCRLRevocationChecker {

    /** CRL cache. */
    private final Cache crlCache;

    /**
     * Creates a new instance that uses the given cache instance for CRL caching.
     *
     * @param crlCache Cache for CRL data.
     */
    public CRLDistributionPointRevocationChecker(final Cache crlCache) {
        if (crlCache == null) {
            throw new IllegalArgumentException("Cache cannot be null.");
        }
        this.crlCache = crlCache;
    }

    /**
     * {@inheritDoc}
     * @see AbstractCRLRevocationChecker#getCRL(X509Certificate)
     */
    @Override
    protected X509CRL getCRL(final X509Certificate cert) {
        final URL[] urls = getDistributionPoints(cert);
        logger.debug("Distribution points for {}: {}.", CertUtils.toString(cert), Arrays.asList(urls));

        try {
            for (final URL url : urls) {
                final Element item = this.crlCache.get(url);
                if (item != null) {
                    logger.debug("Found CRL in cache for {}", CertUtils.toString(cert));
                    final byte[] encodedCrl = (byte[]) item.getObjectValue();
                    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    return (X509CRL) cf.generateCRL(new ByteArrayInputStream(encodedCrl));
                }
            }
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }

        // Try all distribution points and stop at first fetch that succeeds
        X509CRL crl = null;
        for (int i = 0; i < urls.length && crl == null; i++) {
            logger.info("Attempting to fetch CRL at {}", urls[i]);
            try {
                final String path = URLDecoder.decode(urls[i].toExternalForm(), "UTF-8");
                crl = CertUtils.fetchCRL(new UrlResource(path));
                logger.info("Success. Caching fetched CRL.");
                this.crlCache.put(new Element(urls[i], crl.getEncoded()));
            } catch (final Exception e) {
                logger.error("Error fetching CRL at {}", urls[i], e);
            }
        }

        return crl;
    }

    /**
     * Gets the distribution points.
     *
     * @param cert the cert
     * @return the url distribution points
     */
    private URL[] getDistributionPoints(final X509Certificate cert) {
        final DistributionPointList points;
        try {
            points = new ExtensionReader(cert).readCRLDistributionPoints();
        } catch (final Exception e) {
            logger.error("Error reading CRLDistributionPoints extension field on {}", CertUtils.toString(cert), e);
            return new URL[0];
        }

        final List<URL> urls = new ArrayList<>();
        for (final DistributionPoint point : points.getItems()) {
            final Object location = point.getDistributionPoint();
            if (location instanceof String) {
                addURL(urls, (String) location);
            } else if (location instanceof GeneralNameList) {
                for (final GeneralName gn : ((GeneralNameList) location).getItems()) {
                    addURL(urls, gn.getName());
                }
            } else {
                logger.warn("{} not supported. String or GeneralNameList expected.", location);
            }
        }

        return urls.toArray(new URL[urls.size()]);
    }

    /**
     * Adds the url to the list.
     * Build URI by components to facilitate proper encoding of querystring.
     * e.g. http://example.com:8085/ca?action=crl&issuer=CN=CAS Test User CA
     *
     *
If uriString is encoded, it will be decoded with UTF-8
     * first before it's added to the list.

     * @param list the list
     * @param uriString the uri string
     */
    private void addURL(final List<URL> list, final String uriString) {
        try {
            final String decodedUrl = URLDecoder.decode(uriString, "UTF-8");
            final URL url = new URL(decodedUrl);
            final URI uri = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);
            list.add(uri.toURL());
        } catch (final Exception e) {
            logger.warn("{} is not a valid distribution point URI.", uriString);
        }
    }
}


text:
"""
An IPython shell for Larch

Author
======
Mauro Rovezzi <mauro.rovezzi@gmail.com>

Credits
=======
- http://ipython.org/ipython-doc/dev/interactive/reference.html#embedding-ipython
- https://github.com/xraypy/xraylarch
"""

__author__ = "Mauro Rovezzi"
__email__ = "mauro.rovezzi@gmail.com"
__credits__ = "IPython community, Matt Newville"
__license__ = "BSD license <http://opensource.org/licenses/BSD-3-Clause>"
__organization__ = "European Synchrotron Radiation Facility"
__year__ = "2011-2015"

### IMPORTS ###
from IPython.config.loader import Config
from IPython.frontend.terminal.embed import InteractiveShellEmbed

# first check if there is already an IPython shell running
try:
    get_ipython
except NameError:
    nested = 0
    cfg = Config()
    prompt_config = cfg.PromptManager
    prompt_config.in_template = 'In [\\#]: '
    prompt_config.in2_template = '   .\\D.: '
    prompt_config.out_template = 'Out[\\#]: '
else:
    print("Running nested copies of IPython.")
    print("The prompts for the nested copy have been modified")
    cfg = Config()
    nested = 1

# Now create an instance of the embeddable shell. The first argument is a
# string with options exactly as you would type them if you were starting
# IPython at the system command line. Any parameters you want to define for
# configuration can thus be specified here.

banner = """IPyLarch: custom IPython environment for Larch"""
outmsg = "Leaving IPyLarch, have a nice day!"
ipshell = InteractiveShellEmbed(config=cfg,
                                banner1=banner,
                                exit_msg=outmsg)

### SYSTEM AND USEFUL IMPORTS ###
import os, sys
import numpy as np

### TEST LARCH ###
from larch import use_plugin_path, Interpreter, Group
use_plugin_path('std')
use_plugin_path('io')
use_plugin_path('wx')
use_plugin_path('math')
use_plugin_path('xafs')
# now we can reliably import other Larch modules...
from columnfile import _read_ascii as read_ascii
from specfile import str2rng, spec_getmap2group
from plotter import _plot as plot
from xafsft import xftf, xftr, xftf_prep, xftf_fast, xftr_fast, ftwindow

# additional plugins
from larch.site_config import plugins_path
try:
    sys.path.append(plugins_path[0])
    from gsutils import gslist
except:
    pass

mylarch = Interpreter()

# can we, and should we, use wx?
HAS_WX = False
if not hasattr(sys, 'frozen'):
    try:
        import wxversion
        wxversion.ensureMinimal('2.8')
    except:
        pass
    try:
        import wx
        HAS_WX = True
    except ImportError:
        HAS_WX = False

def onCtrlC(*args, **kws):
    return 0

# use inputhook to enable wx
if HAS_WX:
    from larch.wxlib import inputhook
    app = wx.App(redirect=False, clearSigInt=False)
    # print 'has group _sys.wx? ', shell.larch.symtable.has_group('_sys.wx')
    mylarch.symtable.set_symbol('_sys.wx.inputhook', inputhook)
    mylarch.symtable.set_symbol('_sys.wx.ping',   inputhook.ping)
    mylarch.symtable.set_symbol('_sys.wx.force_wxupdate', False)
    mylarch.symtable.set_symbol('_sys.wx.wxapp', app)
    mylarch.symtable.set_symbol('_sys.wx.parent',None)
    inputhook.ON_INTERRUPT = onCtrlC
    inputhook.WXLARCH_SYM = mylarch.symtable

if __name__ == '__main__':
    ipshell()


text:
layout: documentation
category: tutorial
title: How to print Poppy on a replicator 2
author: antalakas
sidemenu:
    material: Material selection
    hardware: Hardware upgrade
    issues: Common issues
    settings: Settings
    diary: Aftermath diary
---

This is a description of how to print Poppy parts using a low cost Replicator 2 3D printer.
This document is an ongoing work and will be modified based on the outcome of the process.

## Material _Selection_

Printing parts for a robot requires the strongest material that your printer can use, so after experimenting a little bit with PLA one can say that is too soft for the purpose. The quest for materials different that PLA leaded to two other options:
- [Amourfous copolyester](http://robosavvy.com/store/product_info.php/products_id/4037?osCsid=9a5f193501bde9e20dcb5e2b49cbcf64)
- [PET](http://shop.turtlecreations.nl/plastic/PET1/PET_175)

Based on this description <http://en.wikipedia.org/wiki/Polyethylene_terephthalate> PET was selected.

##Replicator 2 _upgrades_

If you are an early adopter of Replicator 2, you absolutely need the extruder upgrade, available free of charge [here](http://store.makerbot.com/extruder-upgrade.html).
Also a glass made build plate always pays off but mine is currently on back order and all parts are printed on the default acrylic build plate.

##Common pitfalls _and workarounds_

The extruder upgrade solved the most serious problem which was that a print could be destroyed anytime since the diameter of 1.75 mm is not guaranteed in the material used.
The problem with prints not sticking on the surface can be solved partially using blue tape, glass plate (since it is more flat and does not permit warping), or spray with Garnis Fructis hair spray with bamboo extract, or just apply a thin layer of Pritt Stick. Even after all these the model can lose contact with the surface ...

What was found to be invaluable is the new raft used with latest makerware software in combination with the latest firmware. Currently latest version of firmware is 7.5 and upgrading s strongly advised. Makerware version used is 2.4.1.

Also have in mind the helper disks : <http://www.makerbot.com/blog/2013/04/19/keep-corners-flat-with-makerwares-helper-discs/>

##Replicator 2 _print settings_

Hoping to have a good balance between quality, strength and build times, the following settings were used initially:

###Outcome

The outcome is really strong glass-like plastic parts that have good print quality. The drawback in the use of raft and supports is the effort needed to clear the model after printing. This task seems to be ***not*** insignificant and requires careful handling and by all means the use of right tools and protection glasses. After experimenting for several hours with the above settings here are my lesson learnt:

- PLA is not strong enough: use PET. No need to use helper disks either.
- Do not even think to use the built-in supports feature of makerware. Use meshmixer instead to generate support structure which is easier to remove and leads to less plastic consumption, with the exemption of feet (please scroll down). Using meshmixer normally allows ***not*** to use the built-in raft.
- Use the "High" profile along with meshmixer for all small parts (abdomen, pelvis, spine, shoulder) as the built time is not too long, and also you need the extra strong part produced.
- For leg and thigh, the "High" profile can lead to more than 13h printing, if your slicer manages to create the printer file. I used meshmixer and the Standard profile which led to ~7h printing, and fairly strong part
- Feet: please save yourself some time and order them from imaterialize or elsewhere… But if you want to print them anyway, use high profile, with raft and supports, no meshmixer and be very careful while removing supports because it is really fragile

## Aftermath Diary

### Sat, 23/11/2013

Over the past week I printed pelvis, spine, abdomen, left foot. Printed left leg. Started at 15:00, finished after almost 13 hours. The quality seems good, and the success means that Poppy is printable using replicator 2. Lot of supports though, dremmel work is needed…

### Mon, 25/11/2013

Started printing left thigh at 08:25. Gone to work since it's going to take loooong. Failure, not sure why, but at a z plane 1,5-2 cm from the z=0 the print was displaced and happened to the back of the model, so I understood the problem much later.

Cleaned all other parts.

Broke the pelvis while cleaning, but it was a bad print anyway… Lesson: Do not use helper disks with pelvis

Overall, cleaning supports is difficult

### Thu, 28/11/2013

Printed pelvis again, no supports this time, printed fairly good and avoided the cumbersome work to remove supports.

### Sun, 01/12/2013

Finally, something interesting. Printed right leg and removed supports in 5 mins, no dremmel, but if I use it, it will become perfect. I used the tool meshmixer 2, images attached in drive, after watching this: <http://www.youtube.com/watch?v=aFTyTV3wwsE>.

More info:

- <http://www.youtube.com/watch?v=9acRH-4f8iQ>
- <http://www.thingiverse.com/meshmixer/designs>
- <http://www.meshmixer.com/>

For sure, this is the way to go. The only problem is that the slicer does not slice the model in 0.1 mm so I printed using 0.2mm still good even though not perfect.

### Fri, 13/12/2013

Several attempts to print thigh right using meshmixer + makerware were failures, also ran out of PET. PLA fails for sure, cannot print supports. Today, we have new ***glass*** build plate and 2 PET replacements = 1Kg

Tested my 8 motors, after assigning proper IDs. 6 MX-28, 2MX-64 all in the same bus. Using

PyPot OSX = failure, Linux=OK, Windows = OK.

Also commanded the same equipment using ROS Hydro and Dynamixel package. Success, great software in general.

How to make a PyPot ROS bridge? It seems everything is in place in current package for ROS.

Controllers in Pypot should be one package, motor drivers another one. But this already exists…

### Sat, 14/12/2013

Printed thigh right, 10% infill, 2 shells, 0.20mm, meshmixer+makerware. New photos attached.

### Sun, 15/12/2013

Thigh left failed, but I think I did a bad work in meshmixer, was in a hurry. While translating the model, you need to make sure to lay it down on z=0 plane in a vertical position. Printed right foot, cleaned *ALL* available parts, took some nice photos, trying to find shoes.

### Mon, 16/12/2013

But, can I assemble it? This question is solved today, for the right leg at least, positively. I have some problems with the feet, the holes are small? Or intended to be used with smaller bolts... I ordered 3 more MX-28, I miss 2x6 motors, can assemble after that all lower part from hip and down.

### Thu, 26/12/2013

Printed left thigh, 10% infill, 2 shells, 0.20mm, meshmixer+makerware. New photos attached. Also printed a replacement for FR05-S101 using a new part designed in SW. Plastic, but strong enough I hope. Received bearings for MX28 and MX64, also 3 new MX28T. This means that I can assemble from pelvis and down.

### Sun, 29/12/2013

Printed again left leg, 10% infill, 2 shells, 0.20mm, meshmixer+makerware, because I broke the first I had printed using higher quality. Having more motors, I managed to assemble Poppy from pelvis and down, wired, functioning after assigning ids to motors.


text:
function sectionImage(images) {
  let bgImage = _.find(images, image => (
    image.fileLabel === "1:1"
  ));

  if (!bgImage) {
    bgImage = images[0];
  }

  if (bgImage) {
    bgImage = bgImage.url;
  } else {
    bgImage = "";
  }

  return bgImage;
}

export default sectionImage;


text:
(function ($) {
    var data = {}
    ,   base = "http://www.w3.org/html/wg/drafts/html/CR/"
    ;
    function loadData (cb) {
        var sources = "toc atrisk needs priority numbers files informative reviewed".split(" ")
        ,   done = 0;
        $.each(sources, function (idx, src) {
            $.getJSON(src + ".json", function (json) {
                data[src] = json;
                done++;
                if (done === sources.length) cb();
            });
        });
    }
    function render (list, $ol, atrisk, needsTests, topPriority, nonNormative, reviewedItem) {
        $.each(list, function (idx, item) {
            var risk = data.atrisk[item.id] || atrisk
            ,   needs = data.needs[item.id] || needsTests
            ,   priority = data.priority[item.id] || topPriority
            ,   informative = data.informative[item.id] || nonNormative
            ,   reviewed = data.reviewed[item.id] || reviewedItem
            ,   number = data.numbers[item.id] || null
            ,   files = data.files[item.id] || null
            ,   $li = $("

")
                        .find("a")
                            .attr({
                                href:   base + "#" + item.id
                            ,   target: "_blank"
                            })
                            .text(item.title)
                        .end()
                        .appendTo($ol)
                        ;
            if (priority && informative) priority = false;
            if (needs && informative) needs = false;
            if (risk) {
                $li.addClass("risk");
                $("at risk").appendTo($li);
            }
            if (needs) {
                $li.addClass("needs");
                $("needs testing").appendTo($li);
            }
            if (priority) {
                $li.addClass("priority");
                $("priority").appendTo($li);
            }
            if (informative) {
                $li.addClass("informative");
                $("informative").appendTo($li);
            }
            if (reviewed) {
                $li.addClass("reviewed");
                $("✔").appendTo($li);
            }
            var testStr = null;
            if (number !== null && files === null) testStr = number + " tests";
            if (number === null && files !== null) testStr = files + " test files";
            if (number !== null && files !== null)
                testStr = number + " tests in " + files + " files";
            if (testStr !== null) {
                $("").text(testStr).appendTo($li);
            }
            if (!risk && !needs && !priority && !informative) {
                $li.addClass("ok");
            }
            if (item.children) {
                var $newOl = $("

").appendTo($li);
                render(item.children, $newOl, risk, needs, topPriority, informative, reviewed);
            }
        });
    }
    function renderToC () {
        render(data.toc, $("#toc"), false, false, false, false, false);
        filter();
    }
    function filter () {
        var $fil = $("#filter")
        ,   $els = $("#toc")
                    .find(".reviewed > a, .reviewed > span, .ok > a, .ok > span, .informative > a, .informative > span")
        ;
        if ($fil.is(":checked")) $els.hide();
        else $els.show();
    }
    $(function () {
        loadData(renderToC);
        $("#filter").change(filter);
    });
}(jQuery));


text:
import socket

host = '127.0.0.1'
port = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hello World')
data = s.recv(1024)
s.close()
print 'Received',repr(data)


text:
export const initializeNotifications = () => {
};

export const refreshNotificationToken = () => {
};


text:
class episodeController {
  constructor(mid, $mdDialog) {
    this.mid = mid;
    this.$mdDialog = $mdDialog;
  }

  close() {
    this.$mdDialog.hide();
  }
}

export default /*@ngInject*/ episodeController;


text:
package in.srain.cube.views.ptr.demo.ui.classic;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import in.srain.cube.image.CubeImageView;
import in.srain.cube.image.ImageLoader;
import in.srain.cube.image.ImageLoaderFactory;
import in.srain.cube.mints.base.TitleBaseFragment;
import in.srain.cube.request.JsonData;
import in.srain.cube.request.RequestFinishHandler;
import in.srain.cube.util.LocalDisplay;
import in.srain.cube.views.list.ListViewDataAdapter;
import in.srain.cube.views.list.ViewHolderBase;
import in.srain.cube.views.list.ViewHolderCreator;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.demo.R;
import in.srain.cube.views.ptr.demo.data.DemoRequestData;
import in.srain.cube.views.ptr.demo.ui.MaterialStyleFragment;

public class WithGridView extends TitleBaseFragment {

    private static final int sGirdImageSize = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(12 + 12 + 10)) / 2;
    private ImageLoader mImageLoader;
    private ListViewDataAdapter<JsonData> mAdapter;
    private PtrClassicFrameLayout mPtrFrame;

    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        setHeaderTitle(R.string.ptr_demo_block_grid_view);

        mImageLoader = ImageLoaderFactory.create(getContext());

        final View contentView = inflater.inflate(R.layout.fragment_classic_header_with_gridview, null);
        final GridView gridListView = (GridView) contentView.findViewById(R.id.rotate_header_grid_view);
        gridListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position >= 0) {
                    final String url = mAdapter.getItem(position).optString("pic");
                    if (!TextUtils.isEmpty(url)) {
                        getContext().pushFragmentToBackStack(MaterialStyleFragment.class, url);
                    }
                }
            }
        });

        mAdapter = new ListViewDataAdapter<JsonData>(new ViewHolderCreator<JsonData>() {
            @Override
            public ViewHolderBase<JsonData> createViewHolder() {
                return new ViewHolder();
            }
        });
        gridListView.setAdapter(mAdapter);

        mPtrFrame = (PtrClassicFrameLayout) contentView.findViewById(R.id.rotate_header_grid_view_frame);
        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                updateData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
        // the following are default settings
        mPtrFrame.setResistance(1.7f);
        mPtrFrame.setRatioOfHeaderHeightToRefresh(1.2f);
        mPtrFrame.setDurationToClose(200);
        mPtrFrame.setDurationToCloseHeader(1000);
        // default is false
        mPtrFrame.setPullToRefresh(false);
        // default is true
        mPtrFrame.setKeepHeaderWhenRefresh(true);
        mPtrFrame.postDelayed(new Runnable() {
            @Override
            public void run() {
                // mPtrFrame.autoRefresh();
            }
        }, 100);
        // updateData();
        setupViews(mPtrFrame);
        return contentView;
    }

    protected void setupViews(final PtrClassicFrameLayout ptrFrame) {

    }

    protected void updateData() {

        DemoRequestData.getImageList(new RequestFinishHandler<JsonData>() {
            @Override
            public void onRequestFinish(final JsonData data) {
                mPtrFrame.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.getDataList().clear();
                        mAdapter.getDataList().addAll(data.optJson("data").optJson("list").toArrayList());
                        mPtrFrame.refreshComplete();
                        mAdapter.notifyDataSetChanged();
                    }
                }, 0);
            }
        });
    }

    private class ViewHolder extends ViewHolderBase<JsonData> {

        private CubeImageView mImageView;

        @Override
        public View createView(LayoutInflater inflater) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.with_grid_view_item_image_list_grid, null);
            mImageView = (CubeImageView) view.findViewById(R.id.with_grid_view_item_image);
            mImageView.setScaleType(ScaleType.CENTER_CROP);

            LinearLayout.LayoutParams lyp = new LinearLayout.LayoutParams(sGirdImageSize, sGirdImageSize);
            mImageView.setLayoutParams(lyp);
            return view;
        }

        @Override
        public void showData(int position, JsonData itemData) {
            String url = itemData.optString("pic");
            mImageView.loadImage(mImageLoader, url);
        }
    }
}


text:
package godvile;

/**
 * Created by mark on 24.08.16.
 */

class NotificationString {
    private String string;
    final int wrapSize=40;
    NotificationString(String s){
        StringBuilder sb = new StringBuilder(s);
        int i = 0;
        while (i + wrapSize < sb.length() && (i = sb.lastIndexOf(" ", i + wrapSize)) != -1) { // FIXME: 26.08.16 сделай перенос по словам а не по строчкам
            sb.replace(i, i + 1, "\n");
        }
        string=sb.toString();
    }

    @Override
    public String toString() {
        return string;
    }
}


text:
<?php

function ppal(){

	$iii=(time()%2);

	$ppal=array();

	// Coffees donate
	$ppal[0]="
	<form name=\"_xclick\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" target=\"_blank\">
		<input type=\"hidden\" name=\"cmd\" value=\"_xclick\">
		<input type=\"hidden\" name=\"business\" value=\"marcelloverona@gmail.com\">
		<input type=\"hidden\" name=\"item_name\" value=\"VFront coffee donation\">
		<input type=\"hidden\" name=\"currency_code\" value=\"EUR\">

		<select name=\"amount\" >
			<option value=\"2.00\">1 "._('coffee')."</option>
			<option value=\"4.00\" selected=\"selected\">2 "._('coffees')."</option>
			<option value=\"10.00\">5 "._('coffees')."</option>
			<option value=\"20.00\">10 "._('coffees')."</option>
			<option value=\"40.00\">20 "._('coffees')."</option>
		</select>

		<input type=\"image\" src=\"http://www.vfront.org/img/paypal_bt1.png\" border=\"0\" name=\"submit\" alt=\"Make payments with PayPal - it's fast, free and secure!\">
	</form>

	";

	// Money donate
	$ppal[1]="
	<form name=\"_xclick\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" target=\"_blank\">
		<input type=\"hidden\" name=\"cmd\" value=\"_xclick\">
		<input type=\"hidden\" name=\"business\" value=\"marcelloverona@gmail.com\">
		<input type=\"hidden\" name=\"item_name\" value=\"VFront donation.\">
		<input type=\"hidden\" name=\"currency_code\" value=\"EUR\">
		<input type=\"hidden\" name=\"amount\" value=\"2.00\">
		<input type=\"image\" src=\"http://www.vfront.org/img/paypal_bt_2.png\" border=\"0\" name=\"submit\" alt=\"Make payments with PayPal - it's fast, free and secure!\">
	</form>

	<form name=\"_xclick\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" target=\"_blank\">
		<input type=\"hidden\" name=\"cmd\" value=\"_xclick\">
		<input type=\"hidden\" name=\"business\" value=\"marcelloverona@gmail.com\">
		<input type=\"hidden\" name=\"item_name\" value=\"VFront donation.\">
		<input type=\"hidden\" name=\"currency_code\" value=\"EUR\">
		<input type=\"hidden\" name=\"amount\" value=\"25.00\">
		<input type=\"image\" src=\"http://www.vfront.org/img/paypal_bt_25.png\" border=\"0\" name=\"submit\" alt=\"Make payments with PayPal - it's fast, free and secure!\">
	</form>

	<form name=\"_xclick\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" target=\"_blank\">
		<input type=\"hidden\" name=\"cmd\" value=\"_xclick\">
		<input type=\"hidden\" name=\"business\" value=\"marcelloverona@gmail.com\">
		<input type=\"hidden\" name=\"item_name\" value=\"VFront donation.\">
		<input type=\"hidden\" name=\"currency_code\" value=\"EUR\">
		<div class=\"valuta\"><input type=\"text\" name=\"amount\" value=\"\" id=\"custom_amount\" size=\"6\"> € </div>
		<input type=\"image\" src=\"http://www.vfront.org/img/paypal_bt1.png\" border=\"0\" name=\"submit\" alt=\"Make payments with PayPal - it's fast, free and secure!\">
	</form>
	";

	$ppal[2]="
	<form name=\"_xclick\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" target=\"_blank\">
		<input type=\"hidden\" name=\"cmd\" value=\"_xclick\">
		<input type=\"hidden\" name=\"business\" value=\"marcelloverona@gmail.com\">
		<input type=\"hidden\" name=\"item_name\" value=\"VFront donation\">
		<input type=\"hidden\" name=\"currency_code\" value=\"EUR\">

		<select name=\"amount\" >
			<option value=\"2.00\">2 €</option>
			<option value=\"5.00\" selected=\"selected\">5 €</option>
			<option value=\"10.00\">10 €</option>
			<option value=\"25.00\">25 €</option>
			<option value=\"50.00\">50 €</option>
		</select>

		<input type=\"image\" src=\"http://www.vfront.org/img/paypal_bt1.png\" border=\"0\" name=\"submit\" alt=\"Make payments with PayPal - it's fast, free and secure!\">
	</form>

	";

	return $ppal[$iii];

}

?>


text:
class Rock::PersonAlias < Rock::Base
  self.primary_key = :Id
  self.table_name = 'PersonAlias'
end


text:
<?php
/**
 * User: zhangshize
 * Date: 2016/12/30
 * Time: 下午 3:34
 */

namespace SlimFacades;

class Request extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'request';
    }
}


text:
exopy.measurement.editors.database_access_editor package
===================================================

Submodules
----------

.. toctree::

   editor
   editor_model


text:
"use strict";

var PriceMinisterSite = require("../../../lib/sites/priceminister"),
    cheerio = require("cheerio"),
    siteUtils = require("../../../lib/site-utils");

var VALID_URI = "http://www.priceminister.com/mfp/123/my-video-game#pid=456";
var TRANSLATED_URL = "http://www.priceminister.com/mfp?cid=123&urlname=my-video-game&pid=456&action=advlstmeta";
var INVALID_URI = "http://www.bad.com/123/product";

describe("The PriceMinister Site", function() {

    it("should exist", function() {
        expect(PriceMinisterSite).toBeDefined();
    });

    describe("isSite() function", function() {
        it("should return true for a correct site", function() {
            expect(PriceMinisterSite.isSite(VALID_URI)).toBeTruthy();
        });

        it("should return false for a bad site", function() {
            expect(PriceMinisterSite.isSite(INVALID_URI)).toBeFalsy();
        });
    });

    it("should throw an exception trying to create a new PriceMinisterSite with an incorrect uri", function() {
        expect(function() {
            new PriceMinisterSite(INVALID_URI);
        }).toThrow();
    });

    describe("a new PriceMinister Site", function() {
        var priceminister;

        beforeEach(function() {
            priceminister = new PriceMinisterSite(VALID_URI);
        });

        it("should exist", function() {
            expect(priceminister).toBeDefined();
        });

        it("should return the same URI for getURIForPageData()", function() {
            expect(priceminister.getURIForPageData()).toEqual(TRANSLATED_URL);
        });

        it("should return false for isJSON()", function() {
            expect(priceminister.isJSON()).toBeFalsy();
        });

        describe("with a populated page", function() {
            var $, bad$, price, category, name;

            beforeEach(function() {
                price = 19.99;
                category = siteUtils.categories.VIDEO_GAMES;
                name = "My Video Game";

                $ = cheerio.load(
                    "
" +
                    "
" +
                    "
" + price + " €

" +
                    "
" +
                    "

" + name + "

"
                );
                bad$ = cheerio.load("
Nothin here
");
            });

            it("should return the price when displayed on the page", function() {
                var priceFound = priceminister.findPriceOnPage($);
                expect(priceFound).toEqual(price);
            });

            it("should return -1 when the price is not found", function() {
                var priceFound = priceminister.findPriceOnPage(bad$);
                expect(priceFound).toEqual(-1);
            });

            it("should always return the VIDEO_GAMES category", function() {
                var categoryFound = priceminister.findCategoryOnPage($);
                expect(categoryFound).toEqual(category);
            });

            it("should return the name when displayed on the page", function() {
                var nameFound = priceminister.findNameOnPage($, category);
                expect(nameFound).toEqual(name);
            });

            it("should return null when the name is not displayed on the page", function() {
                var nameFound = priceminister.findNameOnPage(bad$, category);
                expect(nameFound).toEqual(null);
            });

        });
    });

});


text:
package org.apache.rave.portal.web.controller.admin;

import org.apache.rave.portal.model.PortalPreference;
import org.apache.rave.portal.service.PortalPreferenceService;
import org.apache.rave.portal.web.model.PortalPreferenceForm;
import org.apache.rave.portal.web.util.ModelKeys;
import org.apache.rave.portal.web.util.PortalPreferenceKeys;
import org.apache.rave.portal.web.util.ViewNames;
import org.apache.rave.portal.web.validator.PortalPreferenceFormValidator;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.support.SessionStatus;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;

/**
 * Test for {@link PortalPreferenceController}
 */
public class PortalPreferenceControllerTest {

    private PortalPreferenceController controller;
    private PortalPreferenceService service;
    private String validToken;

    @Before
    public void setUp() {
        controller = new PortalPreferenceController();
        service = createMock(PortalPreferenceService.class);
        controller.setPreferenceService(service);
        controller.setFormValidator(new PortalPreferenceFormValidator());
        validToken = AdminControllerUtil.generateSessionToken();
    }

    @Test
    public void testViewPreferences() {
        Model model = new ExtendedModelMap();
        Map<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>();

        expect(service.getPreferencesAsMap()).andReturn(preferenceMap);
        replay(service);

        String view = controller.viewPreferences(null, model);

        assertEquals(ViewNames.ADMIN_PREFERENCES, view);
        assertEquals(preferenceMap, model.asMap().get("preferenceMap"));
        assertFalse(model.containsAttribute("actionresult"));
        assertTrue(model.containsAttribute("topnav"));
        assertTrue(model.containsAttribute("tabs"));

        verify(service);
    }

    @Test

    public void testViewPreferences_afterUpdate() {
        Model model = new ExtendedModelMap();
        Map<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>();

        expect(service.getPreferencesAsMap()).andReturn(preferenceMap);
        replay(service);

        final String action = "update";
        String view = controller.viewPreferences(action, model);

        assertEquals(ViewNames.ADMIN_PREFERENCES, view);
        assertEquals(preferenceMap, model.asMap().get("preferenceMap"));
        assertEquals(action, model.asMap().get("actionresult"));
        assertTrue(model.containsAttribute("topnav"));
        assertTrue(model.containsAttribute("tabs"));

        verify(service);
    }

    @Test
    public void testEditPreferences() {
        Model model = new ExtendedModelMap();

        Map<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>();

        expect(service.getPreferencesAsMap()).andReturn(preferenceMap);
        replay(service);
        String view = controller.editPreferences(model);
        assertEquals(ViewNames.ADMIN_PREFERENCE_DETAIL, view);

        assertTrue(model.asMap().get("preferenceForm") instanceof PortalPreferenceForm);
        assertTrue(model.containsAttribute(ModelKeys.TOKENCHECK));
        assertTrue(model.containsAttribute("topnav"));
        assertTrue(model.containsAttribute("tabs"));
    }

    @Test
    public void testUpdatePreferences_valid() {
        ModelMap model = new ExtendedModelMap();
        PortalPreferenceForm form = new PortalPreferenceForm(new HashMap<String, PortalPreference>());
        final BindingResult errors = new BeanPropertyBindingResult(form, "form");
        SessionStatus sessionStatus = createMock(SessionStatus.class);

        final Set<Map.Entry<String, PortalPreference>> entries = form.getPreferenceMap().entrySet();

        for (Map.Entry<String, PortalPreference> entry : entries) {
            service.savePreference(entry.getValue());
        }
        sessionStatus.setComplete();

        expectLastCall();
        replay(service, sessionStatus);
        String view = controller.updatePreferences(form, errors, validToken, validToken, model, sessionStatus);

        assertEquals("redirect:/app/admin/preferences?action=update", view);
        assertTrue("Model has been cleared", model.isEmpty());

        verify(service, sessionStatus);
    }

    @Test(expected = SecurityException.class)
    public void testUpdatePreferences_invalidToken() {
        ModelMap model = new ExtendedModelMap();
        String invalidToken = AdminControllerUtil.generateSessionToken();
        PortalPreferenceForm form = new PortalPreferenceForm(new HashMap<String, PortalPreference>());
        final BindingResult errors = new BeanPropertyBindingResult(form, "form");
        SessionStatus sessionStatus = createMock(SessionStatus.class);
        sessionStatus.setComplete();

        expectLastCall();
        replay(service, sessionStatus);
        controller.updatePreferences(form, errors, validToken, invalidToken, model, sessionStatus);

        assertFalse("Should not end up here", true);
        verify(service, sessionStatus);
    }

    @Test
    public void testUpdatePreferences_invalidPageSizeValue() {
        ModelMap model = new ExtendedModelMap();
        HashMap<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>();
        PortalPreference pageSizePref = new PortalPreference(PortalPreferenceKeys.PAGE_SIZE, "invalid");
        preferenceMap.put(PortalPreferenceKeys.PAGE_SIZE, pageSizePref);
        PortalPreferenceForm form = new PortalPreferenceForm(preferenceMap);
        final BindingResult errors = new BeanPropertyBindingResult(form, "form");
        SessionStatus sessionStatus = createMock(SessionStatus.class);

        replay(service, sessionStatus);
        String view = controller.updatePreferences(form, errors, validToken, validToken, model, sessionStatus);

        assertEquals(ViewNames.ADMIN_PREFERENCE_DETAIL, view);
        assertTrue(errors.hasErrors());
        assertTrue(model.containsAttribute("topnav"));
        assertTrue(model.containsAttribute("tabs"));
        assertFalse("Model has not been cleared", model.isEmpty());

        verify(service, sessionStatus);
    }

}


text:
ConsequenceStudy
===============

Behavioral analysis tool.

Contributors
------------
Andrew Hood [@andrewhood125](https://github.com/andrewhood125)
Neal Patel [@Patel128](https://github.com/patel128)


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>IVCT</title>
    <scout:include template="head.html" />
    <scout:stylesheet src="res/scout-login-module.less" />
    <scout:script src="res/jquery-all-macro.js" />
    <!--  scout:script src="res/scout-login-module.js" / -->
    <scout:script src="res/nato.ivct.gui-all-login-macro.js" />
    <scout:script src="res/login.js" />
  </head>
  <body>
    <scout:include template="no-script.html" />
    <scout:message style="tag" key="ui.Login" key="ui.LoginFailed" key="ui.User" key="ui.Password" />
  </body>
</html>


text:
package com.xnx3.j2ee.service.impl;

import javax.servlet.http.HttpServletRequest;
import com.xnx3.DateUtil;
import com.xnx3.Lang;
import com.xnx3.j2ee.Global;
import com.xnx3.j2ee.dao.MessageDAO;
import com.xnx3.j2ee.dao.SqlDAO;
import com.xnx3.j2ee.entity.Message;
import com.xnx3.j2ee.entity.MessageData;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.func.Language;
import com.xnx3.j2ee.service.MessageService;
import com.xnx3.j2ee.shiro.ShiroFunc;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.j2ee.vo.MessageVO;

public class MessageServiceImpl implements MessageService {

	private MessageDAO messageDao;
	private SqlDAO sqlDAO;

	public SqlDAO getSqlDAO() {
		return sqlDAO;
	}

	public void setSqlDAO(SqlDAO sqlDAO) {
		this.sqlDAO = sqlDAO;
	}

	public MessageDAO getMessageDao() {
		return messageDao;
	}

	public void setMessageDao(MessageDAO messageDao) {
		this.messageDao = messageDao;
	}

	@Override
	public BaseVO delete(int id) {
		BaseVO baseVO = new BaseVO();
		if(id>0){
			Message m =sqlDAO.findById(Message.class, id);
			if(m!=null){
				m.setIsdelete(Message.ISDELETE_DELETE);
				sqlDAO.save(m);
//				logDao.insert(m.getId(), "MESSAGE_DELETE");
			}else{
				baseVO.setBaseVO(BaseVO.FAILURE, Language.show("message_notFind"));
			}
		}else{
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("message_idFailure"));
		}
		return baseVO;
	}

	@Override
	public BaseVO sendMessage(HttpServletRequest request) {
		BaseVO baseVO = new BaseVO();
		int recipientid = Lang.stringToInt(request.getParameter("recipientid"), 0);
		String content = request.getParameter("content");

		return sendMessage(recipientid, content);
	}

	@Override
	public MessageVO read(int id) {
		MessageVO messageVO = new MessageVO();
		if(id>0){
			Message message = sqlDAO.findById(Message.class, id);
			if(message!=null){
				int userId = ShiroFunc.getUser().getId();
				//查看此信息是此人发的,或者是发送给此人的,此人有权限查看
				if(userId - message.getRecipientid() == 0 || userId - message.getSenderid() == 0){
					//检测此信息是否已被删除
					if(message.getIsdelete() - Message.ISDELETE_DELETE == 0){
						messageVO.setBaseVO(MessageVO.FAILURE, Language.show("message_alreadyDelete"));
					}else{
						//拿到信息的内容
						MessageData messageData = sqlDAO.findById(MessageData.class, id);
						messageVO.setContent(messageData.getContent());

						//如果阅读的人是收信人,且之前没有阅读过,则标注此信息为已阅读
						if(userId - message.getRecipientid() == 0 && message.getState() - Message.MESSAGE_STATE_UNREAD == 0){
							message.setState(Message.MESSAGE_STATE_READ);
							sqlDAO.save(message);
//							logDao.insert(message.getId(), "MESSAGE_READ", messageData.getContent());
						}
						messageVO.setMessage(message);

						//拿到发件人信息
						User senderUser = sqlDAO.findById(User.class, message.getSenderid());

						//检验目标用户状态是否正常,是否被冻结
						if(senderUser.getIsfreeze() - User.ISFREEZE_FREEZE == 0){
							messageVO.setBaseVO(BaseVO.FAILURE, Language.show("message_senderUserFreeze"));
							return messageVO;
						}
						messageVO.setSenderUser(senderUser);

						//拿到收件人信息
						User recipientUser = sqlDAO.findById(User.class, message.getRecipientid());
						messageVO.setRecipientUser(recipientUser);
					}
				}else{
					messageVO.setBaseVO(MessageVO.FAILURE, Language.show("message_notRoleRead"));
				}
			}else{
				messageVO.setBaseVO(BaseVO.FAILURE, Language.show("message_notFind"));
			}
		}else{
			messageVO.setBaseVO(BaseVO.FAILURE, Language.show("message_idFailure"));
		}

		return messageVO;
	}

	@Override
	public BaseVO sendMessage(int recipientid, String content) {
		BaseVO baseVO = new BaseVO();
		User user = ShiroFunc.getUser();
		if(user == null){
			baseVO.setBaseVO(BaseVO.FAILURE, "请先登录");
			return baseVO;
		}
		return sendMessage(user.getId(), recipientid, content);
	}

	public BaseVO sendMessage(int userid, int recipientid, String content){
		BaseVO baseVO = new BaseVO();
		if(recipientid<1){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("message_unknowRecipient"));
			return baseVO;
		}

		if(recipientid == ShiroFunc.getUser().getId()){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("message_notSendOneself"));
			return baseVO;
		}

		if(content == null){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("message_pleaseInputText"));
		}else if(content.length()>Global.MESSAGE_CONTENT_MINLENGTH&&content.length()<Global.MESSAGE_CONTENT_MAXLENGTH) {
			//正常

			//拿到收信人信息
			User recipiendUser = sqlDAO.findById(User.class, recipientid);
			if(recipiendUser == null){
				baseVO.setBaseVO(BaseVO.FAILURE, Language.show("message_sendRecipientNotFind"));
				return baseVO;
			}
			//检验目标用户状态是否正常,是否被冻结
			if(recipiendUser.getIsfreeze() == User.ISFREEZE_FREEZE){
				baseVO.setBaseVO(BaseVO.FAILURE, Language.show("message_sendRecipientUserFreeze"));
				return baseVO;
			}

			Message message = new Message();
			message.setSenderid(ShiroFunc.getUser().getId());
			message.setRecipientid(recipientid);
			message.setTime(DateUtil.timeForUnix10());
			message.setState(Message.MESSAGE_STATE_UNREAD);
			message.setIsdelete(Message.ISDELETE_NORMAL);
			sqlDAO.save(message);
			baseVO.setBaseVO(BaseVO.SUCCESS, message.getId()+"");

			MessageData messageData = new MessageData();
			messageData.setId(message.getId());
			messageData.setContent(content);
			sqlDAO.save(messageData);

			if(messageData.getId()==0){
				baseVO.setBaseVO(BaseVO.FAILURE,Language.show("message_saveFailure"));
			}else{
				//日志记录, MESSAGE_SEND
//				logDao.insert(message.getId(), "MESSAGE_SEND",content);
			}
		}else{
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("message_sizeFailure").replaceAll("\\$\\{min\\}", Global.MESSAGE_CONTENT_MINLENGTH+"").replaceAll("\\$\\{max\\}", Global.MESSAGE_CONTENT_MAXLENGTH+""));
		}

		return baseVO;
	}

	@Override
	public BaseVO sendSystemMessage(int recipientid, String content) {
		return sendMessage(0, recipientid, content);
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include_once(APPPATH.'parser/Parser.php');
include_once(APPPATH.'entity/StockEntity.php');
include_once(APPPATH.'models/Stock.php');
include_once(APPPATH.'helpers/simple_html_dom.php');
include_once(APPPATH.'helpers/AwsHelper.php');

class WantgooStockParser extends Parser{

  private $url ;
  private $logger ;
  private $model ;

  function __construct($url){
    $this->url = $url ;
    $this->logger = Logger::getLogger('rootLogger');
    $this->model = new StockModel();
  }

  function parse(){

    $this->logger->info($this->url);
    $html = file_get_html($this->url);
    $tag = 'tr';
    $elements = $html->find($tag);
    $ranking = 1;
    $stocks = array();

    foreach ($elements as $element) {
      $this->logger->debug(trim($element->plaintext));
      $data = preg_split('/[\s]+/',$element->plaintext);
      // 代碼,股票,成交價,漲跌,漲跌%,周漲跌%,振幅%,最高,最低,成交量,成交值(億),周轉率%,EPS,營益率,營收(%)
      $this->logger->debug($data);
      $stock = new StockEntity();
      if(is_numeric($data[1])){
        $stock->_setRanking($ranking++);
        $stock->_setCode($data[1]);
        $stock->_setName($data[2]);
        $stock->_setPrice($data[3]);
        $stock->_setVarietyPrice($data[4]);
        $stock->_setVarietyRank($data[5]);
        $stock->_setHighest($data[8]);
        $stock->_setLowest($data[9]);
        $stock->_setDiff(abs($data[8]-$data[9]));
        $stock->_setDealAmount($data[10]);
        $stock->_setDealPrice($data[11]);
        $stock->_setDate((int)date('YmdHi'));
        $stock->_setType('all');
        $stock->_setKey();
        array_push($stocks,$stock);
      }
    }

    $result = $this->model->upsert($stocks);
    $this->logger->info('upsert result count = '.$result);
    if($result > 0){
      try {
        $s3 = new AwsHelper();
        $bucket = 'yahoo-b-stock-info';
        $key = 'WantgooStock@'.date('ymdhis');
        $s3->putObject(array('Bucket'=>$bucket,'Key'=>$key,'Body'=>json_encode($stocks)));
      } catch (Exception $e) {
        $this->logger->error($e->getMessage());
        return ;
      }
      $this->logger->info('upload to s3 ok');
    }

  }

}


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('shop', '0004_status_default_status'),
        ('shop', '0006_auto_20170613_1223'),
    ]

    operations = [
    ]


text:
package org.apache.activemq.apollo.broker.protocol;

import org.apache.activemq.apollo.broker.BrokerConnection;
import org.apache.activemq.apollo.broker.Connector;
import org.apache.activemq.apollo.dto.ConnectionStatusDTO;
import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtdispatch.transport.ProtocolCodec;
import org.fusesource.hawtdispatch.transport.Transport;

import java.io.IOException;

/**
 * @author Christian Posta
 */
public class DummyProtocol implements Protocol{
    @Override
    public ProtocolHandler createProtocolHandler() {
        return new DummyProtocolHandler();
    }

    @Override
    public ProtocolCodec createProtocolCodec(Connector connector) {
        return new DummyProtocolCodec();
    }

    @Override
    public boolean isIdentifiable() {
        return true;
    }

    @Override
    public int maxIdentificaionLength() {
        return "CONNECT".length();
    }

    @Override
    public boolean matchesIdentification(Buffer buffer) {
        if (buffer.length < "CONNECT".length()) {
            return false;
        }
        else {
            return buffer.startsWith(Buffer.ascii("CONNECT"));
        }
    }

    @Override
    public String getId() {
        return "dummy-stomp";
    }

    public static class DummyProtocolCodec implements ProtocolCodec {
        @Override
        public void setTransport(Transport transport) {
        }

        @Override
        public Object read() throws IOException {
            return null;
        }

        @Override
        public void unread(byte[] bytes) {
        }

        @Override
        public long getReadCounter() {
            return 0;
        }

        @Override
        public long getLastReadSize() {
            return 0;
        }

        @Override
        public int getReadBufferSize() {
            return 0;
        }

        @Override
        public int getWriteBufferSize() {
            return 0;
        }

        @Override
        public BufferState write(Object o) throws IOException {
            return null;
        }

        @Override
        public BufferState flush() throws IOException {
            return null;
        }

        @Override
        public boolean full() {
            return false;
        }

        @Override
        public long getWriteCounter() {
            return 0;
        }

        @Override
        public long getLastWriteSize() {
            return 0;
        }
    }

    public static class DummyProtocolHandler implements ProtocolHandler{
        @Override
        public String getProtocol() {
            return "dummy-stomp";
        }

        @Override
        public String getSessionId() {
            return null;
        }

        @Override
        public BrokerConnection getConnection() {
            return null;
        }

        @Override
        public ConnectionStatusDTO createConnectionStatus(boolean debug) {
            return null;
        }

        @Override
        public void onTransportCommand(Object o) {
        }

        @Override
        public void onTransportFailure(IOException e) {
        }

        @Override
        public void onTransportConnected() {
        }

        @Override
        public void onTransportDisconnected() {
        }

        @Override
        public void setConnection(BrokerConnection connection) {
        }
    }
}


text:
require 'test_helper'

class ListColumnHelpersTest < ActionView::TestCase
  include ActiveScaffold::Helpers::ListColumnHelpers
  include ActiveScaffold::Helpers::ViewHelpers
  include ::ERB::Util

  def setup
    @column = ActiveScaffold::DataStructures::Column.new(:a, ModelStub)
    @column.form_ui = :select
    @record = stub(:a => 'value_2')
    @config = stub(:list => stub(:empty_field_text => '-', :association_join_text => ', '), :actions => [:list])
    @association_column = ActiveScaffold::DataStructures::Column.new(:b, ModelStub)
    @association_column.stubs(:association).returns(stub(:collection? => true))
  end

  def test_options_for_select_list_ui_for_simple_column
    @column.options[:options] = [:value_1, :value_2, :value_3]
    assert_equal 'Value 2', format_column_value(@record, @column)

    @column.options[:options] = %w(value_1 value_2 value_3)
    assert_equal 'value_2', format_column_value(@record, @column)

    @column.options[:options] = [%w(text_1 value_1), %w(text_2 value_2), %w(text_3 value_3)]
    assert_equal 'text_2', format_column_value(@record, @column)

    @column.options[:options] = [[:text_1, :value_1], [:text_2, :value_2], [:text_3, :value_3]]
    assert_equal 'Text 2', format_column_value(@record, @column)
  end

  def test_association_join_text
    value = [1, 2, 3, 4].map(&:to_s)
    value.each { |v| v.stubs(:to_label).returns(v) }
    assert_equal '1, 2, 3, … (4)', format_association_value(value, @association_column, value.size)
    @config.list.stubs(:association_join_text => ',
')
    assert_equal '1,<br/>2,<br/>3,<br/>… (4)', format_association_value(value, @association_column, value.size)
    @config.list.stubs(:association_join_text => ',
'.html_safe)
    assert_equal '1,
2,
3,
… (4)', format_association_value(value, @association_column, value.size)
  end

  private

  def active_scaffold_config
    @config
  end
end