text:
/*
 * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package javax.naming;

/**
 * This exception is used to describe problems encounter while resolving links.
 * Addition information is added to the base NamingException for pinpointing
 * the problem with the link.
 *

 * Analogous to how NamingException captures name resolution information,
 * LinkException captures "link"-name resolution information pinpointing
 * the problem encountered while resolving a link. All these fields may
 * be null.
 *

 *
 Link Resolved Name. Portion of link name that has been resolved.
 *
 Link Resolved Object. Object to which resolution of link name proceeded.
 *
 Link Remaining Name. Portion of link name that has not been resolved.
 *
 Link Explanation. Detail explaining why link resolution failed.
 *

 *
  *

  * A LinkException instance is not synchronized against concurrent
  * multithreaded access. Multiple threads trying to access and modify
  * a single LinkException instance should lock the object.
  *
  * @author Rosanna Lee
  * @author Scott Seligman
  *
  * @see Context#lookupLink
  * @see LinkRef
  * @since 1.3
  */

  /*

  * The serialized form of a LinkException object consists of the
  * serialized fields of its NamingException superclass, the link resolved
  * name (a Name object), the link resolved object, link remaining name
  * (a Name object), and the link explanation String.
*/

public class LinkException extends NamingException {
    /**
     * Contains the part of the link that has been successfully resolved.
     * It is a composite name and can be null.
     * This field is initialized by the constructors.
     * You should access and manipulate this field
     * through its get and set methods.
     * @serial
     * @see #getLinkResolvedName
     * @see #setLinkResolvedName
     */
    protected Name linkResolvedName;

    /**
      * Contains the object to which resolution of the part of the link was successful.
      * Can be null. This field is initialized by the constructors.
      * You should access and manipulate this field
      * through its get and set methods.
      * @serial
      * @see #getLinkResolvedObj
      * @see #setLinkResolvedObj
      */
    protected Object linkResolvedObj;

    /**
     * Contains the remaining link name that has not been resolved yet.
     * It is a composite name and can be null.
     * This field is initialized by the constructors.
     * You should access and manipulate this field
     * through its get and set methods.
     * @serial
     * @see #getLinkRemainingName
     * @see #setLinkRemainingName
     */
    protected Name linkRemainingName;

    /**
     * Contains the exception of why resolution of the link failed.
     * Can be null. This field is initialized by the constructors.
     * You should access and manipulate this field
     * through its get and set methods.
     * @serial
     * @see #getLinkExplanation
     * @see #setLinkExplanation
     */
    protected String linkExplanation;

    /**
      * Constructs a new instance of LinkException with an explanation
      * All the other fields are initialized to null.
      * @param  explanation     A possibly null string containing additional
      *                         detail about this exception.
      * @see java.lang.Throwable#getMessage
      */
    public LinkException(String explanation) {
        super(explanation);
        linkResolvedName = null;
        linkResolvedObj = null;
        linkRemainingName = null;
        linkExplanation = null;
    }

    /**
      * Constructs a new instance of LinkException.
      * All the non-link-related and link-related fields are initialized to null.
      */
    public LinkException() {
        super();
        linkResolvedName = null;
        linkResolvedObj = null;
        linkRemainingName = null;
        linkExplanation = null;
    }

    /**
     * Retrieves the leading portion of the link name that was resolved
     * successfully.
     *
     * @return The part of the link name that was resolved successfully.
     *          It is a composite name. It can be null, which means
     *          the link resolved name field has not been set.
     * @see #getLinkResolvedObj
     * @see #setLinkResolvedName
     */
    public Name getLinkResolvedName() {
        return this.linkResolvedName;
    }

    /**
     * Retrieves the remaining unresolved portion of the link name.
     * @return The part of the link name that has not been resolved.
     *          It is a composite name. It can be null, which means
     *          the link remaining name field has not been set.
     * @see #setLinkRemainingName
     */
    public Name getLinkRemainingName() {
        return this.linkRemainingName;
    }

    /**
     * Retrieves the object to which resolution was successful.
     * This is the object to which the resolved link name is bound.
     *
     * @return The possibly null object that was resolved so far.
     * If null, it means the link resolved object field has not been set.
     * @see #getLinkResolvedName
     * @see #setLinkResolvedObj
     */
    public Object getLinkResolvedObj() {
        return this.linkResolvedObj;
    }

    /**
      * Retrieves the explanation associated with the problem encounter
      * when resolving a link.
      *
      * @return The possibly null detail string explaining more about the problem
      * with resolving a link.
      *         If null, it means there is no
      *         link detail message for this exception.
      * @see #setLinkExplanation
      */
    public String getLinkExplanation() {
        return this.linkExplanation;
    }

    /**
      * Sets the explanation associated with the problem encounter
      * when resolving a link.
      *
      * @param msg The possibly null detail string explaining more about the problem
      * with resolving a link. If null, it means no detail will be recorded.
      * @see #getLinkExplanation
      */
    public void setLinkExplanation(String msg) {
        this.linkExplanation = msg;
    }

    /**
     * Sets the resolved link name field of this exception.
     *

     * <tt>name</tt> is a composite name. If the intent is to set
     * this field using a compound name or string, you must
     * "stringify" the compound name, and create a composite
     * name with a single component using the string. You can then
     * invoke this method using the resulting composite name.
     *

     * A copy of name is made and stored.
     * Subsequent changes to name does not
     * affect the copy in this NamingException and vice versa.
     *
     *
     * @param name The name to set resolved link name to. This can be null.
     *          If null, it sets the link resolved name field to null.
     * @see #getLinkResolvedName
     */
    public void setLinkResolvedName(Name name) {
        if (name != null) {
            this.linkResolvedName = (Name)(name.clone());
        } else {
            this.linkResolvedName = null;
        }
    }

    /**
     * Sets the remaining link name field of this exception.
     *

     * <tt>name</tt> is a composite name. If the intent is to set
     * this field using a compound name or string, you must
     * "stringify" the compound name, and create a composite
     * name with a single component using the string. You can then
     * invoke this method using the resulting composite name.
     *

     * A copy of name is made and stored.
     * Subsequent changes to name does not
     * affect the copy in this NamingException and vice versa.
     *
     * @param name The name to set remaining link name to. This can be null.
     *  If null, it sets the remaining name field to null.
     * @see #getLinkRemainingName
     */
    public void setLinkRemainingName(Name name) {
        if (name != null)
            this.linkRemainingName = (Name)(name.clone());
        else
            this.linkRemainingName = null;
    }

    /**
     * Sets the link resolved object field of this exception.
     * This indicates the last successfully resolved object of link name.
     * @param obj The object to set link resolved object to. This can be null.
     *            If null, the link resolved object field is set to null.
     * @see #getLinkResolvedObj
     */
    public void setLinkResolvedObj(Object obj) {
        this.linkResolvedObj = obj;
    }

    /**
     * Generates the string representation of this exception.
     * This string consists of the NamingException information plus
     * the link's remaining name.
     * This string is used for debugging and not meant to be interpreted
     * programmatically.
     * @return The non-null string representation of this link exception.
     */
    public String toString() {
        return super.toString() + "; Link Remaining Name: '" +
            this.linkRemainingName + "'";
    }

    /**
     * Generates the string representation of this exception.
     * This string consists of the NamingException information plus
     * the additional information of resolving the link.
     * If 'detail' is true, the string also contains information on
     * the link resolved object. If false, this method is the same
     * as the form of toString() that accepts no parameters.
     * This string is used for debugging and not meant to be interpreted
     * programmatically.
     *
     * @param   detail  If true, add information about the link resolved
     *                  object.
     * @return The non-null string representation of this link exception.
     */
    public String toString(boolean detail) {
        if (!detail || this.linkResolvedObj == null)
            return this.toString();

        return this.toString() + "; Link Resolved Object: " +
            this.linkResolvedObj;
    }

    /**
     * Use serialVersionUID from JNDI 1.1.1 for interoperability
     */
    private static final long serialVersionUID = -7967662604076777712L;
};


text:
<?php declare(strict_types=1);

namespace Granam\Tests\DiceRolls\Templates\Dices;

use Granam\DiceRolls\Templates\Dices\CustomDice;
use Granam\Integer\IntegerInterface;
use Granam\Tests\Tools\TestWithMockery;

class CustomDiceTest extends TestWithMockery
{
    /**
     * @test
     */
    public function I_can_create_it()
    {
        /** @var IntegerInterface|\Mockery\MockInterface $minimum */
        $minimum = $this->mockery(IntegerInterface::class);
        $minimum->shouldReceive('getValue')
            ->andReturn($minimumValue = 1);
        /** @var IntegerInterface|\Mockery\MockInterface $maximum */
        $maximum = $this->mockery(IntegerInterface::class);
        $maximum->shouldReceive('getValue')
            ->andReturn($maximumValue = 2);

        $customDice = new CustomDice($minimum, $maximum);
        self::assertSame($minimum, $customDice->getMinimum());
        self::assertSame($maximum, $customDice->getMaximum());
    }

    /**
     * @test
     */
    public function I_can_use_same_minimum_as_maximum()
    {
        /** @var IntegerInterface|\Mockery\MockInterface $minimum */
        $minimum = $this->mockery(IntegerInterface::class);
        $minimum->shouldReceive('getValue')
            ->andReturn($minimumValue = 12345);
        /** @var IntegerInterface|\Mockery\MockInterface $maximum */
        $maximum = $this->mockery(IntegerInterface::class);
        $maximum->shouldReceive('getValue')
            ->andReturn($minimumValue);

        $customDice = new CustomDice($minimum, $maximum);
        self::assertNotSame($customDice->getMinimum(), $customDice->getMaximum());
        self::assertSame($customDice->getMinimum()->getValue(), $customDice->getMaximum()->getValue());
    }

    /**
     * @test
     */
    public function I_can_not_use_minimum_greater_than_maximum()
    {
        $this->expectException(\Granam\DiceRolls\Templates\Dices\Exceptions\InvalidDiceRange::class);
        /** @var IntegerInterface|\Mockery\MockInterface $minimum */
        $minimum = $this->mockery(IntegerInterface::class);
        $minimum->shouldReceive('getValue')
            ->andReturn($minimumValue = 12345);
        /** @var IntegerInterface|\Mockery\MockInterface $maximum */
        $maximum = $this->mockery(IntegerInterface::class);
        $maximum->shouldReceive('getValue')
            ->andReturn($maximumValue = $minimumValue - 1);
        self::assertLessThan($minimumValue, $maximumValue);

        new CustomDice($minimum, $maximum);
    }

    /**
     * @test
     */
    public function I_can_not_use_zero_for_minimum()
    {
        $this->expectException(\Granam\DiceRolls\Templates\Dices\Exceptions\InvalidDiceRange::class);
        /** @var IntegerInterface|\Mockery\MockInterface $minimum */
        $minimum = $this->mockery(IntegerInterface::class);
        $minimum->shouldReceive('getValue')
            ->andReturn(0);
        /** @var IntegerInterface|\Mockery\MockInterface $maximum */
        $maximum = $this->mockery(IntegerInterface::class);
        $maximum->shouldReceive('getValue')
            ->andReturn(12345);

        new CustomDice($minimum, $maximum);
    }

    /**
     * @test
     */
    public function I_can_not_use_negative_number_for_minimum()
    {
        $this->expectException(\Granam\DiceRolls\Templates\Dices\Exceptions\InvalidDiceRange::class);
        /** @var IntegerInterface|\Mockery\MockInterface $minimum */
        $minimum = $this->mockery(IntegerInterface::class);
        $minimum->shouldReceive('getValue')
            ->andReturn(-1);
        /** @var IntegerInterface|\Mockery\MockInterface $maximum */
        $maximum = $this->mockery(IntegerInterface::class);
        $maximum->shouldReceive('getValue')
            ->andReturn(12345);

        new CustomDice($minimum, $maximum);
    }

    /**
     * @test
     */
    public function I_can_not_use_zero_limits()
    {
        $this->expectException(\Granam\DiceRolls\Templates\Dices\Exceptions\InvalidDiceRange::class);
        /** @var IntegerInterface|\Mockery\MockInterface $minimum */
        $minimum = $this->mockery(IntegerInterface::class);
        $minimum->shouldReceive('getValue')
            ->andReturn(0);
        /** @var IntegerInterface|\Mockery\MockInterface $maximum */
        $maximum = $this->mockery(IntegerInterface::class);
        $maximum->shouldReceive('getValue')
            ->andReturn(0);

        new CustomDice($minimum, $maximum);
    }

    /**
     * @test
     */
    public function I_can_not_use_negatives_for_limits()
    {
        $this->expectException(\Granam\DiceRolls\Templates\Dices\Exceptions\InvalidDiceRange::class);
        /** @var IntegerInterface|\Mockery\MockInterface $minimum */
        $minimum = $this->mockery(IntegerInterface::class);
        $minimum->shouldReceive('getValue')
            ->andReturn(-1);
        /** @var IntegerInterface|\Mockery\MockInterface $maximum */
        $maximum = $this->mockery(IntegerInterface::class);
        $maximum->shouldReceive('getValue')
            ->andReturn(-1);

        new CustomDice($minimum, $maximum);
    }

}

redpajama_set_name: RedPajamaGithub


text:
//
//  BaseModel.m
//  MallCommunicationLibrary
//
//  Created by maoyu on 14-7-28.
//  Copyright (c) 2014年 yuteng. All rights reserved.
//

#import "BaseModel.h"
#import "AutoCoding.h"

@implementation BaseModel

- (id)initWithUUID{
    if (self = [super init]) {
        CFUUIDRef uuid = CFUUIDCreate(NULL);
        self.iid = CFBridgingRelease(CFUUIDCreateString(NULL, uuid));
        CFRelease(uuid);

        self.createDate = [NSDate date];
    }

    return self;
}

/*
 * 支持NSCoding协议,将对象打包成格式数据,打包之后,就能使用TMCache一类的库来做本地数据缓存
 */
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    [self setWithCoder:aDecoder];
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    for (NSString *key in [self codableProperties])
    {
        id object = [self valueForKey:key];
        if (object) [aCoder encodeObject:object forKey:key];
    }
}

@end


text:
package com.linecorp.armeria.client.logging;

import static com.linecorp.armeria.internal.common.logging.LoggingDecorators.log;
import static com.linecorp.armeria.internal.common.logging.LoggingDecorators.logRequest;
import static com.linecorp.armeria.internal.common.logging.LoggingDecorators.logResponse;
import static java.util.Objects.requireNonNull;

import java.util.function.BiFunction;
import java.util.function.Consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linecorp.armeria.client.Client;
import com.linecorp.armeria.client.ClientRequestContext;
import com.linecorp.armeria.client.SimpleDecoratingClient;
import com.linecorp.armeria.common.HttpHeaders;
import com.linecorp.armeria.common.Request;
import com.linecorp.armeria.common.RequestContext;
import com.linecorp.armeria.common.Response;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.logging.LogLevel;
import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.common.logging.RequestLogLevelMapper;
import com.linecorp.armeria.common.logging.RequestOnlyLog;
import com.linecorp.armeria.common.logging.ResponseLogLevelMapper;
import com.linecorp.armeria.common.util.Sampler;

/**
 * Decorates a {@link Client} to log {@link Request}s and {@link Response}s.
 *
 * @param <I> the {@link Request} type
 * @param <O> the {@link Response} type
 */
abstract class AbstractLoggingClient<I extends Request, O extends Response>
        extends SimpleDecoratingClient<I, O> {

    private final RequestLogger requestLogger = new RequestLogger();
    private final ResponseLogger responseLogger = new ResponseLogger();

    private final Logger logger;
    private final RequestLogLevelMapper requestLogLevelMapper;
    private final ResponseLogLevelMapper responseLogLevelMapper;

    private final BiFunction<? super RequestContext, ? super HttpHeaders, ? extends @Nullable Object>
            requestHeadersSanitizer;
    private final BiFunction<? super RequestContext, Object, ? extends @Nullable Object>
            requestContentSanitizer;
    private final BiFunction<? super RequestContext, ? super HttpHeaders, ? extends @Nullable Object>
            requestTrailersSanitizer;

    private final BiFunction<? super RequestContext, ? super HttpHeaders, ? extends @Nullable Object>
            responseHeadersSanitizer;
    private final BiFunction<? super RequestContext, Object, ? extends @Nullable Object>
            responseContentSanitizer;
    private final BiFunction<? super RequestContext, ? super HttpHeaders, ? extends @Nullable Object>
            responseTrailersSanitizer;
    private final BiFunction<? super RequestContext, ? super Throwable, ? extends @Nullable Object>
            responseCauseSanitizer;

    private final Sampler<? super RequestLog> sampler;

    /**
     * Creates a new instance that logs {@link Request}s and {@link Response}s at the specified
     * {@link LogLevel}s with the specified sanitizers.
     */
    AbstractLoggingClient(
            Client<I, O> delegate,
            @Nullable Logger logger,
            RequestLogLevelMapper requestLogLevelMapper,
            ResponseLogLevelMapper responseLogLevelMapper,
            BiFunction<? super RequestContext, ? super HttpHeaders,
                    ? extends @Nullable Object> requestHeadersSanitizer,
            BiFunction<? super RequestContext, Object,
                    ? extends @Nullable Object> requestContentSanitizer,
            BiFunction<? super RequestContext, ? super HttpHeaders,
                    ? extends @Nullable Object> requestTrailersSanitizer,
            BiFunction<? super RequestContext, ? super HttpHeaders,
                    ? extends @Nullable Object> responseHeadersSanitizer,
            BiFunction<? super RequestContext, Object,
                    ? extends @Nullable Object> responseContentSanitizer,
            BiFunction<? super RequestContext, ? super HttpHeaders,
                    ? extends @Nullable Object> responseTrailersSanitizer,
            BiFunction<? super RequestContext, ? super Throwable,
                    ? extends @Nullable Object> responseCauseSanitizer,
            Sampler<? super ClientRequestContext> successSampler,
            Sampler<? super ClientRequestContext> failureSampler) {

        super(requireNonNull(delegate, "delegate"));

        this.logger = logger != null ? logger : LoggerFactory.getLogger(getClass());
        this.requestLogLevelMapper = requireNonNull(requestLogLevelMapper, "requestLogLevelMapper");
        this.responseLogLevelMapper = requireNonNull(responseLogLevelMapper, "responseLogLevelMapper");

        this.requestHeadersSanitizer = requireNonNull(requestHeadersSanitizer, "requestHeadersSanitizer");
        this.requestContentSanitizer = requireNonNull(requestContentSanitizer, "requestContentSanitizer");
        this.requestTrailersSanitizer = requireNonNull(requestTrailersSanitizer, "requestTrailersSanitizer");

        this.responseHeadersSanitizer = requireNonNull(responseHeadersSanitizer, "responseHeadersSanitizer");
        this.responseContentSanitizer = requireNonNull(responseContentSanitizer, "responseContentSanitizer");
        this.responseTrailersSanitizer = requireNonNull(responseTrailersSanitizer, "responseTrailersSanitizer");
        this.responseCauseSanitizer = requireNonNull(responseCauseSanitizer, "responseCauseSanitizer");
        requireNonNull(successSampler, "successSampler");
        requireNonNull(failureSampler, "failureSampler");
        sampler = requestLog -> {
            final ClientRequestContext ctx = (ClientRequestContext) requestLog.context();
            if (ctx.options().successFunction().isSuccess(ctx, requestLog)) {
                return successSampler.isSampled(ctx);
            }
            return failureSampler.isSampled(ctx);
        };
    }

    @Override
    public final O execute(ClientRequestContext ctx, I req) throws Exception {
        ctx.log().whenComplete().thenAccept(log -> {
            if (sampler.isSampled(log)) {
                log(logger, ctx, log, requestLogger, responseLogger);
            }
        });
        return unwrap().execute(ctx, req);
    }

    private class RequestLogger implements Consumer<RequestOnlyLog> {
        @Override
        public void accept(RequestOnlyLog log) {
            logRequest(logger, log,
                       requestLogLevelMapper,
                       requestHeadersSanitizer,
                       requestContentSanitizer, requestTrailersSanitizer);
        }
    }

    private class ResponseLogger implements Consumer<RequestLog> {
        @Override
        public void accept(RequestLog log) {
            logResponse(logger, log,
                        requestLogLevelMapper,
                        responseLogLevelMapper,
                        requestHeadersSanitizer,
                        requestContentSanitizer,
                        requestHeadersSanitizer,
                        responseHeadersSanitizer,
                        responseContentSanitizer,
                        responseTrailersSanitizer,
                        responseCauseSanitizer);
        }
    }
}


text:
package com.reason.lang.ocaml;

import com.intellij.psi.*;
import com.intellij.psi.tree.*;
import com.intellij.psi.util.*;
import com.reason.ide.files.*;
import com.reason.lang.core.*;
import com.reason.lang.core.psi.PsiType;
import com.reason.lang.core.psi.*;
import com.reason.lang.core.psi.impl.*;

import java.util.*;
import java.util.stream.*;

import static com.intellij.psi.util.PsiTreeUtil.*;

@SuppressWarnings("ConstantConditions")
public class TypeParsingTest extends OclParsingTestCase {
    public void test_abstract_type() {
        PsiType type = first(typeExpressions(parseCode("type t")));
        assertEquals("t", type.getName());
    }

    public void test_recursive_type() {
        PsiType type = first(typeExpressions(parseCode("type rec 'a tree = | Leaf of 'a | Tree of 'a tree  * 'a tree")));
        assertEquals("tree", type.getName());
    }

    public void test_path() {
        PsiType e = first(typeExpressions(parseCode("type t = A.B.other")));

        assertEquals("t", e.getName());
        assertFalse(e.isAbstract());
        assertEquals("A.B.other", e.getBinding().getText());
        assertNull(PsiTreeUtil.findChildOfType(e, PsiVariantDeclaration.class));
        List<PsiUpperSymbol> modules = ORUtil.findImmediateChildrenOfClass(e.getBinding(), PsiUpperSymbol.class);
        assertSize(2, modules);
        List<IElementType> es = modules.stream().map(u -> u.getNode().getElementType()).collect(Collectors.toList());
        assertEquals(List.of(myTypes.A_MODULE_NAME, myTypes.A_MODULE_NAME), es);
    }

    public void test_option() {
        PsiType e = first(typeExpressions(parseCode("type t = string array option")));

        PsiOption option = PsiTreeUtil.findChildOfType(e, PsiOption.class);
        assertNotNull(option);
        assertEquals("string array option", option.getText());
    }

    public void test_bindingWithVariant() {
        PsiType e = first(typeExpressions(parseCode("type t = | Tick")));

        PsiTypeBinding binding = first(findChildrenOfType(e, PsiTypeBinding.class));
        assertNotNull(binding);
    }

    public void test_bindingWithRecord() {
        PsiFile file = parseCode("type t = {count: int;}");

        assertNotNull(first(findChildrenOfType(first(typeExpressions(file)), PsiTypeBinding.class)));
    }

    public void test_closed_object() {
        PsiType e = first(typeExpressions(parseCode("type t = <count: int>\n type x")));

        PsiElement b = e.getBinding();
        assertEquals("<count: int>", b.getText());
        assertInstanceOf(b.getFirstChild(), PsiObject.class);
    }

    public void test_open_object() {
        PsiType e = first(typeExpressions(parseCode("type 'a t = < .. > as 'a\n type x")));

        PsiElement b = e.getBinding();
        assertEquals("< .. > as 'a", b.getText());
        assertInstanceOf(b.getFirstChild(), PsiObject.class);
    }

    public void test_binding_with_record_as() {
        PsiTypeBinding typeBinding = first(findChildrenOfType(first(typeExpressions(parseCode(
                "type 'branch_type branch_info = { kind : [> `Master] as 'branch_type; pos : id; }"))), PsiTypeBinding.class));

        PsiRecord record = PsiTreeUtil.findChildOfType(typeBinding, PsiRecord.class);
        List<PsiRecordField> fields = new ArrayList<>(record.getFields());
        assertEquals(2, fields.size());
        assertEquals("kind", fields.get(0).getName());
        assertEquals("pos", fields.get(1).getName());
    }

    public void test_chain_definitions() {
        FileBase file = parseCode("type 'branch_type branch_info = 'branch_type Vcs_.branch_info = { kind: [> `Master] as 'branch_type; root: id; pos: id; }");

        assertEquals(1, childrenCount(file));
    }

    public void test_parameterizedType() {
        PsiType e = first(typeExpressions(parseCode("type ('a, 'b) declaration_arity = | RegularArity of 'a")));

        assertEquals("declaration_arity", e.getName());
        assertEquals("| RegularArity of 'a", e.getBinding().getText());
    }

    public void test_apply_params() {
        PsiType e = first(typeExpressions(parseCode("type 'value t = (key,'value,Comparator.identity) Belt.Map.t")));

        assertEmpty(PsiTreeUtil.findChildrenOfType(e, PsiParameters.class));
    }

    public void test_qname_functor() {
        PsiType e = first(typeExpressions(parseCode("module Coll = Hash.Make(struct type nonrec t = t\n let equal = " +
                "Bsb_pkg_types.equal\n let hash (x : t) = Hashtbl.hash x\n end)")));

        assertEquals("Dummy.Coll.Make[0].t", e.getQualifiedName());
    }

    // https://github.com/giraud/reasonml-idea-plugin/issues/295
    public void test_GH_295() {
        Collection<PsiNamedElement> es = expressions(parseCode("module Set = struct end type x = string"));

        assertSize(2, es);
        Iterator<PsiNamedElement> it = es.iterator();
        assertInstanceOf(it.next(), PsiModule.class);
        assertInstanceOf(it.next(), PsiType.class);
    }

    // https://github.com/giraud/reasonml-idea-plugin/issues/326
    public void test_GH_326() {
        PsiType e = firstOfType(parseCode("type t = { buffer: GText.buffer; mutable breakpoints: breakpoint list }"), PsiType.class);

        PsiRecord r = (PsiRecord) e.getBinding().getFirstChild();
        List<PsiRecordField> f = r.getFields();
        assertSize(2, f);
        assertEquals("buffer", f.get(0).getName());
        assertEquals("breakpoints", f.get(1).getName());
    }

    // https://github.com/giraud/reasonml-idea-plugin/issues/360
    public void test_GH_360() {
        PsiVal e = firstOfType(parseCode("val push : exn -> Exninfo.iexn\n [@@ocaml.deprecated \"please use [Exninfo.capture]\"]"), PsiVal.class);

        PsiSignature signature = e.getSignature();
        assertEquals("exn -> Exninfo.iexn", signature.getText());
    }
}


text:
BINARY=lastz
BINARY_HOME=$PREFIX/bin
POST_LINK=$BINARY_HOME/$BINARY

# go to lastz
cd $SRC_DIR

# build source
make
make test

# copy source to bin
mkdir $BINARY_HOME
cp $SRC_DIR/src/$BINARY $POST_LINK
chmod +x $POST_LINK


text:
<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\Fotos;
use gudezi\croppic\actions\CropAction;
use gudezi\croppic\actions\UploadAction;

class UploadCropController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'upload' => ['post','get'],
                    'crop' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        $id = Yii::$app->request->get('id');
        if($id>0)
            $model = $this->findModel($id);
        else
            $model = new Fotos();

        return [
            'upload' => [
                'class' => 'gudezi\croppic\actions\UploadAction',
                'tempPath' => '@backend/web/img/temp',
                'tempUrl' => '../img/temp/',
                'modelAttribute' => 'urlUpload',
                'model' => $model,
                'validatorOptions' => [
                    'checkExtensionByMimeType' => true,
                    'extensions' => 'jpeg, jpg, png',
                    'maxSize' => 3000000,
                    'tooBig' => 'Ha seleccionado una imagen demasiado grande (máx. 3 MB)',
                ],
            ],
            'crop' => [
                'class' => 'gudezi\croppic\actions\CropAction',
                'path' => '@backend/web/img/user/avatar',
                'url' => '../img/user/avatar/',
                'modelAttribute' => 'urlUpload',
                'model' => $model,
            ],
        ];
    }

    protected function findModel($id)
    {
        if (($model = Fotos::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
package org.javasimon.callback.logging;

/**
 * Log template class is the root of a hierarchy of implementations with different purposes.
 *
 * @author gquintana
 */
public abstract class LogTemplate<C> {

	/**
	 * If enabled, logs the message for context.
	 *
	 * @param context Context
	 * @param messageSource Message producer
	 * @return true if logging is enabled, false otherwise
	 */
	public final boolean log(C context, LogMessageSource<C> messageSource) {
		final boolean enabled = isEnabled(context);
		if (enabled) {
			log(messageSource.getLogMessage(context));
		}
		return enabled;
	}

	/**
	 * Tells whether logging is enabled.
	 *
	 * @return Logging enabled
	 */
	protected abstract boolean isEnabled(C context);

	/** Logs a message. */
	protected abstract void log(String message);
}


text:
{{ Form::open('/donations/'.( $new ? '' : 'update'), $new ? 'POST' : 'PUT', array('class' => 'form-horizontal')) }}
	@if (!$new)
	{{ Form::hidden('id', $donation->id); }}
	@endif

	{{ Form::label('donation_date', 'Donation Date', array('class' => 'control-label')) }}

		{{ Form::text('donation_date', $new ? date('Y-m-d') : AppHelper::date($donation->donation_date), array('class' => 'datepick')) }}

	{{ Form::label('amount', 'Amount', array('class' => 'control-label')) }}

		{{ Form::text('amount', $new ? '' : $donation->amount, array('placeholder' => 'Amount')) }}

	{{ Form::label('remark', 'Remark', array('class' => 'control-label')) }}

		{{ Form::textarea('remark', $new ? '' : $donation->remark, array('placeholder' => 'Remark')); }}

	{{ Form::label('account_id', 'Account', array('class' => 'control-label')) }}

		{{ Form::select('account_id', $accounts, $new ? '' : $donation->account_id); }}

	{{ Form::label('category_id', 'Category', array('class' => 'control-label')) }}

		{{ Form::select('category_id', $categories, $new ? '' : $donation->category_id); }}

			{{ Form::submit('Save', array('class' => 'btn')) }}
			{{ HTML::link_to_action('donations@index', 'Back', array(), array('class' => 'btn')) }}

{{ Form::close() }}


text:
package v7action

import (
	"errors"
	"strings"
	"time"

	"code.cloudfoundry.org/cli/actor/actionerror"
	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3"
	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/constant"
	"code.cloudfoundry.org/cli/resources"

	log "github.com/sirupsen/logrus"
)

func (actor Actor) StagePackage(packageGUID, appName, spaceGUID string) (<-chan resources.Droplet, <-chan Warnings, <-chan error) {
	dropletStream := make(chan resources.Droplet)
	warningsStream := make(chan Warnings)
	errorStream := make(chan error)
	go func() {
		defer close(dropletStream)
		defer close(warningsStream)
		defer close(errorStream)

		apps, warnings, err := actor.GetApplicationsByNamesAndSpace([]string{appName}, spaceGUID)
		warningsStream <- warnings
		if err != nil {
			if _, ok := err.(actionerror.ApplicationsNotFoundError); ok {
				err = actionerror.ApplicationNotFoundError{Name: appName}
			}
			errorStream <- err
			return
		}
		app := apps[0]

		pkgs, allWarnings, err := actor.CloudControllerClient.GetPackages(ccv3.Query{
			Key: ccv3.AppGUIDFilter, Values: []string{app.GUID},
		})
		warningsStream <- Warnings(allWarnings)
		if err != nil {
			errorStream <- err
			return
		}

		if !packageInPackages(packageGUID, pkgs) {
			err = actionerror.PackageNotFoundInAppError{GUID: packageGUID, AppName: appName}
			errorStream <- err
			return
		}

		build := resources.Build{PackageGUID: packageGUID}
		build, allWarnings, err = actor.CloudControllerClient.CreateBuild(build)
		warningsStream <- Warnings(allWarnings)

		if err != nil {
			errorStream <- err
			return
		}

		timer := actor.Clock.NewTimer(time.Millisecond)
		defer timer.Stop()
		timeout := actor.Clock.After(actor.Config.StagingTimeout())

		for {
			select {
			case <-timeout:
				errorStream <- actionerror.StagingTimeoutError{AppName: appName, Timeout: actor.Config.StagingTimeout()}
				return
			case <-timer.C():
				var warnings ccv3.Warnings
				build, warnings, err = actor.CloudControllerClient.GetBuild(build.GUID)
				warningsStream <- Warnings(warnings)
				if err != nil {
					errorStream <- err
					return
				}

				switch build.State {
				case constant.BuildFailed:
					if strings.Contains(build.Error, "NoAppDetectedError") {
						errorStream <- actionerror.StagingFailedNoAppDetectedError{Reason: build.Error}
					} else {
						errorStream <- actionerror.StagingFailedError{Reason: build.Error}
					}
					return
				case constant.BuildStaging:
					timer.Reset(actor.Config.PollingInterval())
				default:

					//TODO: uncomment after #150569020
					// droplet, warnings, err := actor.CloudControllerClient.GetDroplet(build.DropletGUID)
					// warningsStream <- Warnings(warnings)
					// if err != nil {
					// 	errorStream <- err
					// 	return
					// }

					droplet := resources.Droplet{
						GUID:      build.DropletGUID,
						State:     constant.DropletState(build.State),
						CreatedAt: build.CreatedAt,
					}

					dropletStream <- droplet
					return
				}
			}
		}
	}()

	return dropletStream, warningsStream, errorStream
}

func (actor Actor) StageApplicationPackage(packageGUID string) (resources.Build, Warnings, error) {
	var allWarnings Warnings

	build := resources.Build{PackageGUID: packageGUID}
	build, warnings, err := actor.CloudControllerClient.CreateBuild(build)
	log.Debug("created build")
	allWarnings = append(allWarnings, warnings...)
	if err != nil {
		return resources.Build{}, allWarnings, err
	}

	log.Debug("no errors creating build")
	return resources.Build{GUID: build.GUID}, allWarnings, nil
}

func (actor Actor) PollBuild(buildGUID string, appName string) (resources.Droplet, Warnings, error) {
	var allWarnings Warnings

	timeout := actor.Clock.After(actor.Config.StagingTimeout())
	interval := actor.Clock.NewTimer(time.Millisecond)

	for {
		select {
		case <-interval.C():
			build, warnings, err := actor.CloudControllerClient.GetBuild(buildGUID)
			allWarnings = append(allWarnings, warnings...)
			if err != nil {
				return resources.Droplet{}, allWarnings, err
			}

			switch build.State {
			case constant.BuildFailed:
				return resources.Droplet{}, allWarnings, errors.New(build.Error)

			case constant.BuildStaged:
				droplet, warnings, err := actor.CloudControllerClient.GetDroplet(build.DropletGUID)
				allWarnings = append(allWarnings, warnings...)
				if err != nil {
					return resources.Droplet{}, allWarnings, err
				}

				return resources.Droplet{
					GUID:      droplet.GUID,
					State:     droplet.State,
					CreatedAt: droplet.CreatedAt,
				}, allWarnings, nil
			}

			interval.Reset(actor.Config.PollingInterval())

		case <-timeout:
			return resources.Droplet{}, allWarnings, actionerror.StagingTimeoutError{AppName: appName, Timeout: actor.Config.StagingTimeout()}
		}
	}
}

func packageInPackages(targetPkgGUID string, pkgs []resources.Package) bool {
	for i := range pkgs {
		if pkgs[i].GUID == targetPkgGUID {
			return true
		}
	}
	return false
}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}

module Client where

import Control.Applicative
import Control.Monad
import Control.Monad.Catch (MonadThrow)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trans.Control (MonadBaseControl)

import Data.Aeson
import Data.Aeson.Lens

-- applyBasicAuth expects a strict ByteString
import Data.ByteString.Lazy.Char8 hiding (filter, foldl)

import qualified Data.ByteString.Char8 as BC
import Data.Maybe
import Data.Text as T hiding (foldl)
import Network.HTTP.Conduit

--------------------------------------------------------------------------------
-- Response
--------------------------------------------------------------------------------

-- | Some hacking around....


text:
namespace SEQAN_NAMESPACE_MAIN
{

    //////////////////////////////////////////////////////////////////////////////
    // page based read/write for striped files

	template < typename TValue, unsigned FILE_COUNT, typename TFile, typename TSpec >
	inline bool
	readPage(
		int pageNo,
		PageFrame<TValue, File< Striped<FILE_COUNT, TFile> >, TSpec> &pf,
		File< Striped<FILE_COUNT, TFile> > &file)
	{
		typedef typename Position<TFile>::Type pos_t;
		#ifdef SEQAN_VVERBOSE
			::std::cerr << "readPage:  " << ::std::hex << (TValue*)pf.begin;
			::std::cerr << " from page " << ::std::dec << pageNo << ::std::endl;
		#endif
		pf.dirty = false;
		pf.status = pf.READING;
		return asyncReadAt(
			file[pageNo % FILE_COUNT],
			(TValue*)pf.begin,
			size(pf),
			(pos_t)(pageNo / FILE_COUNT) * (pos_t)pageSize(pf),
			pf.request);
	}

	template < typename TValue, unsigned FILE_COUNT, typename TFile, typename TSpec >
	inline bool
	writePage(
		PageFrame<TValue, File< Striped<FILE_COUNT, TFile> >, TSpec> &pf,
		int pageNo,
		File< Striped<FILE_COUNT, TFile> > &file)
	{
		typedef typename Position<TFile>::Type pos_t;
		#ifdef SEQAN_VVERBOSE
			::std::cerr << "writePage: " << ::std::hex << (TValue*)pf.begin;
			::std::cerr << " from page " << ::std::dec << pageNo << ::std::endl;
		#endif
		pf.status = pf.WRITING;
		return asyncWriteAt(
			file[pageNo % FILE_COUNT],
			(TValue*)pf.begin,
			size(pf),
			(pos_t)(pageNo / FILE_COUNT) * (pos_t)pageSize(pf),
			pf.request);
	}

	template < typename TValue, unsigned FILE_COUNT, typename TFile, typename TSpec, typename TSize >
	inline bool
	readLastPage(
		int pageNo,
		PageFrame<TValue, File< Striped<FILE_COUNT, TFile> >, TSpec> &pf,
		File< Striped<FILE_COUNT, TFile> > &file,
		TSize size)
	{
		typedef typename Position<TFile>::Type pos_t;
		#ifdef SEQAN_VVERBOSE
			::std::cerr << "readPage:  " << ::std::hex << (TValue*)pf.begin;
			::std::cerr << " from page " << ::std::dec << pageNo << " size " << size << ::std::endl;
		#endif
		pf.dirty = false;
		pf.status = pf.READY;
		return readAt(
			file[pageNo % FILE_COUNT],
			(TValue*)pf.begin,
			size,
			(pos_t)(pageNo / FILE_COUNT) * (pos_t)pageSize(pf));
	}

	template < typename TValue, unsigned FILE_COUNT, typename TFile, typename TSpec, typename TSize >
	inline bool
	writeLastPage(
		PageFrame<TValue, File< Striped<FILE_COUNT, TFile> >, TSpec> &pf,
		int pageNo,
		File< Striped<FILE_COUNT, TFile> > &file,
		TSize size)
	{
		typedef typename Position<TFile>::Type pos_t;
		#ifdef SEQAN_VVERBOSE
			::std::cerr << "writePage: " << ::std::hex << (TValue*)pf.begin;
			::std::cerr << " from page " << ::std::dec << pageNo << " size " << size << ::std::endl;
		#endif
		pf.dirty = false;
		pf.status = pf.READY;
//        resize(pf, size);
		return writeAt(
			file[pageNo % FILE_COUNT],
			(TValue*)pf.begin,
			size,
			(pos_t)(pageNo / FILE_COUNT) * (pos_t)pageSize(pf));
	}

	//////////////////////////////////////////////////////////////////////////////
	// bucket based read/write methods for striped files

	template < typename TValue, unsigned FILE_COUNT, typename TFile >
	inline unsigned
	readBucket(
		PageBucket<TValue> &b,
		int pageNo,
		unsigned pageSize,
		unsigned dataSize,
		File< Striped<FILE_COUNT, TFile> > &file)
	{
		typedef typename Position<TFile>::Type pos_t;
        unsigned readSize = _min(dataSize - b.pageOfs, (unsigned)(b.end - b.begin));
		#ifdef SEQAN_VVERBOSE
			::std::cerr << "readBucket:  " << ::std::hex << b.begin;
			::std::cerr << " from page " << ::std::dec << pageNo << " at " << (pos_t)(pageNo / FILE_COUNT) * (pos_t)pageSize + b.pageOfs;
			::std::cerr << " size " << readSize << ::std::endl;
		#endif
        if (readSize && readAt(file[pageNo % FILE_COUNT], b.begin, readSize, (pos_t)(pageNo / FILE_COUNT) * (pos_t)pageSize + b.pageOfs)) {
            b.pageOfs += readSize;
            b.cur = b.begin;
            b.end = b.begin + readSize;
            return readSize;
        } else
            return 0;
	}

	template < typename TValue, unsigned FILE_COUNT, typename TFile >
	inline bool
	writeBucket(
		PageBucket<TValue> &b,
		int pageNo,
		unsigned pageSize,
		File< Striped<FILE_COUNT, TFile> > &file)
	{
		typedef typename Position<TFile>::Type pos_t;
		#ifdef SEQAN_VVERBOSE
			::std::cerr << "writeBucket: " << ::std::hex << b.begin;
			::std::cerr << " from page " << ::std::dec << pageNo << " at " << (pos_t)(pageNo / FILE_COUNT) * (pos_t)pageSize + b.pageOfs;
			::std::cerr << " size " << b.cur - b.begin << ::std::endl;
		#endif
        if ((b.cur == b.begin) || writeAt(file[pageNo % FILE_COUNT], b.begin, b.cur - b.begin, (pos_t)(pageNo / FILE_COUNT) * (pos_t)pageSize + b.pageOfs)) {
            b.pageOfs += b.cur - b.begin;
            b.cur = b.begin;
            return true;
        } else
            return false;
	}

	template < typename TValue, unsigned FILE_COUNT, typename TFile, typename TSpec >
	inline bool
	writeBucket(
		PageFrame<TValue, File< Striped<FILE_COUNT, TFile> >, Dynamic<TSpec> > &pf,
		unsigned &pageOfs,
		File< Striped<FILE_COUNT, TFile> > &file)
	{
		typedef typename Position<TFile>::Type pos_t;
		#ifdef SEQAN_VVERBOSE
			::std::cerr << "writeBucket: " << ::std::hex << pf.begin;
			::std::cerr << " from page " << ::std::dec << pf.pageNo << " at " << (pos_t)(pf.pageNo / FILE_COUNT) * (pos_t)pageSize(pf) + pageOfs;
			::std::cerr << " size " << size(pf) << ::std::endl;
		#endif
        if (pf.end == pf.begin) return true;
        if (asyncWriteAt(file[pf.pageNo % FILE_COUNT], pf.begin, size(pf), (pos_t)(pf.pageNo / FILE_COUNT) * (pos_t)pageSize(pf) + pageOfs, pf.request)) {
            pf.status = pf.WRITING;
            pageOfs += size(pf);
            return true;
        } else
            return false;
	}

}

#endif


text:
<?php
namespace Acf\DataBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Acf\DataBundle\Entity\MPaye;

/**
 * MSalaryRepository
 * This class was generated by the Doctrine ORM.
 * Add your own custom
 * repository methods below.
 */
class MSalaryRepository extends EntityRepository
{

    /**
     * Get Query for All Entities
     *
     * @param MPaye $p
     *
     * @return \Doctrine\ORM\Query
     */
    public function getAllByMPayeQuery(MPaye $p)
    {
        $qb = $this->createQueryBuilder('s')
            ->join('s.paye', 'p')
            ->where('p.id = :id')
            ->orderBy('m.matricule', 'ASC')
            ->setParameter('id', $p->getId());
        $query = $qb->getQuery();

        return $query;
    }

    /**
     * Get All Entities
     *
     * @param MPaye $p
     *
     * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL
     */
    public function getAllByMPaye(MPaye $p)
    {
        return $this->getAllByMPayeQuery($p)->execute();
    }
}


text:
import { Component, OnInit } from '@angular/core';
import {ObsUsersService} from './obs-users.service';

@Component({
  selector: 'app-section13',
  templateUrl: './section13.component.html',
  styleUrls: ['./section13.component.css']
})
export class Section13Component implements OnInit {
  user1Activated = false;
  user2Activated = false;

  constructor(private obsUsersService: ObsUsersService) { }

  ngOnInit() {
    this.obsUsersService.userActivated.subscribe(
      (id: number) => {
        if (id === 1) {
          this.user1Activated = true;
        } else if (id === 2) {
          this.user2Activated = true;
        }
      }
    )
  }

}


text:
require 'spec_helper'

describe S3Uploader do

  let(:tmp_directory) do
    File.join(Dir.tmpdir, 'test_s3_uploader')
  end
  let(:access) do
    %w(access.log access.log.1 access.log.2.gz subdir/access.log subdir/access.log.1 subdir/access.log.2.gz) +
    [ File.join('subdirX', tmp_directory, 'somefile-access.txt')]
  end
  let(:error) do
    %w(error.log error.log.1 error.log.2.gz subdir/error.log subdir/error.log.1 subdir/error.log.2.gz)
  end
  let(:logger) do
    Logger.new(STDOUT)
  end

  let(:connection) do
    Fog.mock!

    connection = Fog::Storage.new({
      :provider                 => 'AWS',
      :aws_access_key_id        => '11111111111',
      :aws_secret_access_key    => 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
    })

  end

  before(:each) do
    Fog::Mock.reset

    connection.directories.create(
      :key    => 'mybucket',
      :public => true
    )

    FileUtils.rm_rf(Dir.glob(File.join(tmp_directory, '*')))

    (access + error).each do |file|
      directory, basename = File.split(File.join(tmp_directory, file))
      FileUtils.mkdir_p directory
      create_test_file(File.join(directory, basename), 1)
    end
  end

  it 'when called with missing access keys it should raise an exception' do
    expect {
      S3Uploader.upload('/tmp', 'mybucket',
                                  { destination_dir: 'test1/',
                                    s3_key:          nil,
                                    s3_secret:       nil })
    }.to raise_error('Missing access keys')
  end

  it 'when called with source not directory it should raise an exception' do
    expect {
      S3Uploader.upload('/xzzaz1232', 'mybucket', {
        s3_key:          '11111111111',
        s3_secret:       'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
        })
    }.to raise_error('Source must be a directory')
  end

  it 'should upload all files in a directory' do
    expect(connection.directories.get('mybucket', prefix: 'test1/').files.empty?).to be true

    S3Uploader.upload(tmp_directory, 'mybucket',
                                { destination_dir: 'test1/',
                                  logger:          logger,
                                  connection:      connection })

    files = connection.directories.get('mybucket', prefix: 'test1/').files
    expect(files).to have((access + error).size).items
    expect(files.map(&:key)).to match_array((access + error).map { |f| File.join('test1/', f) })
  end

  it 'should still support upload_directory static method for backwards compatibility' do
    expect(connection.directories.get('mybucket', prefix: 'test1/').files.empty?).to be true

    S3Uploader.upload_directory(tmp_directory, 'mybucket',
                                { destination_dir: 'test1/',
                                  logger:          logger,
                                  connection:      connection })

    files = connection.directories.get('mybucket', prefix: 'test1/').files
    expect(files).to have((access + error).size).items
    expect(files.map(&:key)).to match_array((access + error).map { |f| File.join('test1/', f) })
  end

  describe 'regexp' do

    it 'should upload specific files' do

      S3Uploader.upload(tmp_directory, 'mybucket',
                                  { logger:     logger,
                                    connection: connection,
                                    regexp:     /access/ })

      files = connection.directories.get('mybucket').files
      expect(files).to have(access.size).items
      expect(files.map(&:key)).to match_array(access)
    end

  end

  describe 'gzip' do

    it "should require a gzip working directory" do
      expect {
        S3Uploader.upload('/tmp', 'mybucket',
                                    { logger:     logger,
                                      connection: connection,
                                      gzip: true })
      }.to raise_error('gzip_working_dir required when using gzip')
    end

    it 'should compress files before upload when needed' do
      working_dir = File.join(Dir.tmpdir, 's3uploader_spec/working_dir')
      FileUtils.mkdir_p working_dir
      FileUtils.rm_rf(Dir.glob(File.join(working_dir, '*')))

      S3Uploader.upload(tmp_directory, 'mybucket',
                                  { logger:           logger,
                                    connection:       connection,
                                    regexp:           /error/,
                                    gzip:             true,
                                    gzip_working_dir: working_dir })

      files = connection.directories.get('mybucket').files
      expect(files).to have(error.size).items
      expect(files.map(&:key)).to match_array(error.map { |f| File.extname(f) != '.gz' ? [f, '.gz'].join : f })
    end

    it 'when called with bad gzip_working_dir it should raise an exception' do
      expect {
        S3Uploader.upload(tmp_directory, 'mybucket', {
                                  s3_key:          '11111111111',
                                  s3_secret:       'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
                                  gzip:             true,
                                  gzip_working_dir: File.join(tmp_directory, 'working_dir') })
      }.to raise_error('gzip_working_dir may not be located within source-folder')

      expect {
        S3Uploader.upload(tmp_directory, 'mybucket',
                                    { logger:           logger,
                                      connection:       connection,
                                      regexp:           /non_matching/,
                                      gzip:             true,
                                      gzip_working_dir: File.join(Dir.tmpdir, 'test_s3_uploader_working_dir') })
      }.to_not raise_error

    end

    # Run with: rspec --tag slow
    it 'uploads large files', :slow do
      working_dir = File.join(Dir.tmpdir, 's3uploader_big_file_spec/working_dir')
      big_file_dir = File.join(Dir.tmpdir, 'test_s3_uploader_big_file')
      FileUtils.mkdir_p working_dir
      FileUtils.mkdir_p  big_file_dir
      create_test_file(File.join(big_file_dir, 'test_big_file.dmp'), 2*1024)

      S3Uploader.upload(big_file_dir, 'mybucket',
                                  { logger:          logger,
                                    connection:      connection,
                                    gzip:             true,
                                    gzip_working_dir: working_dir })

      files = connection.directories.get('mybucket').files
      expect(files.map(&:key)).to match_array([ 'test_big_file.dmp.gz' ])

      FileUtils.rm_rf(Dir.glob(File.join(working_dir, '*')))
      FileUtils.rm_rf(Dir.glob(File.join(big_file_dir, '*')))
    end
  end

  describe 'time_range' do

    it 'should not upload any files' do
      file_names = access.map { |f| File.join( tmp_directory, f) }
      yesterday  = Time.now - (60 * 60 * 24)
      File.utime(yesterday, yesterday, *file_names)

      S3Uploader.upload(tmp_directory, 'mybucket',
                                  { logger:     logger,
                                    connection: connection,
                                    regexp:     /access/,
                                    time_range: (Time.now - (60 * 60 * 12))..Time.now })

      files = connection.directories.get('mybucket').files
      expect(files).to have(0).items
    end

    it 'should upload files' do
      file_names = access.map { |f| File.join( tmp_directory, f) }
      yesterday  = Time.now - (60 * 60 * 12)
      File.utime(yesterday, yesterday, *file_names)

      S3Uploader.upload(tmp_directory, 'mybucket',
                                  { logger:     logger,
                                    connection: connection,
                                    regexp:     /access/,
                                    time_range: (Time.now - (60 * 60 * 24))..Time.now })

      files = connection.directories.get('mybucket').files
      expect(files).to have(access.size).items
      expect(files.map(&:key)).to match_array(access)
    end

  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<!-- Definition for textEditor bean -->
	<bean id="textEditor" class="com.tutorialspoint.beansautowiring.TextEditor">
		<property name="spellChecker" ref="spellChecker" />
		<property name="name" value="Generic Text Editor" />
	</bean>

	<!-- Definition for textEditor bean -->
	<bean id="textEditorByName" class="com.tutorialspoint.beansautowiring.TextEditor"
		autowire="byName">
		<property name="name" value="Generic Text Editor ByName" />
	</bean>

	<!-- Definition for textEditor bean -->
	<bean id="textEditorByType" class="com.tutorialspoint.beansautowiring.TextEditor"
		autowire="byType">
		<property name="name" value="Generic Text Editor ByType" />
	</bean>

	<!-- Definition for textEditor bean -->
	<bean id="textEditorConstr" class="com.tutorialspoint.beansautowiring.TextEditor">
		<constructor-arg ref="spellChecker" />
		<constructor-arg value="Generic Text Editor" />
	</bean>

	<!-- Definition for textEditor bean -->
	<bean id="textEditorConstructor" class="com.tutorialspoint.beansautowiring.TextEditor"
		autowire="constructor">
		<constructor-arg value="Generic Text Editor Constructor" />
	</bean>

	<!-- Definition for spellChecker bean -->
	<bean id="spellChecker" class="com.tutorialspoint.beansautowiring.SpellChecker">
	</bean>

</beans>


text:
module HealthDataStandards
  module Import
    module CCDA
      class ResultImporter < CDA::ResultImporter
        def initialize
          super(CDA::EntryFinder.new("//cda:observation[cda:templateId/@root='2.16.840.1.113883.10.20.22.4.2']"))
        end
      end
    end
  end
end


text:
using System.Reflection;
using System.Runtime.CompilerServices;

[assembly: AssemblyTitle("Obvs.MessageDispatcher.Autofac")]
[assembly: AssemblyDescription("Autofac integration support for the Obvs.MessageDispatcher framework.")]

#if DEBUG
[assembly: AssemblyConfiguration("DEBUG")]
#else
[assembly: AssemblyConfiguration("RELEASE")]
#endif

[assembly: AssemblyProduct("Obvs.MessageDispatcher")]
[assembly: AssemblyCopyright("Copyright ©  2015")]

[assembly: AssemblyVersion("0.2.*")]
[assembly: AssemblyInformationalVersion("0.2.0-alpha")]

[assembly: InternalsVisibleTo("Obvs.MessageDispatcher.Autofac.Tests")]


text:
using System;
using System.Web.Mvc;

using SDNUOJ.Controllers.Core;
using SDNUOJ.Controllers.Exception;

namespace SDNUOJ.Controllers.Attributes
{
    /// <summary>
    /// 仅限Access数据库特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AccessDatabaseOnlyAttribute : ActionFilterAttribute
    {
        #region 方法
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!DatabaseManager.IsAccessDB)
            {
                throw new DatabaseNotSupportException();
            }
        }
        #endregion
    }
}


text:
package moe.frc365.commands;

import edu.wpi.first.wpilibj.DriverStation;

/**
 *
 * @author bradmiller
 */
public class ResetTurns extends CommandBase {

    public ResetTurns() {
        // Use requires() here to declare subsystem dependencies
        requires(swerveDrive);
        setRunWhenDisabled(true);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return /*!DriverStation.getInstance().isDisabled() ||*/ swerveDrive.resetTurns();
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
import numpy as np
import sys

sys.path.append("..")
import paddle
from op_test import OpTest, skip_check_grad_ci
from op_test_xpu import XPUOpTest
import unittest
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard

paddle.enable_static()

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp(XPUOpTest):
    def setUp(self):
        self.op_type = "elementwise_add"
        self.init_dtype()
        self.init_input_output()
        self.init_axis()
        self.init_max_relative_error()
        self.inputs = {
            'X': OpTest.np_dtype_to_fluid_dtype(self.x),
            'Y': OpTest.np_dtype_to_fluid_dtype(self.y),
        }
        self.attrs = {'axis': self.axis, 'use_mkldnn': self.use_mkldnn}
        self.outputs = {'Out': self.out}

    def test_check_output(self):
        if paddle.is_compiled_with_xpu():
            place = paddle.XPUPlace(0)
            self.check_output_with_place(place)

    def test_check_grad_normal(self):
        if paddle.is_compiled_with_xpu():
            place = paddle.XPUPlace(0)
            self.check_grad_with_place(
                place,
                ['X', 'Y'],
                'Out',
                max_relative_error=self.max_relative_error,
            )

    def test_check_grad_ingore_x(self):
        if paddle.is_compiled_with_xpu():
            place = paddle.XPUPlace(0)
            self.check_grad_with_place(
                place,
                ['Y'],
                'Out',
                no_grad_set=set("X"),
                max_relative_error=self.max_relative_error,
            )

    def test_check_grad_ingore_y(self):
        if paddle.is_compiled_with_xpu():
            place = paddle.XPUPlace(0)
            self.check_grad_with_place(
                place,
                ['X'],
                'Out',
                no_grad_set=set("Y"),
                max_relative_error=self.max_relative_error,
            )

    def init_input_output(self):
        self.x = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)
        self.y = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)
        self.out = np.add(self.x, self.y)

    def init_dtype(self):
        self.dtype = np.float32

    def init_axis(self):
        self.axis = -1

    def init_max_relative_error(self):
        self.max_relative_error = 0.006

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
@skip_check_grad_ci(
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
class TestElementwiseAddOp_scalar(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
@skip_check_grad_ci(
    reason="[skip shape check] Use y_shape(1,1) to test broadcast."
)
class TestElementwiseAddOp_scalar2(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1, 1).astype(self.dtype)
        self.out = self.x + self.y

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_Vector(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.random((100,)).astype(self.dtype)
        self.y = np.random.random((100,)).astype(self.dtype)
        self.out = np.add(self.x, self.y)

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_broadcast_0(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(100, 2, 3).astype(self.dtype)
        self.y = np.random.rand(100).astype(self.dtype)
        self.out = self.x + self.y.reshape(100, 1, 1)

    def init_axis(self):
        self.axis = 0

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_broadcast_1(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 100, 3).astype(self.dtype)
        self.y = np.random.rand(100).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 100, 1)

    def init_axis(self):
        self.axis = 1

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_broadcast_2(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 100).astype(self.dtype)
        self.y = np.random.rand(100).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1, 100)

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_broadcast_3(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 10, 12, 3).astype(self.dtype)
        self.y = np.random.rand(10, 12).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 10, 12, 1)

    def init_axis(self):
        self.axis = 1

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_broadcast_4(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(100, 2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(100, 1).astype(self.dtype)
        self.out = self.x + self.y.reshape(100, 1, 1, 1)

    def init_axis(self):
        self.axis = 0

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_broadcast_5(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(10, 3, 12).astype(self.dtype)
        self.y = np.random.rand(10, 1, 12).astype(self.dtype)
        self.out = self.x + self.y

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_broadcast_6(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 12, 3, 5).astype(self.dtype)
        self.y = np.random.rand(2, 12, 1, 5).astype(self.dtype)
        self.out = self.x + self.y

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_broadcast_7(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(1, 1, 20, 5).astype(self.dtype)
        self.y = np.random.rand(20, 5, 1, 1).astype(self.dtype)
        self.out = self.x + self.y

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_rowwise_add_0(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 10, 12).astype(self.dtype)
        self.y = np.random.rand(10, 12).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 10, 12)

    def init_axis(self):
        self.axis = 1

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
@skip_check_grad_ci(
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
class TestElementwiseAddOp_rowwise_add_1(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(100, 1).astype(self.dtype)
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1)

    def init_axis(self):
        self.axis = 1

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_channelwise_add(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(100, 2, 3).astype(self.dtype)
        self.y = np.random.rand(100, 1, 1).astype(self.dtype)
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_commonuse_add1(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 100).astype(self.dtype)
        self.y = np.random.rand(1, 1, 100).astype(self.dtype)
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_commonuse_add2(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(10, 3, 1, 4).astype(self.dtype)
        self.y = np.random.rand(10, 1, 12, 1).astype(self.dtype)
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOp_xsize_lessthan_ysize_add(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(10, 12).astype(self.dtype)
        self.y = np.random.rand(2, 3, 10, 12).astype(self.dtype)
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = 2

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestElementwiseAddOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):
            # the input of elementwise_add must be Variable.
            x1 = fluid.create_lod_tensor(
                np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.XPUPlace(0)
            )
            y1 = fluid.create_lod_tensor(
                np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.XPUPlace(0)
            )
            self.assertRaises(TypeError, fluid.layers.elementwise_add, x1, y1)

            # the input dtype of elementwise_add must be float16 or float32 or float64 or int32 or int64
            # float16 only can be set on GPU place
            x2 = fluid.layers.data(name='x2', shape=[3, 4, 5, 6], dtype="uint8")
            y2 = fluid.layers.data(name='y2', shape=[3, 4, 5, 6], dtype="uint8")
            self.assertRaises(TypeError, fluid.layers.elementwise_add, x2, y2)

@unittest.skipIf(
    not paddle.is_compiled_with_xpu(), "core is not compiled with XPU"
)
class TestAddOp(unittest.TestCase):
    def test_name(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data(name="x", shape=[2, 3], dtype="float32")
            y = fluid.data(name='y', shape=[2, 3], dtype='float32')

            y_1 = paddle.add(x, y, name='add_res')
            self.assertEqual(('add_res' in y_1.name), True)

    def test_declarative(self):
        with fluid.program_guard(fluid.Program()):

            def gen_data():
                return {
                    "x": np.array([2, 3, 4]).astype('float32'),
                    "y": np.array([1, 5, 2]).astype('float32'),
                }

            x = fluid.data(name="x", shape=[3], dtype='float32')
            y = fluid.data(name="y", shape=[3], dtype='float32')
            z = paddle.add(x, y)

            place = fluid.XPUPlace(0)
            exe = fluid.Executor(place)
            z_value = exe.run(feed=gen_data(), fetch_list=[z.name])
            z_expected = np.array([3.0, 8.0, 6.0])
            self.assertEqual((z_value == z_expected).all(), True)

    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([2, 3, 4]).astype('float32')
            np_y = np.array([1, 5, 2]).astype('float32')
            x = fluid.dygraph.to_variable(np_x)
            y = fluid.dygraph.to_variable(np_y)
            z = paddle.add(x, y)
            np_z = z.numpy()
            z_expected = np.array([3.0, 8.0, 6.0])
            self.assertEqual((np_z == z_expected).all(), True)

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


text:
layout: post
title: http://hypno-paris.blogspot.fr
date: 2013-02-01 16:44:27.000000000 +01:00
categories:
- Articles
- Hypnose
tags: []
status: publish
type: post
published: true
meta:
  _edit_last: '2'
author:
  first_name: Nico
excerpt:
---

http://hypno-paris.blogspot.fr

L'article sur la distorsion de la perception du temps (DPT) est très intéressant.


text:
package org.easybatch.integration.xstream;

import com.thoughtworks.xstream.XStream;
import org.easybatch.core.api.Record;
import org.easybatch.core.api.RecordMapper;
import org.easybatch.xml.XmlRecord;

import static org.easybatch.core.util.Utils.checkNotNull;

/**
 * Mapper that uses XStream
 * to map XML records to domain objects.
 *
 * @param <T> Target domain object class.
 * @author Mahmoud Ben Hassine (mahmoud@benhassine.fr)
 */
public class XstreamRecordMapper<T> implements RecordMapper<T> {

    private XStream xStream;

    /**
     * Mapper that uses XStream
     * to map XML records to domain objects.
     *
     * @param xStream the {@link XStream} mapper.
     */
    public XstreamRecordMapper(final XStream xStream) {
        checkNotNull(xStream, "xStream");
        this.xStream = xStream;
    }

    @Override
    @SuppressWarnings(value = "unchecked")
    public T mapRecord(final Record record) {
        XmlRecord xmlRecord = (XmlRecord) record;
        return (T) xStream.fromXML(xmlRecord.getPayload());
    }

}


text:
layout: post
title: bash sebagai shell default di BSD
date: 2011-08-31 04:36:16.000000000 +07:00
type: post
published: true
status: publish
categories:
- uncategorized
tags:
- bash
- bsd
- ports
- shell
- unix
meta:
  _edit_last: '7761285'
  geo_latitude: '-8.588990'
  geo_longitude: '116.130400'
  geo_accuracy: '206'
  geo_address: mataram
  geo_public: '1'
  _wpas_skip_fb: '1'
author:
  login: pdft
  email: padfoot.tgz@gmail.com
  display_name: piko
  first_name: herpiko
  last_name: dwi aguno
---

cari port bash
 #echo /usr/ports/*/*bash*
 dari hasilnya kita pindah ke direktori port bash dan pasang
 #cd /usr/ports/shells/bash
 #make install clean
 cari dimana bash berada
 #whereis bash
 set bash sebagai shell default
 #chsh -s /usr/local/bin/bash namauser

silakan logout dan login kembali. :)


text:
require 'faker'

QUESTION = "This spirit animals has the following behavior: "

BEHAVIORS = [
  "the messenger of the spirit world",
  "it's medicine includes swiftness, strength, courage, wisdom, keen sight, illumination of Spirit, healing, creation, and knowledge of magic.",
  "it is generally associated with the symbolic meaning of transformation",
  "it is considered a peace maker",
  "it represents elevation from earthly matters, tuning into emotional or spiritual",
  "it is symbolic of cleansing and renewal",
  "it is a symbol of balance, grace, and seeing into the future",
  "it is a complex animal and has had many different meanings attached to it throughout history, including protection, playfulness, and cooperation",
  "its symbolism is characterized by the association with the Earth and earth symbols of groundedness and patience",
  "it symbolizes creation and destruction and is the keeper and protector of all knowledge",
  "it is commonly associated with emotion, inner truth, and creativity.",
  "it represents the yearning to join with one's source",
  "it represents sexual energy and the drive behind life",
  "this animal represents trust, patience, and knowing the right moment to make a move",
  "it often symbolizes the trickster or joker, but is also associated with a deep magic of life and creation.",
  "its primary meaning is strength and confidence",
  "it means you are often resourceful and have a way of manifesting all the things you need in the present and for the future",
  "it is considered the earth father in Mayan tradition, and holds authority over the sacred power of and in the earth, and the animals who live upon it.",
  "it generally symbolizes joy and playfulness, as well as adaptability."
]

SKY_ANIMALS = {
  hawk: {
    url:     "https://s-media-cache-ak0.pinimg.com/236x/a4/85/74/a48574dbc66ecdedc21f231b708837eb.jpg",
    answer: "the messenger of the spirit world",
    description: "When you have the hawk as a spirit animal, you may have an inclination towards using the power of vision and intuition in your daily life. The hawk totem provides wisdom about seeing situations from a higher perspective, using the power of observation, and focusing on the task at hand. It's a good companion to develop spiritual awareness.",
    deck_id: 1
  },

  eagle: {
    url:     "http://cdn2-b.examiner.com/sites/default/files/styles/image_content_width/hash/23/e5/Eagle%20(604x1087)%20(569x1024)%20(445x800).jpg?itok=lUvvo874",
    answer: "it's medicine includes swiftness, strength, courage, wisdom, keen sight, illumination of Spirit, healing, creation, and knowledge of magic.",
    description: "Eagle's medicine includes swiftness, strength, courage, wisdom, keen sight, illumination of Spirit, healing, creation, knowledge of magic, ability to see hidden spiritual truths, rising above the material to see the spiritual, ability to see the overall pattern/big picture, connection to spirit guides and teachers and higher truths, great power and balance, dignity with grace, intuitive and creative spirit, respect for the boundaries of the regions, grace achieved through knowledge and hard work.",
    deck_id: 1
  },

  dragonfly: {
    url:     "https://s-media-cache-ak0.pinimg.com/236x/04/10/bf/0410bf6ec9f5218dc5bf7749fa6c599f.jpg",
    answer:   "it is generally associated with the symbolic meaning of transformation",
    description: "The dragonfly totem carries the wisdom of transformation and adaptability in life. As spirit animal, the dragonfly is connected to the symbolism of change and light. When the dragonfly shows up in your life, it may remind you to bring a bit more lightness and joy into your life. Those who have this animal as totem may be inclined to delve deep into their emotions and shine their true colors.",
    deck_id: 1

  },
  blue_heron: {
    url:     "https://s-media-cache-ak0.pinimg.com/236x/5e/09/22/5e09223107273ed701b865d99d364a4f.jpg",
    answer:   "it is considered a peace maker",
    description: "Heron people do no seem to need a lot of people in their life, nor do they feel pressured to keep up with the Joneses, or be traditional in their life roles. The only time they gather in colonies is during the breeding season. They stand out in their uniqueness, and they know how to snatch and take advantage of things and events that the average person would not even bother with.",
    deck_id: 1

  },
  butterfly: {
    url:     "http://www.learntarot.com/mebtfy.gif",
    answer:   "it represents elevation from earthly matters, tuning into emotional or spiritual",
    description: "The butterfly is one of the most emblematic totem animals symbolizing personal transformation. If you see the butterfly as your totem or spirit animal, pay attention to the areas in your life or personality that are in need of profound change or transformation. Perhaps, this animal totem guides you to be sensitive to your personal cycles of expansion and growth, as well as the beauty of life's continuous unfolding. An important message carried by the spirit of the butterfly is about the ability to go through important changes with grace and lightness.",
    deck_id: 1

  },
  hummingbird: {
    url: "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTWyEItrSAxEY_4rPBcqJACoeez2EgMeBQPxjvEQ_lcngzvNuYD",
    answer: "it generally symbolizes joy and playfulness, as well as adaptability.",
    description: "The hummingbird spirit animal symbolizes the enjoyment of life and lightness of being. Those who have the hummingbird as a totem are invited to enjoy the sweetness of life, lift up negativity wherever it creeps in and express love more fully in their daily endeavors. This fascinating bird is capable of the most amazing feats despite its small size, such as traveling great distances or being able to fly backwards. By affinity with the hummingbird, those who have this bird as totem may be encouraged to develop their adaptability and resiliency while keeping a playful and optimistic outlook.",
    deck_id: 3

  }
}

WATER_ANIMALS = {
  frog: {
    url:     "http://www.mysticfamiliar.com/archive/divination_with_cards/images_tarot_angel_cards/16frog.JPG",
    answer: "it is symbolic of cleansing and renewal",
    description: "The frog as spirit animal or totem reminds us of the transient nature of our lives. As symbol of transition and transformation, this spirit animal supports us in times of change. Strongly associated with the water element, it connects us with the world of emotions and feminine energies, as well as the process of cleansing, whether it's physical, emotional, or more spiritual or energetic.",
    deck_id: 2

  },
  swan: {
    url:     "http://cdn2-b.examiner.com/sites/default/files/styles/image_content_width/hash/f2/62/Swan_0.jpg?itok=gtwb8HMy",
    answer: "it is a symbol of grace and beauty",
    description: "The swan is one of the most powerful and ancient totems.  Even the word swan is one of the oldest names in the English language, coming from the Anglo-Saxons.  Most of swan's associations come from its appearance—it is a graceful, white bird, and the largest of the waterfowl.  But swans are also powerful birds.  From this, they reflect the power and longevity that is possible when we awaken to the power and beauty within ourselves.  Swan is not only a widely known symbol, but also a very personal one to the individual.",
    deck_id: 2

  },
  dolphin: {
    url:     "http://www.tarotopia.com.au/sites/default/files/med%20cards294.jpg",
    answer: "it is a complex animal and has had many different meanings attached to it throughout history, including protection, playfulness, and cooperation",
    description: "The dolphin spirit animal represents harmony and balance. Dolphins are both highly intelligent and closely in tune with their instincts, striking a balance between the two states. Dolphins are also a symbol of protection and of resurrection. Their playful nature is a reminder that everyone needs to approach life with humor and joy. People who identify with the dolphin totem are usually peaceful and gentle, but with a deep inner strength.",
    deck_id: 2

  },
  turtle: {
    url:     "http://crowingcrone.files.wordpress.com/2011/06/turtle.jpg",
    answer: "its symbolism is characterized by the association with the Earth and earth symbols of groundedness and patience",
    description: "The turtle totem wisdom teaches us about walking our path in peace and sticking to it with determination and serenity. Slow moving on earth, yet also incredibly fast and agile in water, those who have the turtle as totem or spirit animal may be encouraged to take a break in their busy lives and look around or within themselves for more grounded, long-lasting solutions. Traditionally, the turtle is symbolic of the way of peace, whether it's inviting us to cultivate peace of mind or a peaceful relationship with our environment.",
    deck_id: 2

  },
  alligator: {
    url:     "https://s-media-cache-ak0.pinimg.com/236x/66/3b/b8/663bb883ad2eff6f6b967b93f7ba2762.jpg",
    answer: "it symbolizes creation and destruction and is the keeper and protector of all knowledge",
    description: "Alligator/Crocodile's medicine includes maternal protection, primal energies, connection to mother earth, protection from manipulation, understanding deceit, revenge through patience, initiation, understanding weather, access to ancient knowledge, power to survive.",
    deck_id: 2

  },
  whale: {
    url:     "http://cdn2-b.examiner.com/sites/default/files/styles/image_content_width/hash/d5/57/d55703d78baa00e36ca68cd0b0d30e19.jpg?itok=0uFIyQ9H",
    answer: "it is commonly associated with emotion, inner truth, and creativity.",
    description: "The whale spirit animal is the earth's record keeper for all time. As a totem, the whale teaches you about listening to your inner voice, understanding the impact your emotions have on your everyday life, and following your own truth. When the whale enters your life, it may be time to closely examine where you are, the actions and emotions that have brought you to this point, and what you can do to alleviate existing drama and unrest and find peace. Those who have the whale as their animal totem are in touch with true reality. They are nurturers and go-getters who understand there is more to this life than meets the eye.",
    deck_id: 2

  },
  salmon: {
    url:     "https://angelsandcelestials.files.wordpress.com/2014/04/49-salmon.jpg",
    answer: "it represents the yearning to join with one's source",
    description: "The salmon's wisdom includes – value of returning home to regenerate, swimming upstream through emotional waters to gain insight, understanding divination messages, rebirth of spiritual knowledge, wisdom.",
    deck_id: 2

  },

  otter: {
    url: "http://www.karmictools.com/Divinations/images/8-Otter.JPG",
    answer: "if it is your spirit animal, you likely find everything interesting and have a lot of curiosity",
    description: "If Otter is your animal totem you take great pleasure in the success and happiness of others and will work untiringly to help others achieve that. You have no selfishness, are not self centered, or self driven and could never be mean to others. You are never unnecessarily critical in a vengeful way nor are you a gossip. You find purpose in supporting and enhancing the lives of others.",
    deck_id: 3
  }
}
LAND_ANIMALS = {
  horse: {
    url:    "http://www.learntarot.com/mehrse.gif",
    answer: "it represents sexual energy and the drive behind life",
    description: "The horse spirit animal symbolizes personal drive, passion and appetite for freedom. Among all the spirit animals, it is one that shows a strong motivation that carries one through life. The meaning of the horse varies depending on whether this animal spirit guide is represented as wild, tamed, moving freely or constrained.",
    deck_id: 3
  },

  opossom: {
    url: "https://s-media-cache-ak0.pinimg.com/236x/8f/9b/fc/8f9bfce1b7f8e05ceff9046a85802bb8.jpg",
    answer: "this animal represents trust, patience, and knowing the right moment to make a move",
    description: "You are being asked to lay low and blend into the fabric of your surroundings. Things are not entirely what they appear to be at this time so simply say nothing and do nothing. Allow yourself the space and time to see things for what they really are. Alternatively Opossum is letting you know that the universe is working behind the scenes to fulfill your dreams. Be patient, allow things to develop, and trust that you will know the exact moment to make your move. Take a passive stance in all that is happening around you.",
    deck_id: 3

  },
  bear: {
    url: "http://cdn2-b.examiner.com/sites/default/files/styles/image_content_width/hash/57/a8/Bear_2.jpg?itok=WDeVtbGv",
    answer: "its primary meaning is strength and confidence",
    description: "In the kingdom of spirit animals, the bear is emblematic of grounding forces and strength. This animal has been worshiped throughout time as a powerful totem, inspiring those who need it the courage to stand up against adversity. As a spirit animal in touch with the earth and the cycles of nature, it is a powerful guide to support physical and emotional healing.",
    deck_id: 3

  },

  jaguar: {
    url: "http://cdn2-b.examiner.com/sites/default/files/styles/image_content_width/hash/b6/ec/b6ecf5066f39830e1350341d842239d7.jpg?itok=ZvQLPjIe",
    answer: "it is considered the earth father in Mayan tradition, and holds authority over the sacred power of and in the earth, and the animals who live upon it.",
    description: "The Jaguar's medicine includes seeing the roads within chaos and understanding the patterns of chaos, moving without fear in the darkness, moving in unknown places, shape shifting, psychic vision, facilitating soul work, empowering oneself, reclaiming power.",
    deck_id: 3

  },

  sqirrel: {
    url: "http://www.learntarot.com/mesqrl.gif",
    answer: "it means you are often resourceful and have a way of manifesting all the things you need in the present and for the future",
    description: "It is often a message for us to have more fun. Most likely we've been so busy taking life so seriously that we have forgotten that play is important too. On another note squirrel can also be signaling that we have to take a look at practical matters such as retirement, insurance, or even simple repairs. Are we adequately prepared? A visit from Squirrel could also indicate that you need lighten your load of things that are unnecessary. Things that you have gathered in the past and may be cluttering your life such as thoughts, worries, and stresses.",
    deck_id: 3

  },

  rabbit: {
    url: "https://s-media-cache-ak0.pinimg.com/236x/0c/70/a9/0c70a98c5ba29aa94713e6b73dae7fd9.jpg",
    answer: "it's medicine is also very positive, showing us how to attract love, abundance, health, and a warm, dry burrow.",
    description: "Rabbits are guides into the shadow world, where our personal fears lie. When the rabbit shows up it is time to examine those deep reflexive fears that hold you back from growing. Do you keep bounding for the safety of your old patterns every time something new or challenging presents itself? If the answer is yes, the rabbit asks you to face your fears with compassion for yourself. You must accept that it is part of human nature to feel fear at times, but also believe that our fears need not paralyze our growth and movement.",
    deck_id: 3

  },

  coyote: {
    url: "http://cdn2-b.examiner.com/sites/default/files/styles/image_content_width/hash/24/1a/241a501174dc8333c9ae6d98e8301ece.jpg?itok=T3P-TPW2",
    answer: "it often symbolizes the trickster or joker, but is also associated with a deep magic of life and creation.",
    description: "The coyote totem is strikingly paradoxical and is hard to categorize. It's a teacher of hidden wisdom with a sense of humor, so the messages of the coyote spirit animal may paradoxically appear in the form of a joke or trickery. Don't be tricked by the foolish appearances. The spirit of the coyote may remind you to not take things too seriously and bring more balance between wisdom and playfulness.",
    deck_id: 3

  }
}

DECKS = ["sky", "land", "water"]

DECKS.each do |deck|
  DefaultDeck.create(name: deck)
end

DefaultDeck.all.each do |deck|
  case deck.name
  when "sky"
    then SKY_ANIMALS.each do |animal, value|

      Card.create(name: animal.to_s,
                  answer: value[:answer],
                  image_url: value[:url],
                  description: value[:description],
                  deck_id: deck.id)
    end
  when "land"
    then LAND_ANIMALS.each do |animal, value|
      Card.create(name: animal.to_s, answer: value[:answer], image_url: value[:url], description: value[:description], deck_id: deck.id)
    end
  when "water"
    then WATER_ANIMALS.each do |animal, value|
      Card.create(name: animal.to_s, answer: value[:answer], image_url: value[:url], description: value[:description], deck_id: deck.id)
    end
  end
end

BEHAVIORS.each do |behavior|
  CardBehavior.create(name: behavior)
end


text:
module Spree
  module UserMethods
    extend ActiveSupport::Concern

    include Spree::UserApiAuthentication
    include Spree::UserPaymentSource
    include Spree::UserReporting
    include Spree::RansackableAttributes

    included do
      has_many :role_users, class_name: 'Spree::RoleUser', foreign_key: :user_id, dependent: :destroy
      has_many :spree_roles, through: :role_users, class_name: 'Spree::Role', source: :role

      has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser', foreign_key: :user_id, dependent: :destroy
      has_many :promotion_rules, through: :promotion_rule_users, class_name: 'Spree::PromotionRule'

      has_many :orders, foreign_key: :user_id, class_name: "Spree::Order"
      has_many :store_credits, foreign_key: :user_id, class_name: 'Spree::StoreCredit'

      belongs_to :ship_address, class_name: 'Spree::Address'
      belongs_to :bill_address, class_name: 'Spree::Address'

      self.whitelisted_ransackable_associations = %w[bill_address ship_address]
      self.whitelisted_ransackable_attributes = %w[id email]
    end

    # has_spree_role? simply needs to return true or false whether a user has a role or not.
    def has_spree_role?(role_in_question)
      spree_roles.where(name: role_in_question.to_s).any?
    end

    def last_incomplete_spree_order
      orders.incomplete.
        includes(line_items: [variant: [:images, :option_values, :product]]).
        order('created_at DESC').
        first
    end

    def analytics_id
      id
    end

    def total_available_store_credit
      store_credits.reload.to_a.sum(&:amount_remaining)
    end
  end
end


text:
module Placemaker

  class Reference
    include Placemaker::XmlHelper

    def woe_ids
      nested_node('woeIds')
    end

    def start
      nested_node('start')
    end

    def end
      nested_node('end')
    end

    def is_plain_text_marker
      nested_node('isPlainTextMarker')
    end

    def text
      nested_node('text')
    end

    def type
      nested_node('type')
    end

    def xpath
      nested_node('xpath')
    end
  end
end


text:
"""
    Server API

    Reference for Server API (REST/Json)

    OpenAPI spec version: 2.0.21

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import os
import sys
import unittest

import kinow_client
from kinow_client.rest import ApiException
from kinow_client.models.ip_coordinates import IPCoordinates

class TestIPCoordinates(unittest.TestCase):
    """ IPCoordinates unit test stubs """

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testIPCoordinates(self):
        """
        Test IPCoordinates
        """
        model = kinow_client.models.ip_coordinates.IPCoordinates()

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


text:
<application>
  <component name="FileTypeManager" version="17">
    <ignoreFiles list="*.hprof;*.orig;*.pyc;*.pyo;*.rbc;*.yarb;*~;.DS_Store;.git;.hg;.svn;CVS;RCS;SCCS;__pycache__;_svn;rcs;vssver.scc;vssver2.scc;" />
    <extensionMap>
      <mapping ext="volt" type="Twig" />
    </extensionMap>
  </component>
</application>


text:
namespace WebAPI.Common.Models.Raven.Keys
{
    public class MultipleGeocodeUsage : GeocodeStreetZoneUsage
    {
        public MultipleGeocodeUsage(string apiKeyId, string accountId, long lastUsedTicks, string inputAddress,
                                    double score, string page)
            : base(apiKeyId, accountId, lastUsedTicks, inputAddress, score)
        {
            Page = page;
        }

        public string Page { get; set; }
    }
}


text:
id: home
layout: default
sectionid: home
---

## Project Status

ContainerJS is currently under active development, with frequent breaking changes!

## Getting Started

The following describes how to create a simple 'Hello World' application and run it with Electron, OpenFin and a Browser.

#### Creating the Hello World app

From within an empty folder, add a minimal HTML file called `index.html`:

```html
<!doctype html>
<meta charset="utf-8">
<body>
  <h1>Hello World!</h1>
  <div>
    ContainerJS status: <span id="status">initialising</span>
  </div>

  <script src="https://unpkg.com/containerjs-api-browser@0.0.3/build/dist/containerjs-api.js"></script>

  <script>
    ssf.app.ready()
      .then(() => {
        const status = document.getElementById('status')
        status.innerText = 'ready';
      });
  </script>
</body>
```

The above displays a simple welcome message and indicates the status of the ContainerJS APIs. The `containerjs-api.js` is the browser API, that will create the ContainerJS API if no API currently exists.

This file uses the `ssf` API to handle the container `ready` promise, updating the status text when this lifecycle event occurs.

Within the same folder, add the following `app.json` manifest file:

```json
{
  "name": "Hello World",
  "url": "http://localhost:8080/index.html",
  "uuid": "hello-world",
  "autoShow": true
}
```

The manifest tells the container which URL to load initially.

#### Starting a local server

The container loads HTML applications over HTTP, so in order to run this demo application you need to start a local server. If you don't already have a preferred tool, you can use the node `http-server` package:

```
$ npm install --global http-server
$ http-server -p 8080
```

This starts a server on port 8080.

#### Running with OpenFin

The ContainerJS project provides an OpenFin-based command line tool, which can be installed as follows:

```
$ npm install --global containerjs-api-openfin
```

To run your simple 'Hello World' application from within an OpenFin container, execute the following:

```
$ ssf-openfin --config app.json
```

You should now see the Hello World application, and see the status update to 'ready'. _Note:_ The notification API
will not work unless a `notification.html` is hosted on a server. An example notifaction file can be generated by passing
`--notification [outdir]` to `ssf-openfin`.

#### Running with Electron

The ContainerJS project provides an Electron-based command line tool, which can be installed as follows:

```
$ npm install --global containerjs-api-electron
```

From within your 'Hello World' folder, execute the following:

```
$ ssf-electron app.json
```

You should now see exactly the same app running within Electron.

#### Browser

To run your app within a browser, simply navigate to the URL `http://localhost:8080/index.html`.