text:
<?php

namespace App\Helpers\ExerciseConfig;

use App\Exceptions\ExerciseConfigException;
use App\Helpers\EntityMetadata\HwGroupMeta;
use App\Helpers\ExerciseConfig\Validation\EnvironmentConfigValidator;
use App\Helpers\ExerciseConfig\Validation\ExerciseConfigValidator;
use App\Helpers\ExerciseConfig\Validation\ExerciseLimitsValidator;
use App\Helpers\ExerciseConfig\Validation\PipelineValidator;
use App\Model\Entity\Exercise;
use App\Model\Entity\Pipeline as PipelineEntity;

/**
 * Validator which should be used for whole exercise configuration machinery.
 * Rather than for internal validation of structures themselves, this helper
 * is considered only for validation of cross-structures data and references.
 * In here identifications of pipelines can be included or variables and
 * proper types of two joined ports. Also proper environments and hwgroups
 * can be checked here.
 */
class Validator
{
    /**
     * @var ExerciseConfigValidator
     */
    private $exerciseConfigValidator;

    /**
     * @var PipelineValidator
     */
    private $pipelineValidator;

    /**
     * @var ExerciseLimitsValidator
     */
    private $exerciseLimitsValidator;

    /**
     * @var EnvironmentConfigValidator
     */
    private $environmentConfigValidator;

    /**
     * Validator constructor.
     * @param ExerciseConfigValidator $exerciseConfigValidator
     * @param PipelineValidator $pipelineValidator
     * @param ExerciseLimitsValidator $exerciseLimitsValidator
     * @param EnvironmentConfigValidator $environmentConfigValidator
     */
    public function __construct(
        ExerciseConfigValidator $exerciseConfigValidator,
        PipelineValidator $pipelineValidator,
        ExerciseLimitsValidator $exerciseLimitsValidator,
        EnvironmentConfigValidator $environmentConfigValidator
    ) {
        $this->exerciseConfigValidator = $exerciseConfigValidator;
        $this->pipelineValidator = $pipelineValidator;
        $this->exerciseLimitsValidator = $exerciseLimitsValidator;
        $this->environmentConfigValidator = $environmentConfigValidator;
    }

    /**
     * Validate pipeline, all ports either have to have value specified and
     * pointing to variables table or it has to be blank. Value in port is always
     * reference to variables table, actual textual values are not supported here.
     * Types of port and variable in table has to be checked against each other.
     * The relations between ports can be one-to-many from the perspective of
     * output ports. That means one output port can be directed to multiple input
     * ones. There is possibility to have variable which is only aimed to input
     * port, in that case this variables has to be present in variables table of
     * pipeline. Variables whose only reference is in output port are not
     * supported. Validation also checks remote files presence in pipeline
     * database entity.
     * @param PipelineEntity $pipeline
     * @param Pipeline $pipelineConfig
     * @param array|null $pipelineFiles supplementary files of pipeline [ fileName => fileHash]
     *                                  if null, the array is automatically loaded from the pipeline entity
     * @throws ExerciseConfigException
     */
    public function validatePipeline(PipelineEntity $pipeline, Pipeline $pipelineConfig, ?array $pipelineFiles = null)
    {
        $this->pipelineValidator->validate($pipeline, $pipelineConfig, $pipelineFiles);
    }

    /**
     * Validation of exercise environment configuration. Presence of exercise
     * files is checked in all remote-file variables.
     * @param Exercise $exercise
     * @param VariablesTable $table
     * @throws ExerciseConfigException
     */
    public function validateEnvironmentConfig(Exercise $exercise, VariablesTable $table)
    {
        $this->environmentConfigValidator->validate($exercise, $table);
    }

    /**
     * Validation of exercise configuration against environment configurations,
     * that means mainly runtime environment identification. Another checks are
     * made against pipeline, again identification of pipeline is checked,
     * but in here also variables and if pipeline requires them is checked.
     * Validation also checks remote files presence in exercise database entity.
     * Exercise tests are checked against the ones in exercise.
     * @param Exercise $exercise
     * @param ExerciseConfig $config
     * @throws ExerciseConfigException
     */
    public function validateExerciseConfig(Exercise $exercise, ExerciseConfig $config)
    {
        $this->exerciseConfigValidator->validate($config, $exercise);
    }

    /**
     * Validation of exercise limits, limits are defined for tests which comes
     * from exercise database entity and are checked if existing.
     * @param Exercise $exercise
     * @param HwGroupMeta $hwGroupMeta
     * @param ExerciseLimits $limits
     * @throws ExerciseConfigException
     */
    public function validateExerciseLimits(Exercise $exercise, HwGroupMeta $hwGroupMeta, ExerciseLimits $limits)
    {
        $this->exerciseLimitsValidator->validate($exercise, $hwGroupMeta, $limits);
    }
}


text:
class MarkdownProofer
  VERSION = '0.1.1'
end

redpajama_set_name: RedPajamaGithub


text:
package org.strongback.hardware;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.strongback.Executable;
import org.strongback.annotation.ThreadSafe;
import org.strongback.control.Controller;
import org.strongback.control.PIDController;
import org.strongback.control.TalonController;

import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.CANTalon.TalonControlMode;

/**
 * A hardware-based Talon SRX PID controller.
 */
@ThreadSafe
class HardwareTalonController extends HardwareTalonSRX implements TalonController {

    private static final Executable NO_OP = (clock) -> {
    };

    private static final class Gains implements TalonController.Gains {
        private final double p;
        private final double i;
        private final double d;
        private final double feedForward;
        private final double iZone;
        private final double closedLoopRampRate;

        protected Gains(double p, double i, double d, double feedForward, double iZone, double closeLoopRampRate) {
            this.p = p;
            this.i = i;
            this.d = d;
            this.feedForward = feedForward;
            this.iZone = iZone;
            this.closedLoopRampRate = closeLoopRampRate;
        };

        @Override
        public double getP() {
            return p;
        }

        @Override
        public double getI() {
            return i;
        }

        @Override
        public double getD() {
            return d;
        }

        @Override
        public double getFeedForward() {
            return feedForward;
        }
        @Override
        public double getIzone() {
            return iZone;
        }
        @Override
        public double getCloseLoopRampRate() {
            return closedLoopRampRate;
        }
    }

    private double tolerance;
    private volatile int currentProfile = 0;
    private final Set<Integer> profiles = Collections.newSetFromMap(new ConcurrentHashMap<>());

    HardwareTalonController(CANTalon talon, double pulsesPerDegree, double analogTurnsOverVoltageRange) {
        super(talon, pulsesPerDegree, analogTurnsOverVoltageRange);
        profiles.add(currentProfile);
    }

    @Override
    public Controller disable() {
        talon.disable();
        return this;
    }

    @Override
    public Controller enable() {
        talon.enableControl();
        return this;
    }

    @Override
    public boolean isEnabled() {
        return talon.isControlEnabled();
    }

    @Override
    public double getValue() {
        return talon.get();
    }

    @Override
    public double getTarget() {
        double targetPosition = talon.getSetpoint();
        return this.selectedInput.angleInDegreesFromRawPosition(targetPosition);
    }

    @Override
    public TalonController withTarget(double angleInDegrees) {
        talon.set(this.selectedInput.rawPositionForAngleInDegrees(angleInDegrees));
        return this;
    }

    @Override
    public double getTolerance() {
        return this.tolerance;
    }

    @Override
    public TalonController withTolerance(double tolerance) {
        this.tolerance = tolerance;
        return this;
    }

    @Override
    public boolean computeOutput() {
        // The Talon SRX is always computing output, so we don't have to do anything except
        // return whether we're within tolerance ...
        return isWithinTolerance();
    }

    @Override
    public Controller reset() {
        talon.ClearIaccum();
        return this;
    }

    @Override
    public Executable executable() {
        return NO_OP;
    }

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

    @Override
    public ControlMode getControlMode() {
        return ControlMode.valueOf(talon.getControlMode().value);
    }

    @Override
    public TalonController setControlMode(ControlMode mode) {
        talon.changeControlMode(TalonControlMode.valueOf(mode.value()));
        return this;
    }

    @Override
    public TalonController setFeedbackDevice(FeedbackDevice device) {
        super.setFeedbackDevice(device);
        return this;
    }

    @Override
    public TalonController setStatusFrameRate(StatusFrameRate frameRate, int periodMillis) {
        talon.setStatusFrameRateMs(edu.wpi.first.wpilibj.CANTalon.StatusFrameRate.valueOf(frameRate.value()), periodMillis);
        return this;
    }

    @Override
    public TalonController reverseOutput(boolean flip) {
        talon.reverseOutput(flip);
        return this;
    }

    @Override
    public TalonController reverseSensor(boolean flip) {
        super.reverseSensor(flip);
        return this;
    }

    @Override
    public TalonController setForwardSoftLimit(int forwardLimitDegrees) {
        super.setForwardSoftLimit(forwardLimitDegrees);
        return this;
    }

    @Override
    public HardwareTalonController enableForwardSoftLimit(boolean enable) {
        super.enableForwardSoftLimit(enable);
        return this;
    }

    @Override
    public HardwareTalonController setReverseSoftLimit(int reverseLimitDegrees) {
        super.setReverseSoftLimit(reverseLimitDegrees);
        return this;
    }

    @Override
    public HardwareTalonController enableReverseSoftLimit(boolean enable) {
        super.enableReverseSoftLimit(enable);
        return this;
    }

    @Override
    public HardwareTalonController enableLimitSwitch(boolean forward, boolean reverse) {
        super.enableLimitSwitch(forward, reverse);
        return this;
    }

    @Override
    public HardwareTalonController enableBrakeMode(boolean brake) {
        super.enableBrakeMode(brake);
        return this;
    }

    @Override
    public HardwareTalonController setForwardLimitSwitchNormallyOpen(boolean normallyOpen) {
        super.setForwardLimitSwitchNormallyOpen(normallyOpen);
        return this;
    }

    @Override
    public HardwareTalonController setReverseLimitSwitchNormallyOpen(boolean normallyOpen) {
        super.setReverseLimitSwitchNormallyOpen(normallyOpen);
        return this;
    }

    @Override
    public HardwareTalonController withGains(double p, double i, double d) {
        talon.setPID(p, i, d);
        return this;
    }

    @Override
    public HardwareTalonController withGains(double p, double i, double d, double feedForward) {
        talon.setPID(p, i, d);
        talon.setF(feedForward);
        return this;
    }

    @Override
    public HardwareTalonController withGains(double p, double i, double d, double feedForward, int izone, double closeLoopRampRate) {
        talon.setPID(p, i, d);
        talon.setF(feedForward);
        talon.setIZone(izone);
        talon.setCloseLoopRampRate(closeLoopRampRate);
        return this;
    }

    @Override
    public HardwareTalonController withProfile(int profile, double p, double i, double d) {
        return withProfile(profile,p,i,d,0.0,0,0.0);
    }

    @Override
    public HardwareTalonController withProfile(int profile, double p, double i, double d, double feedForward) {
        return withProfile(profile,p,i,d,feedForward,0,0.0);
    }

    @Override
    public HardwareTalonController withProfile(int profile, double p, double i, double d, double feedForward, int izone, double closeLoopRampRate) {
        talon.setPID(p, i, d, feedForward, izone, closeLoopRampRate, profile);
        return this;
    }

    @Override
    public PIDController useProfile(int profile) {
        talon.setProfile(profile);
        this.currentProfile = profile;
        this.profiles.add(profile);
        return this;
    }

    @Override
    public int getCurrentProfile() {
        return currentProfile;
    }

    @Override
    public Set<Integer> getProfiles() {
        return Collections.unmodifiableSet(profiles);
    }

    @Override
    public TalonController.Gains getGainsForCurrentProfile() {
        return new Gains(talon.getP(),talon.getI(), talon.getD(), talon.getF(), talon.getIZone(), talon.getCloseLoopRampRate());
    }

    @Override
    public TalonController setVoltageRampRate(double rampRate) {
        super.setVoltageRampRate(rampRate);
        return this;
    }

    @Override
    public TalonController clearStickyFaults() {
        super.clearStickyFaults();
        return this;
    }

    @Override
    public TalonController setSafetyEnabled(boolean enabled) {
        super.setSafetyEnabled(enabled);
        return this;
    }

    @Override
    public TalonController setExpiration(double timeout) {
        super.setExpiration(timeout);
        return this;
    }
}


text:
import math, random, datetime

graphStart = datetime.datetime(1, 1, 2, 10, 0) # 10:00
graphEnd = datetime.datetime(1, 1, 2, 18, 0)	# 18:00

class basePriceGenerator():
	price = 0.0
	NO_VALUE=-0.00000001

	def getPriceAtTime(self, dt):
		if dt < self.startTime or dt > self.stopTime:
			return self.NO_VALUE
		elif dt == self.startTime:
			return 0.0
		else:
			self.price += (random.choice([-1,1]) * math.log(random.random())/self.beta)
			return self.price

class xjoPriceGenerator(basePriceGenerator):
	startTime = datetime.datetime(1, 1, 2, 10, 0) # 10:00
	stopTime = datetime.datetime(1, 1, 2, 16, 30) # 16:30
	beta = 100

class kospiPriceGenerator(basePriceGenerator):
	startTime = datetime.datetime(1, 1, 2, 11, 0) # 11:00
	stopTime = datetime.datetime(1, 1, 2, 17, 0) # 17:00
	beta = 30

class nikkeiPriceGenerator(basePriceGenerator):
	startTime = datetime.datetime(1, 1, 2, 11, 0) # 11:00
	stopTime = datetime.datetime(1, 1, 2, 17, 30) # 17:30
	beta = 50

xjo = xjoPriceGenerator()
kospi = kospiPriceGenerator()
nikkei = nikkeiPriceGenerator()

dt = graphStart

print "timeofday,xjo,kospi,nikkei"

while dt < graphEnd:
	dt += datetime.timedelta(0,60) # Add one minute
	print "%s,%.8f,%.8f,%.8f" % \
			(dt.time(), \
			xjo.getPriceAtTime(dt), \
			kospi.getPriceAtTime(dt), \
			nikkei.getPriceAtTime(dt))


text:
package io.nats.client.impl;

import io.nats.client.*;
import io.nats.client.api.*;
import io.nats.client.utils.TestBase;
import org.junit.jupiter.api.function.Executable;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import static io.nats.examples.jetstream.NatsJsUtils.printConsumerInfo;
import static io.nats.examples.jetstream.NatsJsUtils.printStreamInfo;
import static org.junit.jupiter.api.Assertions.*;

public class JetStreamTestBase extends TestBase {
    public static final String JS_REPLY_TO = "$JS.ACK.test-stream.test-consumer.1.2.3.1605139610113260000";
    public static final Duration DEFAULT_TIMEOUT = Duration.ofMillis(500);

    public NatsMessage getJsMessage(String replyTo) {
        return new NatsMessage.InternalMessageFactory("sid", "subj", replyTo, 0, false).getMessage();
    }

    // ----------------------------------------------------------------------------------------------------
    // Management
    // ----------------------------------------------------------------------------------------------------
    public static StreamInfo createMemoryStream(JetStreamManagement jsm, String streamName, String... subjects)
            throws IOException, JetStreamApiException {

        StreamConfiguration sc = StreamConfiguration.builder()
                .name(streamName)
                .storageType(StorageType.Memory)
                .subjects(subjects).build();

        return jsm.addStream(sc);
    }

    public static StreamInfo createMemoryStream(Connection nc, String streamName, String... subjects)
            throws IOException, JetStreamApiException {
        return createMemoryStream(nc.jetStreamManagement(), streamName, subjects);
    }

    public static StreamInfo createTestStream(Connection nc) throws IOException, JetStreamApiException {
        return createMemoryStream(nc, STREAM, SUBJECT);
    }

    public static StreamInfo createTestStream(JetStreamManagement jsm) throws IOException, JetStreamApiException {
        return createMemoryStream(jsm, STREAM, SUBJECT);
    }

    public static void debug(JetStreamManagement jsm, int n) throws IOException, JetStreamApiException {
        System.out.println("\n" + n + ". -------------------------------");
        printStreamInfo(jsm.getStreamInfo(STREAM));
        printConsumerInfo(jsm.getConsumerInfo(STREAM, DURABLE));
    }

    public static <T extends Throwable> T assertThrowsPrint(Class<T> expectedType, Executable executable) {
        T t = org.junit.jupiter.api.Assertions.assertThrows(expectedType, executable);
        t.printStackTrace();
        return t;
    }

    // ----------------------------------------------------------------------------------------------------
    // Publish / Read
    // ----------------------------------------------------------------------------------------------------
    public static void jsPublish(JetStream js, String subject, String prefix, int count) throws IOException, JetStreamApiException {
        for (int x = 1; x <= count; x++) {
            String data = prefix + x;
            js.publish(NatsMessage.builder()
                    .subject(subject)
                    .data(data.getBytes(StandardCharsets.US_ASCII))
                    .build()
            );
        }
    }

    public static void jsPublish(JetStream js, String subject, int startId, int count) throws IOException, JetStreamApiException {
        for (int x = 0; x < count; x++) {
            js.publish(NatsMessage.builder().subject(subject).data((dataBytes(startId++))).build());
        }
    }

    public static void jsPublish(JetStream js, String subject, int count) throws IOException, JetStreamApiException {
        jsPublish(js, subject, 1, count);
    }

    public static void jsPublish(Connection nc, String subject, int count) throws IOException, JetStreamApiException {
        jsPublish(nc.jetStream(), subject, 1, count);
    }

    public static void jsPublish(Connection nc, String subject, int startId, int count) throws IOException, JetStreamApiException {
        jsPublish(nc.jetStream(), subject, startId, count);
    }

    public static PublishAck jsPublish(JetStream js) throws IOException, JetStreamApiException {
        Message msg = NatsMessage.builder()
                .subject(SUBJECT)
                .data(DATA.getBytes(StandardCharsets.US_ASCII))
                .build();
        return js.publish(msg);
    }

    public static List<Message> readMessagesAck(JetStreamSubscription sub) throws InterruptedException {
        return readMessagesAck(sub, false);
    }

    public static List<Message> readMessagesAck(JetStreamSubscription sub, boolean noisy) throws InterruptedException {
        List<Message> messages = new ArrayList<>();
        Message msg = sub.nextMessage(Duration.ofSeconds(1));
        while (msg != null) {
            messages.add(msg);
            if (msg.isJetStream()) {
                if (noisy) {
                    System.out.println("ACK " + new String(msg.getData()));
                }
                msg.ack();
            }
            else if (msg.isStatusMessage()) {
                if (noisy) {
                    System.out.println("STATUS " + msg.getStatus());
                }
            }
            else if (noisy) {
                System.out.println("? " + new String(msg.getData()) + "?");
            }
            msg = sub.nextMessage(Duration.ofSeconds(1));
        }
        return messages;
    }

    public static List<Message> readMessages(Iterator<Message> list) {
        List<Message> messages = new ArrayList<>();
        while (list.hasNext()) {
            messages.add(list.next());
        }
        return messages;
    }

    // ----------------------------------------------------------------------------------------------------
    // Validate / Assert
    // ----------------------------------------------------------------------------------------------------
    public static void validateRedAndTotal(int expectedRed, int actualRed, int expectedTotal, int actualTotal) {
        validateRead(expectedRed, actualRed);
        validateTotal(expectedTotal, actualTotal);
    }

    public static void validateTotal(int expectedTotal, int actualTotal) {
        assertEquals(expectedTotal, actualTotal, "Total does not match");
    }

    public static void validateRead(int expectedRed, int actualRed) {
        assertEquals(expectedRed, actualRed, "Read does not match");
    }

    public static void assertSubscription(JetStreamSubscription sub, String stream, String consumer, String deliver, boolean isPullMode) {
        assertEquals(stream, ((NatsJetStreamSubscription)sub).getStream());
        if (consumer == null) {
            assertNotNull(((NatsJetStreamSubscription)sub).getConsumer());
        }
        else {
            assertEquals(consumer, ((NatsJetStreamSubscription) sub).getConsumer());
        }
        if (deliver != null) {
            assertEquals(deliver, ((NatsJetStreamSubscription)sub).getDeliverSubject());
        }

        boolean pm = ((NatsJetStreamSubscription)sub).isPullMode();
        assertEquals(isPullMode, pm);

        // coverage
        assertTrue(sub.toString().contains("isPullMode=" + pm));
    }

    public static void assertSameMessages(List<Message> l1, List<Message> l2) {
        assertEquals(l1.size(), l2.size());
        List<String> data1 = l1.stream()
                .map(m -> new String(m.getData()))
                .collect(Collectors.toList());
        List<String> data2 = l2.stream()
                .map(m -> new String(m.getData()))
                .collect(Collectors.toList());
        assertEquals(data1, data2);
    }

    public static void assertAllJetStream(List<Message> messages) {
        for (Message m : messages) {
            assertIsJetStream(m);
        }
    }

    public static void assertIsJetStream(Message m) {
        assertTrue(m.isJetStream());
        assertFalse(m.isStatusMessage());
        assertNull(m.getStatus());
    }

    public static void assertLastIsStatus(List<Message> messages, int code) {
        int lastIndex = messages.size() - 1;
        for (int x = 0; x < lastIndex; x++) {
            Message m = messages.get(x);
            assertTrue(m.isJetStream());
        }
        assertIsStatus(messages.get(lastIndex), code);
    }

    public static void assertStarts408(List<Message> messages, int count408, int expectedJs) {
        for (int x = 0; x < count408; x++) {
            assertIsStatus(messages.get(x), 408);
        }
        int countedJs = 0;
        int lastIndex = messages.size() - 1;
        for (int x = count408; x <= lastIndex; x++) {
            Message m = messages.get(x);
            assertTrue(m.isJetStream());
            countedJs++;
        }
        assertEquals(expectedJs, countedJs);
    }

    private static void assertIsStatus(Message statusMsg, int code) {
        assertFalse(statusMsg.isJetStream());
        assertTrue(statusMsg.isStatusMessage());
        assertNotNull(statusMsg.getStatus());
        assertEquals(code, statusMsg.getStatus().getCode());
    }

    public static void assertSource(JetStreamManagement jsm, String stream, Long msgCount, Long firstSeq)
            throws IOException, JetStreamApiException {
        sleep(1000);
        StreamInfo si = jsm.getStreamInfo(stream);

        assertConfig(stream, msgCount, firstSeq, si);
    }

    public static void assertMirror(JetStreamManagement jsm, String stream, String mirroring, Long msgCount, Long firstSeq)
            throws IOException, JetStreamApiException {
        sleep(1000);
        StreamInfo si = jsm.getStreamInfo(stream);

        MirrorInfo msi = si.getMirrorInfo();
        assertNotNull(msi);
        assertEquals(mirroring, msi.getName());

        assertConfig(stream, msgCount, firstSeq, si);
    }

    public static void assertConfig(String stream, Long msgCount, Long firstSeq, StreamInfo si) {
        StreamConfiguration sc = si.getConfiguration();
        assertNotNull(sc);
        assertEquals(stream, sc.getName());

        StreamState ss = si.getStreamState();
        if (msgCount != null) {
            assertEquals(msgCount, ss.getMsgCount());
        }
        if (firstSeq != null) {
            assertEquals(firstSeq, ss.getFirstSequence());
        }
    }

    public static void assertStreamSource(MessageInfo info, String stream, int i) {
        String hval = info.getHeaders().get("Nats-Stream-Source").get(0);
        String[] parts = hval.split(" ");
        assertEquals(stream, parts[0]);
        assertEquals("" + i, parts[1]);

    }

}


text:
package com.ducetech.framework.security;

import com.ducetech.framework.cons.GlobalConstant;
import com.ducetech.framework.context.WebContext;
import com.ducetech.framework.util.ExtStringUtil;
import com.ducetech.framework.web.annotation.IgnoreSecurity;
import org.apache.shiro.authz.UnauthorizedException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * Created by lenzhao on 17-2-2.
 */
public class SecurityAspect {

    private static final String DEFAULT_TOKEN_NAME = "X-Token";

    private TokenManager tokenManager;
    private String tokenName;

    public void setTokenManager(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    public void setTokenName(String tokenName) {
        if (ExtStringUtil.isBlank(tokenName)) {
            tokenName = DEFAULT_TOKEN_NAME;
        }
        this.tokenName = tokenName;
    }

    public Object execute(ProceedingJoinPoint pjp) throws Throwable {
        String path = "";
        if (null != WebContext.getRequest()) {
            path = WebContext.getRequest().getServletPath();
        }
        if (!ExtStringUtil.isBlank(path) && path.startsWith(GlobalConstant.API_PATH_PREFIX)) {
            // 从切点上获取目标方法
            MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
            Method method = methodSignature.getMethod();
            // 若目标方法忽略了安全性检查,则直接调用目标方法
            if (method.isAnnotationPresent(IgnoreSecurity.class)) {
                return pjp.proceed();
            }
            // 从 request header 中获取当前 token
            String token = WebContext.getRequest().getHeader(tokenName);
            // 检查 token 有效性
            if (ExtStringUtil.isBlank(token) || !tokenManager.checkToken(token)) {
                String message = String.format("token [%s] is invalid", token);
                throw new UnauthorizedException(message);
            }
        }
        // 调用目标方法
        return pjp.proceed();
    }
}


text:
from django.template.loader import render_to_string
from feincms.content.medialibrary.models import MediaFileContent as BaseMediaFileContent

class MediaFileContent(BaseMediaFileContent):
    """Add some region specific rendering options."""
    class Meta(BaseMediaFileContent.Meta):
        abstract = True

    def render(self, **kwargs):
        ctx = {'content': self}
        ctx.update(kwargs)
        template_names = [
            'content/mediafile/%s/%s_%s.html' % (self.region, self.mediafile.type, self.type),
            'content/mediafile/%s/%s.html' % (self.region, self.mediafile.type),
            'content/mediafile/%s/%s.html' % (self.region, self.type),
            'content/mediafile/%s/default.html' % self.region,

            'content/mediafile/%s_%s.html' % (self.mediafile.type, self.type),
            'content/mediafile/%s.html' % self.mediafile.type,
            'content/mediafile/%s.html' % self.type,
            'content/mediafile/default.html',
        ]
        ctx_inst = kwargs.get('context')
        return render_to_string(template_names, ctx, context_instance=ctx_inst)


text:
using System.Linq;
using System.Xml.Linq;
using System;

namespace EAAddinFramework.Utils
{
    public class EaScript
    {
        // Script t_script
        // ScriptID         ID, auto generated)
        // ScriptCategory   Group:  "3955A83E-9E54-4810-8053-FACC68CD4782"
        //                  Script: "605A62F7-BCD0-4845-A8D0-7DC45B4D2E3F"
        // ScriptName       GUID of Script or Group
        // ScriptAuthor     Group:  free
        //                  Script: GUID as Group the script belongs to (JOIN script with GROUP)
        // Notes:           <Script Name =".." Type="Internal" Language="VBScript"/>
        //                  <Group Type="Normal" Notes=""/>
        // Script:          The Script itself
        //                  The Group Name
        // Script Category of a Script
        const string ScriptCategory = "605A62F7-BCD0-4845-A8D0-7DC45B4D2E3F";

        int _id;
        string _groupGuid;  // the group / author of the Script
        string _name;    // the name of the Script
        string _type;    // VBScript, JavaScript, JScript
        string _language;
        string _code; // the script itself
        Model _model;

        #region Constructor
        public EaScript(Model model, string name, string type, string language, string groupGuid, string code)
        {
            Init(model, name, type, language, groupGuid, code);
        }
        // ReSharper disable once UnusedMember.Global
        public EaScript(Model model, string name, string type, string language, string code)
        {
            Init(model, name, type, language, "", code);
        }

        private void Init(Model model, string name, string type, string language, string groupGuid, string code)
        {
            _groupGuid = groupGuid;
            _name = name;
            _type = type;
            _language = language;
            _model = model;
            _code = code;

        }
        #endregion

        private bool Exists()
        {
            GetInfo();
            return (_id > 0);
        }
        public void Save()
        {
            string notes = $" '<Script Name=\"{_name}\" Type=\"{ _type}\" Language=\"{_language}\" Notes=\"\"/>' ";
            if (Exists())
            {

                string sqlUpdate = "update t_script set " +
                                            $"script = '{_model.EscapeSqlString(_code)}' " +
                                            $", notes = {notes} "  +
                                    " where ScriptID = " + _id;
                _model.ExecuteSql(sqlUpdate);
            }
            else
            {

                string guid = "{" + Guid.NewGuid() + "}";
                string sql = "insert into t_script (ScriptCategory, ScriptAuthor, ScriptName, Notes, Script) " +
                        @" Values (" +
                                   $"'{ScriptCategory}', " +
                                   $"'{_groupGuid}', " +
                                   $"'{guid}', " +
                                   $"{notes}, " +
                                   $"'{_model.EscapeSqlString(_code)}' )";
                _model.ExecuteSql(sql);
                // update script information
                GetInfo();
            }
        }
        /// <summary>
        /// getInfo from script (ID, groupName, groupGuid)
        /// <para/> It get's only one Script (The same ScriptName could be in more than one ScriptGroup)
        /// </summary>
        void GetInfo()
        {
            // check if author (Group of Script) is the expected
            string sqlWhereScriptGroup = "";
            if (!string.IsNullOrEmpty(_groupGuid) )
            {
                sqlWhereScriptGroup = $" AND s.[ScriptAuthor] = '{_groupGuid}'";
            }

            string sql = "select s.[ScriptID], s.[ScriptName] as ScriptGuid, grp.[ScriptID] as GroupID, grp.[Script] as GroupName, grp.[ScriptName] as GroupGuid" +
                             "  from t_script s " +
                             "       inner join t_script grp on s.ScriptAuthor = grp.ScriptName " +
                             "  where s.Script like '%EA-Matic%' AND " +
                             $"  s.Notes like '<Script Name=\"{_name}\"*' " +
                             sqlWhereScriptGroup;
            // run query into XDocument to proceed with LinQ
            string xml = _model.SqlQueryNative(sql);
            var x = new XDocument(XDocument.Parse(xml));

            // get scriptID
            var scriptIdNode = x.Descendants("ScriptID").FirstOrDefault();
            if (scriptIdNode == null) return;
            _id = (int)scriptIdNode;

            // get groupName
            var scriptGroupNameNode = x.Descendants("GroupName").FirstOrDefault();
            if (scriptGroupNameNode == null) return;

            // get groupName
            var scriptGroupGuidNode = x.Descendants("GroupGuid").FirstOrDefault();
            if (scriptGroupGuidNode == null) return;
            _groupGuid = scriptGroupGuidNode.Value;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Asylo: asylo/util Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="/favicons/favicon.ico" rel="shortcut icon" type="image/x-icon"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Asylo

asylo

util

util Directory Reference

Files

file  	cleansing_types.h [code]

file  	error_space.h [code]

file  	logging.h [code]

file  	posix_error_matchers.h [code]

file  	posix_error_space.h [code]

file  	posix_errors.h [code]

file  	proto_flag.h [code]

file  	status.h [code]

file  	status_helpers.h [code]

file  	status_macros.h [code]

file  	statusor.h [code]


text:
<?php

namespace ForkCMS\Modules\Pages\Installer;

use Doctrine\ORM\Query\ResultSetMapping;
use ForkCMS\Modules\Extensions\Domain\Module\ModuleInstaller;
use ForkCMS\Modules\Extensions\Domain\ThemeTemplate\ThemeTemplate;
use ForkCMS\Modules\Frontend\Domain\Meta\Meta;
use ForkCMS\Modules\Internationalisation\Domain\Locale\InstalledLocale;
use ForkCMS\Modules\Internationalisation\Domain\Locale\Locale;
use ForkCMS\Modules\Internationalisation\Domain\Translation\TranslationKey;
use ForkCMS\Modules\Pages\Backend\Actions\ModuleSettings;
use ForkCMS\Modules\Pages\Backend\Actions\PageAdd;
use ForkCMS\Modules\Pages\Backend\Actions\PageCopyToOtherLocale;
use ForkCMS\Modules\Pages\Backend\Actions\PageDelete;
use ForkCMS\Modules\Pages\Backend\Actions\PageEdit;
use ForkCMS\Modules\Pages\Backend\Actions\PageIndex;
use ForkCMS\Modules\Pages\Backend\Ajax\PageMove;
use ForkCMS\Modules\Pages\DependencyInjection\PagesRouteLoader;
use ForkCMS\Modules\Pages\Domain\Page\Page;
use ForkCMS\Modules\Pages\Domain\Revision\Command\CreateRevision;
use ForkCMS\Modules\Pages\Domain\Revision\MenuType;
use ForkCMS\Modules\Pages\Domain\Revision\Revision;
use ForkCMS\Modules\Pages\Domain\RevisionBlock\RevisionBlock;
use ForkCMS\Modules\Pages\Frontend\Widgets\Sitemap;

final class PagesInstaller extends ModuleInstaller
{
    public const IS_REQUIRED = true;

    public function preInstall(): void
    {
        $this->createTableForEntities(Page::class, Revision::class, RevisionBlock::class);
    }

    public function install(): void
    {
        $this->importTranslations(__DIR__ . '/../assets/installer/translations.xml');
        $this->createBackendPages();
        $this->configureBackendAjaxActions();
        $this->createFrontendPages();
        $this->defaultModuleSettings();
    }

    private function createBackendPages(): void
    {
        $this->getOrCreateBackendNavigationItem(
            label: TranslationKey::label('Pages'),
            slug: PageIndex::getActionSlug(),
            selectedFor: [
                PageAdd::getActionSlug(),
                PageEdit::getActionSlug(),
                PageDelete::getActionSlug(),
                PageCopyToOtherLocale::getActionSlug(),
            ],
            sequence: 1,
        );
        $this->getOrCreateBackendNavigationItem(
            TranslationKey::label('Pages'),
            ModuleSettings::getActionSlug(),
            $this->getModuleSettingsNavigationItem()
        );
    }

    private function createFrontendPages(): void
    {
        /** @var Locale[] $locales */
        $locales = $this->getRepository(InstalledLocale::class)->findInstalledLocales();
        $this->createPage($locales, 'lbl.Home', MenuType::MAIN);
        $this->createPage($locales, 'lbl.Disclaimer', MenuType::FOOTER);
        $this->createPage(
            $locales,
            'lbl.Sitemap',
            MenuType::FOOTER,
            callback: function (Locale $locale, CreateRevision $revision): void {
                $revision->addBlock('main', $this->getOrCreateFrontendBlock(Sitemap::getModuleBlock()->getName()));
            }
        );
        $this->setPagesAutoIncrement(Page::PAGE_ID_404);
        $this->createPage($locales, '404', MenuType::ROOT);
        $this->setPagesAutoIncrement(Page::PAGE_ID_START);
    }

    /**
     * @param Locale[] $locales
     * @param callable(Locale, CreateRevision)|null $createRevision
     */
    public function createPage(
        array $locales,
        string $title,
        MenuType $type,
        ?Page $parentPage = null,
        ?Page $page = null,
        ?callable $callback = null,
    ): Page {
        foreach ($locales as $locale) {
            if ($page === null) {
                $page = new Page($locale);
            }
            $revision = new CreateRevision($page, $locale, false);
            $revision->title = $this->trans($locale, $title);
            $revision->parentPage = $parentPage;
            $revision->meta = Meta::forName($title);
            $revision->themeTemplate = $this->entityManager->getReference(ThemeTemplate::class, 1);
            $revision->type = $type;
            $revision->settings['navigation_title'] = $title;

            if ($callback !== null) {
                $callback($locale, $revision);
            }

            $this->dispatchCommand($revision);
        }

        return $page;
    }

    private function setPagesAutoIncrement(int $startValue): void
    {
        $this->entityManager->createNativeQuery(
            'ALTER TABLE pages__page AUTO_INCREMENT=' . $startValue,
            new ResultSetMapping()
        )->execute();
    }

    private function configureBackendAjaxActions(): void
    {
        $this->allowGroupToAccessModuleAjaxAction(PageMove::getAjaxActionSlug()->asModuleAction());
    }

    private function defaultModuleSettings(): void
    {
        $this->setSetting('enabled_extensions', [PagesRouteLoader::FORMAT_DEFAULT]);
    }
}


text:
@interface ListAroundViewController : RootViewController<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) NSString *appendDownloadStr;
@property (nonatomic,assign) NSInteger pointing;

@end


text:
package gocql // import "github.com/gocql/gocql"

// TODO(tux21b): write more docs.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<link rel="stylesheet" type="text/css" media="print"
  href="branding/css/print.css"/>

<title>Project Status</title>

Subversion Project Status

Here is information about upcoming and past releases.  Each release
goes through a stabilization phase as described in
the Hacker's Guide to
Subversion.
The CHANGES file contains an overview of what's new in each release.
Releases are always source tarballs; binary package updates for
various OS's generally follow the source tarball by a few days.

For information about what features are being worked on, and how we
coordinate features with releases, please see the roadmap page.

Upcoming

Subversion 1.6.0 (future):
    Feature and bugfix release.

    See open issues marked for 1.6 or 1.6-consider.

Subversion 2.0.0 (future):
    Feature and compatibility-affecting release.

    See open issues under consideration for 2.0
    (absolutely not commitments, and likely to change).

Older Releases

Information about older releases is located on a separate page.


text:
package org.aeonbits.owner;

import java.util.HashSet;
import java.util.Set;

public class SystemPropertiesHelper {

    private Set<String> sysProps = new HashSet<String>();

    public void setProperty(String key, String val) {
        System.setProperty(key, val);
        sysProps.add(key);
    }

    public void cleanProperty(String key) {
        System.clearProperty(key);
        sysProps.remove(key);
    }

    public void cleanNonDefaultSysProps() {
        for (String prop : sysProps) {
            System.clearProperty(prop);
        }
        sysProps.clear();
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sleuthkit.autopsy.timeline;

import javafx.scene.control.ListCell;
import javafx.scene.text.Text;

/**
 *
 */
class WrappingListCell extends ListCell<String> {

    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (item == null || isEmpty()) {
            setGraphic(null);
        } else {
            Text text = new Text(item);
            text.wrappingWidthProperty().bind(getListView().widthProperty().subtract(20));
            setGraphic(text);
        }
    }

}


text:
^title Program Structure

Magpie programs are stored in plain text files with a <tt>.mag</tt> file extension. Magpie does not compile ahead of time: programs are interpreted directly from source, from top to bottom like a typical scripting language.

## Comments

Comments are as in C, C++, Java, etc.:

    :::magpie
    some code // This is a line comment.
    // A line comment ends at the end of the line.

    some more /* This is a block comment. */ code code

    /* Block comments
       can span multiple lines. */

## Names

Magpie is more ended when it comes to names than most other languages. Regular identifiers, used for things like [variables](expressions/variables.html) and [messages](expressions/messages.html) can consist of letters, numbers, underscores, and even many punctuation characters. These are all valid names:

    :::magpie
    hi
    +
    using-hyphens
    numb3r5_r_0k_2
    even_!$%_this_^&*_is_<>=_valid
    $%^*

### Whitespace

This flexibility has a side effect that might trip you up at first (but I
hope only at first): whitespace must be used to separate names, operators, and
literals. These examples will not be parsed like they would be in other
languages:

    a+b
    true==false
    count=3

Each line here is actually a single identifier. The solution is to make sure to
separate names with spaces, like `a + b`.

Note that the syntax highlighting is actually wrong in the examples here. Sorry. If you've got skill at hacking Pygments lexers, feel free to lend a hand.

## Newlines

Like many scripting languages, newlines are significant in Magpie and are used to separate expressions. You can keep your semicolons safely tucked away.

    :::magpie
    // Two expressions:
    print("hi")
    print("bye")

To make things easier, Magpie will ignore a newline in any place where it
doesn't make sense. Specifically, that means newlines following a comma (`,`),
colon (`:`), operator (`+`, `-`, etc.), backtick (\`</code>), arrow (`->`), or conjunction (`and` or `or`) will be discarded:

    :::magpie
    var a = 1,
            2 // a will be the tuple (1, 2).

    var b = 1 +
            2 // b will be 3.

    var c = true and
            false // c will be false.

If you specifically want to ignore a newline where it otherwise *would* separate two expressions, you can end the line with a backslash (`\`):

    :::magpie
    var a = foo
    bar()
    // Sets a to foo then calls bar()

    var a = foo \
    bar()
    // Equivalent to:
    // var a = foo bar()

## Precedence

Magpie's syntax has fewer distinct levels of precedence than most languages. Many constructs start with a unique keyword (i.e. `var`, `class`, `if`, etc.) so don't need special precedence rules. For the core expression syntax, the precendence levels (from loosest to tightest) are:

1. Assigment (`=`)
2. Tuples and records (`,`)
3. Conjunctions (`and`, `or`)
4. Operators (`+`, `-`, `?$!`, etc.)
5. Messages (`print(foo)`, `list count`, etc.)

Some examples will clarify. The comment after each line is how the parser interprets that expression:

    :::magpie
    a = b, c            // a = (b, c)
    a and b, c or d     // (a and b), (c or d)
    a or b + c          // a or (b + c)
    a b + c             // (a b) + c
    a = b c, d - e or f // a = ((b c), ((d - e) or f))

Parentheses can be used for grouping to override this as you'd expect:

    :::magpie
    a or b + c    // a or (b + c)
    (a or b) + c  // (a or b) + c

Tuples and records exist at the same precedence level, so cannot be mixed:

    1, 2, 3           // a tuple
    a: 1, b: 2, c:, 3 // a record
    a: 1, 2           // bad: need a field name before "2"
    1, a: 2           // bad: not expecting field name in tuple

To mix them together, use parentheses:

    a: (1, 2) // ok: a record with one field that's a tuple
    1, (a: 2) // ok: a tuple whose second field is a record


text:
/** Type declaration for ambient System. */
declare var System: any;


text:
package com.mercadopago.android.px.internal.util;

import android.support.annotation.NonNull;
import com.mercadopago.android.px.addons.model.EscValidationData;
import com.mercadopago.android.px.addons.model.SecurityValidationData;
import com.mercadopago.android.px.internal.core.ProductIdProvider;
import com.mercadopago.android.px.model.internal.PaymentConfiguration;
import java.math.BigDecimal;

public final class SecurityValidationDataFactory {

    private SecurityValidationDataFactory() {
    }

    public static SecurityValidationData create(@NonNull final ProductIdProvider productIdProvider,
        @NonNull final BigDecimal totalAmount, @NonNull final PaymentConfiguration paymentConfiguration) {
        final String productId = productIdProvider.getProductId();
        final String customOptionId = paymentConfiguration.getCustomOptionId();
        final boolean isCard = paymentConfiguration.isCard();
        final EscValidationData escValidationData = new EscValidationData.Builder(customOptionId, isCard).build();
        return new SecurityValidationData.Builder(productId).putParam("amount", totalAmount)
            .setEscValidationData(escValidationData).build();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 330340 $ -->

<book xml:id="book.mqseries" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <title>mqseries</title>

 <!-- {{{ preface -->
 <preface xml:id="intro.mqseries">
  &reftitle.intro;
  <simpara>
   This extension aims to provide an interface for communicating with IBMs
   WebSphere MQ series Queue managers.
  </simpara>
  <simpara>
   The interface mimics the C-API client interface of WebSphere MQ Series as
   close as possible. Using the same naming conventions and possibilities of the
   C-API. In order to understand the workings of this extension some level of
   understanding the C-API is required.
  </simpara>
  <simpara>
   For MQ-options, MQ-structures, MQ-results etc. please read the WebSphere MQ
   Application Programming Guide and WebSphere MQ Application Programming
   Reference.
  </simpara>
 </preface>
 <!-- }}} -->

 &reference.mqseries.setup;
 &reference.mqseries.constants;
 &reference.mqseries.reference;

</book>

<!-- Keep this comment at the end of the file
 Local variables:
 mode: sgml
 sgml-omittag:t
 sgml-shorttag:t
 sgml-minimize-attributes:nil
 sgml-always-quote-attributes:t
 sgml-indent-step:1
 sgml-indent-data:t
 indent-tabs-mode:nil
 sgml-parent-document:nil
 sgml-default-dtd-file:"~/.phpdoc/manual.ced"
 sgml-exposed-tags:nil
 sgml-local-catalogs:nil
 sgml-local-ecat-files:nil
 End:
 vim600: syn=xml fen fdm=syntax fdl=2 si
 vim: et tw=78 syn=sgml
 vi: ts=1 sw=1
-->


text:
layout: page
title: Twin Temple Electronics Show
date: 2016-05-24
author: Kelly Barker
tags: weekly links, java
status: published
summary: Morbi viverra semper quam in.
banner: images/banner/wedding.jpg
booking:
  startDate: 02/16/2019
  endDate: 02/18/2019
  ctyhocn: HLGTXHX
  groupCode: TTES
published: true
---
Aliquam vitae purus pretium, consequat urna ac, mollis sem. Aenean sit amet malesuada sem. Morbi sit amet varius metus. Quisque quis eleifend tortor, rutrum aliquet ipsum. Sed hendrerit orci velit, ut pharetra libero tempor nec. Quisque hendrerit faucibus tempus. Vivamus tincidunt tincidunt rutrum. Pellentesque feugiat tincidunt quam, ac mattis magna aliquam ac. Nulla vestibulum vulputate mauris. Morbi et enim lobortis, malesuada ante et, accumsan orci. Nam at laoreet ex, id suscipit ligula. Suspendisse potenti. Nunc at felis vel sem sodales condimentum. Phasellus consectetur congue sem, ut congue odio. Vestibulum vulputate facilisis nisi, in lobortis lectus feugiat tempus.
Morbi sodales tempus gravida. Nunc sapien urna, elementum ac massa eget, mattis accumsan enim. Pellentesque eget cursus nisi, sed rhoncus ipsum. Nullam laoreet nec tortor sit amet mollis. Curabitur imperdiet quis arcu non accumsan. Donec porta ex eget velit consequat, non vulputate ipsum laoreet. Maecenas pellentesque pellentesque mauris in aliquet. Aliquam ac orci eget lorem venenatis euismod ac a turpis.

1 Sed congue odio ac risus aliquam placerat
1 Donec in leo ut enim ultricies facilisis
1 Vivamus efficitur nisi vitae neque rhoncus luctus
1 Aliquam ornare dolor vitae lacus elementum, eget volutpat magna accumsan.

Quisque vitae quam mattis, lacinia purus laoreet, tempus est. Ut non urna nunc. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas mollis leo sed turpis tincidunt, id hendrerit ligula viverra. Phasellus laoreet porttitor mattis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ultrices porta dolor, quis tincidunt nulla vestibulum et. Donec ornare, odio eget mollis feugiat, ipsum nisi varius ante, sed consectetur tortor nisl sit amet diam. Quisque feugiat gravida convallis.


text:
class SkCanvas;

namespace cc {

class LayerPainter;

// This class records the contentRect into an SkPicture. Subclasses, provide
// different implementations of tile updating based on this recorded picture.
// The BitmapSkPictureContentLayerUpdater and
// FrameBufferSkPictureContentLayerUpdater are two examples of such
// implementations.
class SkPictureContentLayerUpdater : public ContentLayerUpdater {
public:
    class Resource : public LayerUpdater::Resource {
    public:
        Resource(SkPictureContentLayerUpdater*, scoped_ptr<PrioritizedResource>);
        virtual ~Resource();

        virtual void update(ResourceUpdateQueue&, const gfx::Rect& sourceRect, const gfx::Vector2d& destOffset, bool partialUpdate, RenderingStats&) OVERRIDE;

    private:
        SkPictureContentLayerUpdater* updater() { return m_updater; }

        SkPictureContentLayerUpdater* m_updater;
    };

    static scoped_refptr<SkPictureContentLayerUpdater> create(scoped_ptr<LayerPainter>);

    virtual scoped_ptr<LayerUpdater::Resource> createResource(PrioritizedResourceManager*) OVERRIDE;
    virtual void setOpaque(bool) OVERRIDE;

protected:
    explicit SkPictureContentLayerUpdater(scoped_ptr<LayerPainter>);
    virtual ~SkPictureContentLayerUpdater();

    virtual void prepareToUpdate(const gfx::Rect& contentRect, const gfx::Size& tileSize, float contentsWidthScale, float contentsHeightScale, gfx::Rect& resultingOpaqueRect, RenderingStats&) OVERRIDE;
    void drawPicture(SkCanvas*);
    void updateTexture(ResourceUpdateQueue& queue, PrioritizedResource* texture, const gfx::Rect& sourceRect, const gfx::Vector2d& destOffset, bool partialUpdate);

    bool layerIsOpaque() const { return m_layerIsOpaque; }

private:
    // Recording canvas.
    SkPicture m_picture;
    // True when it is known that all output pixels will be opaque.
    bool m_layerIsOpaque;
};

} // namespace cc
#endif  // CC_SKPICTURE_CONTENT_LAYER_UPDATER_H_


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'

import Logo from './getthroughit_logo.jpg'
import UserNavLink from '../containers/UserNavLink'
import { HOME } from '../routes'

class Navbar extends Component {
  render() {
    return (
      <header className="navbar nav-default">
      <Link to={HOME} className="navbar-section App-logo">
        <img className="navbar-brand" src={Logo} />
      </Link>
      <UserNavLink />
      </header>
    )
  }
}

export default Navbar


text:
package org.hawkular.client.android.push;

import org.hawkular.client.android.BuildConfig;

/**
 * Push constants.
 *
 * Contains constants used for push notifications configuration.
 */
final class PushConfiguration {
    private PushConfiguration() {
    }

    public static final String NAME = "hawkular";

    public static final class Ups {
        private Ups() {
        }

        public static final String URL = BuildConfig.UPS_URL;
        public static final String SECRET = BuildConfig.UPS_SECRET;
        public static final String VARIANT = BuildConfig.UPS_VARIANT;
    }

    public static final class Fcm {
        private Fcm() {
        }

        public static final String SENDER = BuildConfig.FCM_SENDER;
        public static final String API_KEY = BuildConfig.FCM_API_KEY;
        public static final String APPLICATION_ID = BuildConfig.FCM_APPLICATION_ID;
        public static final String DATABASE_URL = BuildConfig.FCM_DATABASE_URL;
        public static final String STORAGE_BUCKET = BuildConfig.FCM_STORAGE_BUCKET;
    }
}


text:
(function () {
    'use strict';

    angular.module('motech-server')
        .directive('progressBar', progressBar);

    progressBar.$inject = ['ServerStatusService'];
    function progressBar(ServerStatusService) {
        return {
            restrict: 'EA',
            replace: true,
            templateUrl: '/server/status/status.progress-bar.html',
            link: function (scope, element, attrs) {
                var percentage = 0;

                scope.$on('motech.statusCheck.start', setStartupPercentage);
                scope.$on('motech.statusCheck.update', setStartupPercentage);
                scope.$on('motech.statusCheck.stop', setStartupPercentage);

                function setStartupPercentage() {
                    if(ServerStatusService.running || ServerStatusService.errors && ServerStatusService.errors.length < 1) {
                        element.removeClass('ng-hide');
                        percentage = (ServerStatusService.startedPercentage) ? ServerStatusService.startedPercentage : 0;
                        element.find('.progress-bar').text(percentage + '%').css({width: percentage + '%'}).attr('aria-valuenow', percentage);
                        if (ServerStatusService.errors.length > 0) {
                            element.find('.progress-bar').removeClass('active progress-bar-striped').addClass('progress-bar-danger');
                        }
                    } else {
                        element.addClass('ng-hide');
                    }
                }
            }
        };
    }

})();


text:
layout: post
title: 'Getting Started with Activity & Fragment Transitions (part 1)'
date: 2014-12-04
permalink: /2014/12/activity-fragment-transitions-in-android-lollipop-part1.html
related: ['/2013/08/fragment-transaction-commit-state-loss.html',
    '/2013/04/retaining-objects-across-config-changes.html',
    '/2016/11/introduction-to-icon-animation-techniques.html']
style: |
    .framed-nexus6-port {
      background: transparent url(/assets/images/nexus6_frame.png) no-repeat
      scroll top left;
      padding-top: 71px;
      padding-right: 33px;
      padding-bottom: 50px;
      padding-left: 48px;
      overflow: hidden;
    }

    .framed-nexus6-port,
    .framed-nexus6-port video,
    .framed-nexus6-port img {
      width: 216px;
      height: 384px;
    }

    .nexus6-figure {
      width: 290px;
      margin-right: 35px;
      float: right;
    }
script: |
    function playPause(figureName) {
      var myVideo = document.getElementById(figureName);
      myVideo.load();
      myVideo.play();
    }
updated: '2014-03-11'
---

This post gives a brief overview of `Transition`s and introduces the new [Activity & Fragment transition APIs][customizeActivityTransitions] that were added in Android 5.0 Lollipop. This is the first of a series of posts I will be writing on the topic:

* **Part 1:** [Getting Started with Activity & Fragment Transitions][part1]
* **Part 2:** [Content Transitions In-Depth][part2]
* **Part 3a:** [Shared Element Transitions In-Depth][part3a]
* **Part 3b:** [Postponed Shared Element Transitions][part3b]
* **Part 3c:** Implementing Shared Element Callbacks (_coming soon!_)
* **Part 4:** Activity & Fragment Transition Examples (_coming soon!_)

Until I write part 4, an example application demonstrating some advanced activity transitions is available [here](https://github.com/alexjlockwood/activity-transitions).

We begin by answering the following question: what is a `Transition`?

### What is a `Transition`?

Activity and Fragment transitions in Lollipop are built on top of a relatively new feature in Android called `Transition`s. Introduced in KitKat, the transition framework provides a convenient API for animating between different UI states in an application. The framework is built around two key concepts: _scenes_ and _transitions_. A scene defines a given state of an application's UI, whereas a transition defines the animated change between two scenes.

When a scene changes, a [`Transition`][Transition] has two main responsibilities:

1. Capture the state of each view in both the start and end scenes, and
2. Create an `Animator` based on the differences that will animate the views from one scene to the other.

As an example, consider an `Activity` which fades its views in or out when the user taps the screen. We can achieve this effect with only a few lines using Android's transition framework, as shown in the code1 below:

```java
public class ExampleActivity extends Activity implements View.OnClickListener {
    private ViewGroup mRootView;
    private View mRedBox, mGreenBox, mBlueBox, mBlackBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRootView = (ViewGroup) findViewById(R.id.layout_root_view);
        mRootView.setOnClickListener(this);

        mRedBox = findViewById(R.id.red_box);
        mGreenBox = findViewById(R.id.green_box);
        mBlueBox = findViewById(R.id.blue_box);
        mBlackBox = findViewById(R.id.black_box);
    }

    @Override
    public void onClick(View v) {
        TransitionManager.beginDelayedTransition(mRootView, new Fade());
        toggleVisibility(mRedBox, mGreenBox, mBlueBox, mBlackBox);
    }

    private static void toggleVisibility(View... views) {
        for (View view : views) {
            boolean isVisible = view.getVisibility() == View.VISIBLE;
            view.setVisibility(isVisible ? View.INVISIBLE : View.VISIBLE);
        }
    }
}
```

To better understand what happens under-the-hood in this example, let's analyze the process step-by-step assuming that each view is initially `VISIBLE` on screen:

  <video id="figure11" onclick="playPause('figure11')" poster="/assets/videos/posts/2014/12/04/trivial-opt.png" preload="none">
    <source src="/assets/videos/posts/2014/12/04/trivial-opt.mp4" type="video/mp4">
    <source src="/assets/videos/posts/2014/12/04/trivial-opt.webm" type="video/webm">
    <source src="/assets/videos/posts/2014/12/04/trivial-opt.ogv" type="video/ogg">
  </video>

Video 1.1 - Running the example transition above using a Fade, Slide, and Explode. Click to play.

1. A click is detected and the developer calls [`beginDelayedTransition()`][beginDelayedTransition], passing the scene root and a `Fade` transition as the arguments. The framework immediately calls the transition's [`captureStartValues()`][captureStartValues] method for each view in the scene and the transition records each view's visibility.
2. When the call returns, the developer sets each view in the scene to `INVISIBLE`.
3. On the next display frame, the framework calls the transition's [`captureEndValues()`][captureEndValues] method for each view in the scene and the transition records each view's (recently updated) visibility.
4. The framework calls the transition's [`createAnimator()`][createAnimator] method. The transition analyzes the start and end values of each view and notices a difference: _the views are `VISIBLE` in the start scene but `INVISIBLE` in the end scene._ The `Fade` transition uses this information to create and return an `AnimatorSet` that will fade each view's `alpha` property to `0f`.
5. The framework runs the returned `Animator`, causing all views to gradually fade out of the screen.

This simple example highlights two main advantages that the transition framework has to offer. First, `Transition`s abstract the idea of `Animator`s from the developer. As a result, `Transition`s can significantly reduce the amount of code you write in your activities and fragments: all the developer must do is set the views' start and end values and the `Transition` will automatically construct an animation based on the differences. Second, animations between scenes can be easily changed by using different `Transition` objects. **Video 1.1**, for example, illustrates the dramatically different effects we can achieve by replacing the `Fade` transition with a `Slide` or `Explode`. As we will see moving forward, these advantages will allow us to build complex Activity and Fragment transition animations with a relatively small amount of code. In the next few sections, we will see for ourselves how this can be done using Lollipop's new Activity and Fragment transition APIs.

### Activity & Fragment Transitions in Android Lollipop

As of Android 5.0, `Transition`s can now be used to perform elaborate animations when switching between different `Activity`s or `Fragment`s. Although Activity and Fragment animations could already be specified in previous platform versions using the [`Activity#overridePendingTransition()`][Activity#overridePendingTransition] and [`FragmentTransaction#setCustomAnimation()`][FragmentTransaction#setCustomAnimations] methods, they were limited in that they could only animate the entire Activity/Fragment container as a whole. The new Lollipop APIs take this a step further, making it possible to animate individual views as they enter or exit their containers and even allowing us to animate shared views from one Activity/Fragment container to the other.

Let's begin by discussing the terminology that will be used in this series of posts. Note that although the terminology below is defined in terms of Activity transitions, the exact same terminology will be used for Fragment transitions as well:

> Let `A` and `B` be activities and assume activity `A` starts activity `B`. We refer to `A` as the "_calling Activity_" (the activity that "calls" `startActivity()`) and `B` as the "_called Activity_".

The Activity transition APIs are built around the idea of _exit, enter, return, and reenter transitions_. In the context of activities `A` and `B` defined above, we can describe each as follows:

> Activity `A`'s _exit transition_ determines how views in `A` are animated when `A` starts `B`.
>
> Activity `B`'s _enter transition_ determines how views in `B` are animated when `A` starts `B`.
>
> Activity `B`'s _return transition_ determines how views in `B` are animated when `B` returns to `A`.
>
> Activity `A`'s _reenter transition_ determines how views in `A` are animated when `B` returns to `A`.

  <video id="figure12" onclick="playPause('figure12')" poster="/assets/videos/posts/2014/12/04/news-opt.png" preload="none">
    <source src="/assets/videos/posts/2014/12/04/news-opt.mp4" type="video/mp4">
    <source src="/assets/videos/posts/2014/12/04/news-opt.webm" type="video/webm">
    <source src="/assets/videos/posts/2014/12/04/news-opt.ogv" type="video/ogg">
  </video>

Video 1.2 - Content transitions and shared element transitions in action in the Google Play Newsstand app (as of v3.3). Click to play.

Lastly, the framework provides APIs for two types of Activity transitions—_content transitions_ and _shared element transitions_—each of which allow us to customize the animations between Activities in unique ways:

> A _content transition_ determines how an activity's non-shared views (also called _transitioning views_) enter or exit the activity scene.
>
> A _shared element transition_ determines how an activity's _shared elements_ (also called _hero views_) are animated between two activities.

**Video 1.2** gives a nice illustration of content transitions and shared element transitions used in the Google Play Newsstand app. Although we can't be sure without looking at the Newsstand source code, my best guess is that the following transitions are used:

* The exit and reenter content transitions for activity `A` (the calling activity) are both `null`. We can tell because the non-shared views in `A` are not animated when the user exits and reenters the activity.2
* The enter content transition for activity `B` (the called activity) uses a custom slide-in transition that shuffles the list items into place from the bottom of the screen.
* The return content transition for activity `B` is a `TransitionSet` that plays two child transitions in parallel: a `Slide(Gravity.TOP)` transition targeting the views in the top half of the activity and a `Slide(Gravity.BOTTOM)` transition targeting the views in the bottom half of the activity. The result is that the activity appears to "break in half" when the user clicks the back button and returns to activity `A`.
* The enter and return shared element transitions both use a `ChangeImageTransform`, causing the `ImageView` to be animated seamlessly between the two activities.

You've probably also noticed the cool circular reveal animation that plays under the shared element during the transition. We will cover how this can be done in a future blog post. For now, let's keep things simple and familiarize ourselves with the Activity and Fragment transition APIs.

### Introducing the Activity Transition API

Creating a basic Activity transition is relatively easy using the new Lollipop APIs. Summarized below are the steps you must take in order to implement one in your application. In the posts that follow, we will go through much more advanced use-cases and examples, but for now the next two sections will serve as a good introduction:

* Enable the new transition APIs by requesting the [`Window.FEATURE_ACTIVITY_TRANSITIONS`][FEATURE_ACTIVITY_TRANSITIONS] window feature in your called and calling Activities, either programatically or in your theme's XML.3 Material-themed applications have this flag enabled by default.
* Set [exit][setExitTransition] and [enter][setEnterTransition] content transitions for your calling and called activities respectively. Material-themed applications have their exit and enter content transitions set to `null` and [`Fade`][Fade] respectively by default. If the [reenter][setReenterTransition] or [return][setReturnTransition] transitions are not explicitly set, the activity's exit and enter content transitions respectively will be used in their place instead.
* Set [exit][setSharedElementExitTransition] and [enter][setSharedElementEnterTransition] shared element transitions for your calling and called activities respectively. Material-themed applications have their shared element exit and enter transitions set to [`@android:transition/move`][Move] by default. If the [reenter][setSharedElementReenterTransition] or [return][setSharedElementReturnTransition] transitions are not explicitly set, the activity's exit and enter shared element transitions respectively will be used in their place instead.
* To start an Activity transition with content transitions and shared elements, call the [`startActivity(Context, Bundle)`][startActivity] method and pass the following `Bundle` as the second argument:

    ```
    ActivityOptions.makeSceneTransitionAnimation(activity, pairs).toBundle();
    ```

    where `pairs` is an array of `Pair<View, String>` objects listing the shared element views and names that you'd like to share between activities.4 Don't forget to give your shared elements unique transition names, either [programatically][setTransitionName] or in [XML][transitionName]. Otherwise, the transition will not work properly!
* To programatically trigger a return transition, call [`finishAfterTransition()`][finishAfterTransition] instead of `finish()`.
* By default, material-themed applications have their enter/return content transitions started a tiny bit before their exit/reenter content transitions complete, creating a small overlap that makes the overall effect more seamless and dramatic. If you wish to explicitly disable this behavior, you can do so by calling the [`setWindowAllowEnterTransitionOverlap()`][setWindowAllowEnterTransitionOverlap] and [`setWindowAllowReturnTransitionOverlap()`][setWindowAllowReturnTransitionOverlap] methods or by setting the corresponding attributes in your theme's XML.

### Introducing the Fragment Transition API

If you are working with Fragment transitions, the API is similar with a few small differences:

* Content [exit][Fragment#setExitTransition], [enter][Fragment#setEnterTransition], [reenter][Fragment#setReenterTransition], and [return][Fragment#setReturnTransition] transitions should be set by calling the corresponding methods in the `Fragment` class or as attributes in your Fragment's XML tag.
* Shared element [enter][Fragment#setSharedElementEnterTransition] and [return][Fragment#setSharedElementReturnTransition] transitions should be set by calling the corresponding methods in the `Fragment` class or as attributes in your Fragment's XML.
* Whereas Activity transitions are triggered by explicit calls to `startActivity()` and `finishAfterTransition()`, Fragment transitions are triggered automatically when a fragment is added, removed, attached, detached, shown, or hidden by a `FragmentTransaction`.
* Shared elements should be specified as part of the `FragmentTransaction` by calling the [`addSharedElement(View, String)`][addSharedElement] method before the transaction is committed.

### Conclusion

In this post, we have only given a brief introduction to the new Activitiy and Fragment transition APIs. However, as we will see in the next few posts having a solid understanding of the basics will significantly speed up the development process in the long-run, especially when it comes to writing custom `Transition`s. In the posts that follow, we will cover content transitions and shared element transitions in even more depth and will obtain an even greater understanding of how Activity and Fragment transitions work under-the-hood.

As always, thanks for reading! Feel free to leave a comment if you have any questions, and don't forget to +1 and/or share this blog post if you found it helpful!

1 If you want to try the example out yourself, the XML layout code can be found [here][exampleXmlLayoutGist]. ↩

2 It might look like the views in `A` are fading in/out of the screen at first, but what you are really seeing is activity `B` fading in/out of the screen _on top of activity `A`_. The views in activity `A` are not actually animating during this time. You can adjust the duration of the background fade by calling [`setTransitionBackgroundFadeDuration()`][setTransitionBackgroundFadeDuration] on the called activity's `Window`. ↩

3 For an explanation describing the differences between the `FEATURE_ACTIVITY_TRANSITIONS` and `FEATURE_CONTENT_TRANSITIONS` window feature flags, see [this StackOverflow post][ACTIVITY_TRANSITIONS_vs_CONTENT_TRANSITIONS]. ↩

4 To start an Activity transition with content transitions _but no shared elements_, you can create the `Bundle` by calling `ActivityOptions.makeSceneTransitionAnimation(activity).toBundle()`. To disable content transitions and shared element transitions entirely, don't create a `Bundle` object at all—just pass `null` instead. ↩

  [exampleXmlLayoutGist]: https://gist.github.com/alexjlockwood/a96781b876138c37e88e
  [setExitTransition]: https://developer.android.com/reference/android/view/Window.html#setExitTransition(android.transition.Transition)
  [setEnterTransition]: https://developer.android.com/reference/android/view/Window.html#setEnterTransition(android.transition.Transition)
  [setReturnTransition]: https://developer.android.com/reference/android/view/Window.html#setReturnTransition(android.transition.Transition)
  [setReenterTransition]: https://developer.android.com/reference/android/view/Window.html#setReenterTransition(android.transition.Transition)
  [setSharedElementExitTransition]: https://developer.android.com/reference/android/view/Window.html#setSharedElementExitTransition(android.transition.Transition)
  [setSharedElementEnterTransition]: https://developer.android.com/reference/android/view/Window.html#setSharedElementEnterTransition(android.transition.Transition)
  [setSharedElementReturnTransition]: https://developer.android.com/reference/android/view/Window.html#setSharedElementReturnTransition(android.transition.Transition)
  [setSharedElementReenterTransition]: https://developer.android.com/reference/android/view/Window.html#setSharedElementReenterTransition(android.transition.Transition)
  [Fragment#setExitTransition]: https://developer.android.com/reference/android/app/Fragment.html#setExitTransition(android.transition.Transition)
  [Fragment#setEnterTransition]: https://developer.android.com/reference/android/app/Fragment.html#setEnterTransition(android.transition.Transition)
  [Fragment#setReturnTransition]: https://developer.android.com/reference/android/app/Fragment.html#setReturnTransition(android.transition.Transition)
  [Fragment#setReenterTransition]: https://developer.android.com/reference/android/app/Fragment.html#setReenterTransition(android.transition.Transition)
  [Fragment#setSharedElementExitTransition]: https://developer.android.com/reference/android/app/Fragment.html#setSharedElementExitTransition(android.transition.Transition)
  [Fragment#setSharedElementEnterTransition]: https://developer.android.com/reference/android/app/Fragment.html#setSharedElementEnterTransition(android.transition.Transition)
  [Fragment#setSharedElementReturnTransition]: https://developer.android.com/reference/android/app/Fragment.html#setSharedElementReturnTransition(android.transition.Transition)
  [Fragment#setSharedElementReenterTransition]: https://developer.android.com/reference/android/app/Fragment.html#setSharedElementReenterTransition(android.transition.Transition)
  [addSharedElement]: https://developer.android.com/reference/android/app/FragmentTransaction.html#addSharedElement(android.view.View,%20java.lang.String)
  [Transition]: https://developer.android.com/reference/android/transition/Transition.html
  [Fade]: https://developer.android.com/reference/android/transition/Fade.html
  [Move]: https://github.com/android/platform_frameworks_base/blob/lollipop-release/core/res/res/transition/move.xml
  [FEATURE_ACTIVITY_TRANSITIONS]: http://developer.android.com/reference/android/view/Window.html#FEATURE_ACTIVITY_TRANSITIONS
  [FEATURE_CONTENT_TRANSITIONS]: http://developer.android.com/reference/android/view/Window.html#FEATURE_CONTENT_TRANSITIONS
  [transitionName]: https://developer.android.com/reference/android/view/View.html#attr_android:transitionName
  [setTransitionName]: https://developer.android.com/reference/android/view/View.html#setTransitionName(java.lang.String)

  [Activity#overridePendingTransition]: http://developer.android.com/reference/android/app/Activity.html#overridePendingTransition(int,%20int)
  [FragmentTransaction#setCustomAnimations]: http://developer.android.com/reference/android/app/FragmentTransaction.html#setCustomAnimations(int,%20int,%20int,%20int)

  [setWindowAllowEnterTransitionOverlap]: http://developer.android.com/reference/android/view/Window.html#setAllowEnterTransitionOverlap(boolean)
  [setWindowAllowReturnTransitionOverlap]: http://developer.android.com/reference/android/view/Window.html#setAllowReturnTransitionOverlap(boolean)

  [beginDelayedTransition]: https://developer.android.com/reference/android/transition/TransitionManager.html#beginDelayedTransition(android.view.ViewGroup,%20android.transition.Transition)
  [captureStartValues]: https://developer.android.com/reference/android/transition/Transition.html#captureStartValues(android.transition.TransitionValues)
  [captureEndValues]: https://developer.android.com/reference/android/transition/Transition.html#captureEndValues(android.transition.TransitionValues)
  [createAnimator]: https://developer.android.com/reference/android/transition/Transition.html#createAnimator(android.view.ViewGroup,%20android.transition.TransitionValues,%20android.transition.TransitionValues)
  [finishAfterTransition]: https://developer.android.com/reference/android/app/Activity.html#finishAfterTransition()

  [part1]: /2014/12/activity-fragment-transitions-in-android-lollipop-part1.html
  [part2]: /2014/12/activity-fragment-content-transitions-in-depth-part2.html
  [part3a]: /2015/01/activity-fragment-shared-element-transitions-in-depth-part3a.html
  [part3b]: /2015/03/activity-postponed-shared-element-transitions-part3b.html

  [customizeActivityTransitions]: https://developer.android.com/training/material/animations.html#Transitions
  [startActivity]: http://developer.android.com/reference/android/app/Activity.html#startActivity%28android.content.Intent,%20android.os.Bundle%29

  [setTransitionBackgroundFadeDuration]: http://developer.android.com/reference/android/view/Window.html#setTransitionBackgroundFadeDuration(long)
  [ACTIVITY_TRANSITIONS_vs_CONTENT_TRANSITIONS]: http://stackoverflow.com/q/28975840/844882


text:
package com.amazonaws.services.devicefarm.model;

/**
 *
 */
public enum ArtifactCategory {

    SCREENSHOT("SCREENSHOT"),
    FILE("FILE"),
    LOG("LOG");

    private String value;

    private ArtifactCategory(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ArtifactCategory corresponding to the value
     */
    public static ArtifactCategory fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        } else if ("SCREENSHOT".equals(value)) {
            return SCREENSHOT;
        } else if ("FILE".equals(value)) {
            return FILE;
        } else if ("LOG".equals(value)) {
            return LOG;
        } else {
            throw new IllegalArgumentException("Cannot create enum from "
                    + value + " value!");
        }
    }
}


text:
package io.hydrosphere.mist

import java.nio.file.Paths

import io.hydrosphere.mist.master.models.FunctionConfig
import org.scalatest.{BeforeAndAfterAll, FunSpec, Matchers}

case class EnvArgs(
  imageName: String,
  examplesJar: String
)

class InsideDockerSpec extends FunSpec with Matchers with BeforeAndAfterAll {

  var container: TestContainer = _

  val envArgs = {
    def read(name: String): String = sys.props.get(name) match {
      case Some(v) => v
      case None => throw new RuntimeException(s"Property $name is not set")
    }
    EnvArgs(
      imageName = read("imageName"),
      examplesJar = read("examplesJar")
    )
  }

  override def beforeAll = {
    container = TestContainer.run(
      DockerImage(envArgs.imageName),
      Map(2004 -> 2004),
      Map("/var/run/docker.sock" -> "/var/run/docker.sock")
    )
    super.beforeAll()
  }

  override def afterAll = {
    container.close()
    super.afterAll
  }

  describe("hello-mist project") {

    it("should deploy and invoke") {
      val jarName = "docker-examples.jar"
      val functionName = "spark-ctx"
      val clazz = "SparkContextExample$"

      val interface = MistHttpInterface("localhost", 2004)
      interface.uploadArtifact(jarName, Paths.get(envArgs.examplesJar))
      interface.createFunction(
        FunctionConfig(
          name = functionName,
          path = jarName,
          className = clazz,
          defaultContext = "default"
        )
      )
      val result = interface.runJob(functionName, "numbers" -> Seq(1,2,3,4))
      assert(result.success)
    }
  }

}


text:
package im.AfriChat.core.js.modules;

import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.ExportClosure;
import org.timepedia.exporter.client.Exportable;

@Export
@ExportClosure
public interface JsBindedValueCallback extends Exportable {
    void onChanged(Object obj);
}


text:
import * as types from '../actions/actionTypes';
import initialState from './initialState';

const adoptersReducer = (state = initialState.adopters, action) => {
  switch (action.type) {
    case types.LOAD_ADOPTERS_SUCCESS: {
      let newAdopters = action.row === 1 ? [] : state.adopters;
      const { adopters, total_pages } = action.response;
      newAdopters = newAdopters.concat(adopters);
      let newValues = {
        totalPages: total_pages,
        adopters: newAdopters,
        firstPage: action.row === 1,
        filterParam: action.filterParam || {}
      };
      return Object.assign({}, state, newValues);
    }
    case types.SEND_ADOPTER_FORM_SUCCESS: {
      return initialState.adopters;
    }
    case types.CLEAN_ADOPTERS_SUCCESS: {
      return Object.assign({}, state, { totalPages: 0, adopters: [], firstPage: false });
    }
    default:
      return state;
  }
};

export default adoptersReducer;


text:
.class public LPreHeader;

.super Ljava/lang/Object;

# Label names in this method are taken from the original apk
# that exposed the crash. The crash was due to fixing a critical
# edge and not preserving the invariant that the pre header of a loop
# is the first predecessor of the loop header.
.method public static method()V
   .registers 2
   const/4 v0, 0
   const/4 v1, 0
   goto :b31
   :b23
   if-eqz v0, :b25
   goto :b23
   :b25
   return-void
   :b31
   if-eqz v0, :b23
   if-eqz v1, :bexit
   goto :b31
   :bexit
   return-void
.end method


text:
<!DOCTYPE html>

		<title>Documentation of {{className}}</title>
		<link rel="stylesheet" href="../../../../../styles/dbm/documentation/main.css" />
		<link rel="stylesheet" href="../../../../../styles/dbm/documentation/class.css" />

Dbm documentation

						Index

						<form action="https://www.google.co.uk/cse/publicurl" method="GET">
							<input type="hidden" name="cx" value="006746230495882673940:ilr36kbyhjo" />
							<input type="text" name="q" value="" />
						</form>

TextReplacementNode

dbm.flow.nodes.text.TextReplacementNode

FlowBaseObject > BaseObject

Subclasses

Class has no subclasses.

Dependencies

AnyChangeMultipleInputProperty, ArrayHolder, KeyValuePropertyPair

Import code

var TextReplacementNode = dbm.importClass("dbm.flow.nodes.text.TextReplacementNode");

Full code

dbm.registerClass("dbm.flow.nodes.text.TextReplacementNode", "dbm.core.FlowBaseObject", function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.flow.nodes.text.TextReplacementNode");

	//Self reference
	var TextReplacementNode = dbm.importClass("dbm.flow.nodes.text.TextReplacementNode");

	//Error report

	//Dependencies
	var AnyChangeMultipleInputProperty = dbm.importClass("dbm.core.objectparts.AnyChangeMultipleInputProperty");
	var KeyValuePropertyPair = dbm.importClass("dbm.flow.data.KeyValuePropertyPair");
	var ArrayHolder = dbm.importClass("dbm.utils.data.ArrayHolder");

	//Utils

	//Constants

	/**
	 * Constructor
	 */
	objectFunctions._init = function() {
		//console.log("dbm.flow.nodes.text.TextReplacementNode::_init");

		this.superCall();

		this._inputValue = this.createProperty("inputValue", "");
		this._outputValue = this.createProperty("outputValue", "");
		this._replacementUpdate = this.addProperty("replacementUpdate", AnyChangeMultipleInputProperty.create());

		this._textReplacements = ArrayHolder.create(true);
		this.addDestroyableObject(this._textReplacements);

		this.createUpdateFunction("default", this._update, [this._inputValue, this._replacementUpdate], [this._outputValue]);

		return this;
	};

	objectFunctions.addReplacement = function(aKeyValue, aDataValue) {
		var newKeyValuePair = KeyValuePropertyPair.create(aKeyValue, aDataValue);
		this._replacementUpdate.connectInput(newKeyValuePair.keyValue);
		this._replacementUpdate.connectInput(newKeyValuePair.dataValue);
		this._textReplacements.array.push(newKeyValuePair);

		return this;
	};

	objectFunctions._update = function(aFlowUpdateNumber) {
		//console.log("dbm.flow.nodes.text.TextReplacementNode::_update");

		var currentText = this._inputValue.getValueWithoutFlow().toString();

		var currentArray = this._textReplacements.array;
		var currentArrayLength = currentArray.length;
		for(var i = 0; i < currentArrayLength; i++) {
			var currentReplacement = currentArray[i];
			var keyValue = currentReplacement.keyValue.getValueWithoutFlow().toString();
			var dataValue = currentReplacement.dataValue.getValueWithoutFlow().toString();
			currentText = currentText.split(keyValue).join(dataValue);
		}

		this._outputValue.setValueWithFlow(currentText, aFlowUpdateNumber);
	};

	objectFunctions.setAllReferencesToNull = function() {

		this._inputValue = null;
		this._outputValue = null;
		this._replacementUpdate = null;

		this.superCall();
	};

	staticFunctions.create = function(aInput) {
		var newNode = (new ClassReference()).init();
		newNode.setPropertyInputWithoutNull("inputValue", aInput);
		return newNode;
	};
})

Local variables

Local functions

					_init():self

Constructor

Arguments

Function has no arguments

Return value

Self. Function is linkable.

Full code

objectFunctions._init = function() {
		//console.log("dbm.flow.nodes.text.TextReplacementNode::_init");

		this.superCall();

		this._inputValue = this.createProperty("inputValue", "");
		this._outputValue = this.createProperty("outputValue", "");
		this._replacementUpdate = this.addProperty("replacementUpdate", AnyChangeMultipleInputProperty.create());

		this._textReplacements = ArrayHolder.create(true);
		this.addDestroyableObject(this._textReplacements);

		this.createUpdateFunction("default", this._update, [this._inputValue, this._replacementUpdate], [this._outputValue]);

		return this;
	}

					addReplacement(aKeyValue, aDataValue):self

Arguments

aKeyValue

aDataValue

Return value

Self. Function is linkable.

Full code

objectFunctions.addReplacement = function(aKeyValue, aDataValue) {
		var newKeyValuePair = KeyValuePropertyPair.create(aKeyValue, aDataValue);
		this._replacementUpdate.connectInput(newKeyValuePair.keyValue);
		this._replacementUpdate.connectInput(newKeyValuePair.dataValue);
		this._textReplacements.array.push(newKeyValuePair);

		return this;
	}

					_update(aFlowUpdateNumber):void

Arguments

aFlowUpdateNumber

Return value

Function has no return value.

Full code

objectFunctions._update = function(aFlowUpdateNumber) {
		//console.log("dbm.flow.nodes.text.TextReplacementNode::_update");

		var currentText = this._inputValue.getValueWithoutFlow().toString();

		var currentArray = this._textReplacements.array;
		var currentArrayLength = currentArray.length;
		for(var i = 0; i < currentArrayLength; i++) {
			var currentReplacement = currentArray[i];
			var keyValue = currentReplacement.keyValue.getValueWithoutFlow().toString();
			var dataValue = currentReplacement.dataValue.getValueWithoutFlow().toString();
			currentText = currentText.split(keyValue).join(dataValue);
		}

		this._outputValue.setValueWithFlow(currentText, aFlowUpdateNumber);
	}

					setAllReferencesToNull():void

Arguments

Function has no arguments

Return value

Function has no return value.

Full code

objectFunctions.setAllReferencesToNull = function() {

		this._inputValue = null;
		this._outputValue = null;
		this._replacementUpdate = null;

		this.superCall();
	}

Static variables

Static functions

					create(aInput):Unknown

Arguments

aInput

Return value

Unknown

Full code

staticFunctions.create = function(aInput) {
		var newNode = (new ClassReference()).init();
		newNode.setPropertyInputWithoutNull("inputValue", aInput);
		return newNode;
	}

				Documentation exported with dbm.


text:
	<title>Mum Shoppe</title>

	<meta name="viewport" content="width=device-width, initial-scale=1">

	<link rel="stylesheet" href="public/css/font-awesome.min.css">
	<link rel="stylesheet" href="public/css/bootstrap.min.css">

			Welcome to the MumShoppe!
			Welcome, {{customer.Name}}!

Your Mums

Logout

			<alert type="{{alert.type}}" class="alert" ng-click="closeAlert(alert)">
				{{alert.msg}}
				Click to dismiss
			</alert>

Copyright  2014 Colby Brown


text:
package com.intellij.openapi.fileEditor;

import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.editor.impl.EditorHeaderComponent;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;

public class SplitEditorToolbar extends EditorHeaderComponent {

  private final ActionToolbar myRightToolbar;
  private final boolean myLeftToolbarEmpty;

  public SplitEditorToolbar(@Nullable ActionToolbar leftToolbar, @NotNull ActionToolbar rightToolbar) {
    super();
    setLayout(new GridBagLayout());
    myRightToolbar = rightToolbar;
    myLeftToolbarEmpty = leftToolbar == null || leftToolbar.getActions().isEmpty();

    if (leftToolbar != null) {
      add(leftToolbar.getComponent());
    }

    final JPanel centerPanel = new JPanel(new BorderLayout());
    add(centerPanel, new GridBagConstraints(2, 0, 1, 1, 1.0, 1.0,
                                            GridBagConstraints.CENTER, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0));

    add(myRightToolbar.getComponent());
  }

  public ActionToolbar getRightToolbar() {
    return myRightToolbar;
  }

  public boolean isLeftToolbarEmpty() {
    return myLeftToolbarEmpty;
  }

  public void refresh() {
    myRightToolbar.updateActionsImmediately();
  }
}


text:
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter

class AccountAdapter(DefaultAccountAdapter):
    def is_open_for_signup(self, request):
        return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)

    def save_user(self, request, user, form):
        if len(user.socialaccount_set.all()) == 0:
            name = request.data.get('name', None)
            email = request.data.get('email', None)
            username = request.data.get('username', None)
            password1 = request.data.get('password1', None)
            password2 = request.data.get('password2', None)
            user.name = name
            user.email = email
            user.username = username
            if(password1 == password2):
                user.set_password(password1)
            user.save()

class SocialAccountAdapter(DefaultSocialAccountAdapter):
    def is_open_for_signup(self, request, sociallogin):
        return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)


text:
template <class T> class DLL_PUBLIC SimObjectPtr
{
  private:
   SimObject *mObj;

  public:
   SimObjectPtr() { mObj = 0; }
   SimObjectPtr(T* ptr)
   {
      mObj = ptr;
      if(mObj)
         mObj->registerReference(&mObj);
   }
   SimObjectPtr(const SimObjectPtr<T>& rhs)
   {
      mObj = const_cast<T*>(static_cast<const T*>(rhs));
      if(mObj)
         mObj->registerReference(&mObj);
   }
   SimObjectPtr<T>& operator=(const SimObjectPtr<T>& rhs)
   {
      if(this == &rhs)
         return(*this);
      if(mObj)
         mObj->unregisterReference(&mObj);
      mObj = const_cast<T*>(static_cast<const T*>(rhs));
      if(mObj)
         mObj->registerReference(&mObj);
      return(*this);
   }
   ~SimObjectPtr()
   {
      if(mObj)
         mObj->unregisterReference(&mObj);
   }
   SimObjectPtr<T>& operator= (T *ptr)
   {
      if(mObj != (SimObject *) ptr)
      {
         if(mObj)
            mObj->unregisterReference(&mObj);
         mObj = (SimObject *) ptr;
         if (mObj)
            mObj->registerReference(&mObj);
      }
      return *this;
   }
#if defined(__MWERKS__) && (__MWERKS__ < 0x2400)
   // CW 5.3 seems to get confused comparing SimObjectPtrs...
   bool operator == (const SimObject *ptr) { return mObj == ptr; }
   bool operator != (const SimObject *ptr) { return mObj != ptr; }
#endif
   bool isNull() const   { return mObj == 0; }
   bool notNull() const   { return mObj != 0; }
   T* operator->() const { return static_cast<T*>(mObj); }
   T& operator*() const  { return *static_cast<T*>(mObj); }
   operator T*() const   { return static_cast<T*>(mObj)? static_cast<T*>(mObj) : 0; }
};

#endif // _SIM_OBJECT_PTR_H_


text:
#!/usr/bin/env node

var program = require('commander'),
    request = require('superagent'),
    colors  = require('colors'),
    archy   = require('archy'),
    _       = require('underscore'),

    fs      = require('fs'),
    exec    = require('child_process').exec,
    spawn   = require('child_process').spawn,

    CONFIG  = JSON.parse(fs.readFileSync('./config.json')),
    ASANA_KEY = CONFIG['API_KEY'],
    ASANA   = CONFIG['API_URL'] + CONFIG['API_VERSION'];

/**
 * Asana CLI
 */
program
  .version('0.0.1')
  .usage('[options] <cmds>');

program
  .command('me')
  .description(' -- Current user')
  .action(function(){
    me();
  });

program
  .command('tasks')
  .description('  -- list all tasks assigned to you')
  .action(function(){
    tasks();
  });

program
  .command('cd')
  .description(' -- Change directory')
  .action(function(){
    cd();
  });

program
  .command('ls')
  .description(' -- List all in current directory')
  .action(function(){

  });

program
  .command('projects')
  .description(' -- List all projects')
  .action(function(){
    projects();
  });

program.parse(process.argv);

/**
 * Functions
 */

function puts(error, stdout, stderr) {
  stream(error);
  stream(stdout);
  stream(stderr);
}

function stream(data) {
  if (data) console.log(data);
}

function cd() {
  var dir = _.first(program.args);
  console.log(dir);
}

function projects() {
  request
    .get(ASANA+'/projects')
    .auth(ASANA_KEY,'')
    .end(function(res){
      var data = res['body']['data'];
      printChildren(data, 'Projects')
    });
}

function workspaces() {
  request
    .get(ASANA+'/workspaces')
    .auth(ASANA_KEY,'')
    .end(function(res){
      var data = res['body']['data'];
      printChildren(data, 'Workspaces')
    });
}

function tasks() {
  request
    .get(ASANA + '/tasks')
    .query({ assignee: 'me' })
    .auth(ASANA_KEY,'')
    .end(function(res){
      var data = res['body']['data'];
      printChildren(data, 'Tasks')
    });
}

function me() {
  request
    .get(ASANA + '/users/me')
    .query({opt_pretty: 'true'})
    .auth(ASANA_KEY,'')
    .end(function(res){
      if (res.ok) {
        var data = res.body['data'];

        print('    name: '.blue+data['name'],
              '    email: '.blue+data['email'],
              '    id: '.blue+data['id']);

        if (data['workspaces']) {
          printChildren(data['workspaces'], 'Workspaces');
        }

        projects();
      }
    });
}

function printChildren(data, label) {
  var nodes, s;
  data = _.toArray(data);

  // map workspace.name => nodes.label for
  // archy support.
  nodes = _.map(data, function(d) {
    return {'label': d['name']}
  });

  s = archy({
    label: label.green,
    nodes: nodes
  }, "    ");

  print(s);
}

function print() {
  console.log('');
  _.each(arguments, function(arg){
    console.log(arg);
  })
}