text:
namespace Apache.Ignite.Core.Cache.Expiry
{
    using System;

    /// <summary>
    /// Default expiry policy implementation with all durations defined explicitly.
    /// </summary>
    public class ExpiryPolicy : IExpiryPolicy
    {
        /** Expiry for create. */
        private readonly TimeSpan? _create;

        /** Expiry for update. */
        private readonly TimeSpan? _update;

        /** Expiry for access. */
        private readonly TimeSpan? _access;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="create">Expiry for create.</param>
        /// <param name="update">Expiry for udpate.</param>
        /// <param name="access">Expiry for access.</param>
        public ExpiryPolicy(TimeSpan? create, TimeSpan? update, TimeSpan? access)
        {
            _create = create;
            _update = update;
            _access = access;
        }

        /// <summary>
        /// Gets expiry for create operation.
        /// <para />
        /// If <c>TimeSpan.ZERO</c> is returned, cache entry is considered immediately expired
        /// and will not be added to cache.
        /// <para />
        /// If <c>null</c> is returned, no change to previously understood expiry is performed.
        /// </summary>
        /// <returns>Expiry for create opeartion.</returns>
        public TimeSpan? GetExpiryForCreate()
        {
            return _create;
        }

        /// <summary>
        /// Gets expiry for update operation.
        /// <para />
        /// If <c>TimeSpan.ZERO</c> is returned, cache entry is considered immediately expired.
        /// <para />
        /// If <c>null</c> is returned, no change to previously understood expiry is performed.
        /// </summary>
        /// <returns>Expiry for update operation.</returns>
        public TimeSpan? GetExpiryForUpdate()
        {
            return _update;
        }

        /// <summary>
        /// Gets expiry for access operation.
        /// <para />
        /// If <c>TimeSpan.ZERO</c> is returned, cache entry is considered immediately expired.
        /// <para />
        /// If <c>null</c> is returned, no change to previously understood expiry is performed.
        /// </summary>
        /// <returns>Expiry for access operation.</returns>
        public TimeSpan? GetExpiryForAccess()
        {
            return _access;
        }
    }
}


text:
package org.apache.dubbo.rpc.protocol.dubbo.decode;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler;
import org.apache.dubbo.remoting.transport.DecodeHandler;
import org.apache.dubbo.remoting.transport.MultiMessageHandler;
import org.apache.dubbo.remoting.transport.netty4.NettyBackedChannelBuffer;
import org.apache.dubbo.remoting.transport.netty4.NettyCodecAdapter;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.protocol.dubbo.DecodeableRpcInvocation;
import org.apache.dubbo.rpc.protocol.dubbo.DubboCodec;
import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * These junit tests aim to test unpack and stick pack of dubbo and telnet
 */
public class DubboTelnetDecodeTest {
    private static AtomicInteger dubbo = new AtomicInteger(0);

    private static AtomicInteger telnet = new AtomicInteger(0);

    private static AtomicInteger telnetDubbo = new AtomicInteger(0);

    private static AtomicInteger dubboDubbo = new AtomicInteger(0);

    private static AtomicInteger dubboTelnet = new AtomicInteger(0);

    private static AtomicInteger telnetTelnet = new AtomicInteger(0);

    /**
     * just dubbo request
     *
     * @throws InterruptedException
     */
    @Test
    public void testDubboDecode() throws InterruptedException, IOException {
        ByteBuf dubboByteBuf = createDubboByteBuf();

        EmbeddedChannel ch = null;
        try {
            Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo");
            URL url = new URL("dubbo", "localhost", 22226);
            NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler());

            MockHandler mockHandler = new MockHandler(null,
                    new MultiMessageHandler(
                            new DecodeHandler(
                                    new HeaderExchangeHandler(new ExchangeHandlerAdapter() {
                                        @Override
                                        public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) {
                                            if (checkDubboDecoded(msg)) {
                                                dubbo.incrementAndGet();
                                            }
                                            return getDefaultFuture();
                                        }
                                    }))));

            ch = new LocalEmbeddedChannel();
            ch.pipeline()
                    .addLast("decoder", adapter.getDecoder())
                    .addLast("handler", mockHandler);

            ch.writeInbound(dubboByteBuf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ch != null) {
                ch.close().await(200, TimeUnit.MILLISECONDS);
            }
        }

        TimeUnit.MILLISECONDS.sleep(100);

        Assertions.assertEquals(1, dubbo.get());
    }

    /**
     * just telnet request
     *
     * @throws InterruptedException
     */
    @Test
    public void testTelnetDecode() throws InterruptedException {
        ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("test\r\n".getBytes());

        EmbeddedChannel ch = null;
        try {
            Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo");
            URL url = new URL("dubbo", "localhost", 22226);
            NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler());

            MockHandler mockHandler = new MockHandler((msg) -> {
                if (checkTelnetDecoded(msg)) {
                    telnet.incrementAndGet();
                }
            },
                    new MultiMessageHandler(
                            new DecodeHandler(
                                    new HeaderExchangeHandler(new ExchangeHandlerAdapter() {
                                        @Override
                                        public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) {
                                            return getDefaultFuture();
                                        }
                                    }))));

            ch = new LocalEmbeddedChannel();
            ch.pipeline()
                    .addLast("decoder", adapter.getDecoder())
                    .addLast("handler", mockHandler);

            ch.writeInbound(telnetByteBuf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ch != null) {
                ch.close().await(200, TimeUnit.MILLISECONDS);
            }
        }

        TimeUnit.MILLISECONDS.sleep(100);

        Assertions.assertEquals(1, telnet.get());
    }

    /**
     * telnet and dubbo request
     *
     *

     * First ByteBuf:
     * +--------------------------------------------------+
     * |               telnet(incomplete)                 |
     * +--------------------------------------------------+
     *

     *
     * Second ByteBuf:
     * +--------------------------++----------------------+
     * |  telnet(the remaining)   ||   dubbo(complete)    |
     * +--------------------------++----------------------+
     *                            ||
     *                        Magic Code
     *
     * @throws InterruptedException
     */
    @Test
    public void testTelnetDubboDecoded() throws InterruptedException, IOException {
        ByteBuf dubboByteBuf = createDubboByteBuf();

        ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("test\r".getBytes());
        EmbeddedChannel ch = null;
        try {
            Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo");
            URL url = new URL("dubbo", "localhost", 22226);
            NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler());

            MockHandler mockHandler = new MockHandler((msg) -> {
                if (checkTelnetDecoded(msg)) {
                    telnetDubbo.incrementAndGet();
                }
            },
                    new MultiMessageHandler(
                            new DecodeHandler(
                                    new HeaderExchangeHandler(new ExchangeHandlerAdapter() {
                                        @Override
                                        public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) {
                                            if (checkDubboDecoded(msg)) {
                                                telnetDubbo.incrementAndGet();
                                            }

                                            return getDefaultFuture();
                                        }
                                    }))));

            ch = new LocalEmbeddedChannel();
            ch.pipeline()
                    .addLast("decoder", adapter.getDecoder())
                    .addLast("handler", mockHandler);

            ch.writeInbound(telnetByteBuf);
            ch.writeInbound(Unpooled.wrappedBuffer(Unpooled.wrappedBuffer("\n".getBytes()), dubboByteBuf));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ch != null) {
                ch.close().await(200, TimeUnit.MILLISECONDS);
            }
        }

        TimeUnit.MILLISECONDS.sleep(100);

        Assertions.assertEquals(2, telnetDubbo.get());
    }

    /**
     * NOTE: This test case actually will fail, but the probability of this case is very small,
     * and users should use telnet in new QOS port(default port is 22222) since dubbo 2.5.8,
     * so we could ignore this problem.
     *
     *

     * telnet and telnet request
     *
     *

     * First ByteBuf (firstByteBuf):
     * +--------------------------------------------------+
     * |               telnet(incomplete)                 |
     * +--------------------------------------------------+
     *

     *
     * Second ByteBuf (secondByteBuf):
     * +--------------------------------------------------+
     * |  telnet(the remaining)   |   telnet(complete)    |
     * +--------------------------------------------------+
     *
     * @throws InterruptedException
     */
    // @Test
    public void testTelnetTelnetDecoded() throws InterruptedException {
        ByteBuf firstByteBuf = Unpooled.wrappedBuffer("ls\r".getBytes());
        ByteBuf secondByteBuf = Unpooled.wrappedBuffer("\nls\r\n".getBytes());

        EmbeddedChannel ch = null;
        try {
            Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo");
            URL url = new URL("dubbo", "localhost", 22226);
            NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler());

            MockHandler mockHandler = new MockHandler((msg) -> {
                if (checkTelnetDecoded(msg)) {
                    telnetTelnet.incrementAndGet();
                }
            },
                    new MultiMessageHandler(
                            new DecodeHandler(
                                    new HeaderExchangeHandler(new ExchangeHandlerAdapter() {
                                        @Override
                                        public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) {
                                            return getDefaultFuture();
                                        }
                                    }))));

            ch = new LocalEmbeddedChannel();
            ch.pipeline()
                    .addLast("decoder", adapter.getDecoder())
                    .addLast("handler", mockHandler);

            ch.writeInbound(firstByteBuf);
            ch.writeInbound(secondByteBuf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ch != null) {
                ch.close().await(200, TimeUnit.MILLISECONDS);
            }
        }

        TimeUnit.MILLISECONDS.sleep(100);

        Assertions.assertEquals(2, telnetTelnet.get());
    }

    /**
     * dubbo and dubbo request
     *
     *

     * First ByteBuf (firstDubboByteBuf):
     * ++-------------------------------------------------+
     * ||               dubbo(incomplete)                 |
     * ++-------------------------------------------------+
     * ||
     * Magic Code
     *

     *
     *

     * Second ByteBuf (secondDubboByteBuf):
     * +-------------------------++-----------------------+
     * |  dubbo(the remaining)   ||    dubbo(complete)    |
     * +-------------------------++-----------------------+
     *                           ||
     *                       Magic Code
     *
     * @throws InterruptedException
     */
    @Test
    public void testDubboDubboDecoded() throws InterruptedException, IOException {
        ByteBuf dubboByteBuf = createDubboByteBuf();

        ByteBuf firstDubboByteBuf = dubboByteBuf.copy(0, 50);
        ByteBuf secondLeftDubboByteBuf = dubboByteBuf.copy(50, dubboByteBuf.readableBytes() - 50);
        ByteBuf secondDubboByteBuf = Unpooled.wrappedBuffer(secondLeftDubboByteBuf, dubboByteBuf);

        EmbeddedChannel ch = null;
        try {
            Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo");
            URL url = new URL("dubbo", "localhost", 22226);
            NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler());

            MockHandler mockHandler = new MockHandler(null,
                    new MultiMessageHandler(
                            new DecodeHandler(
                                    new HeaderExchangeHandler(new ExchangeHandlerAdapter() {
                                        @Override
                                        public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) {
                                            if (checkDubboDecoded(msg)) {
                                                dubboDubbo.incrementAndGet();
                                            }
                                            return getDefaultFuture();
                                        }
                                    }))));

            ch = new LocalEmbeddedChannel();
            ch.pipeline()
                    .addLast("decoder", adapter.getDecoder())
                    .addLast("handler", mockHandler);

            ch.writeInbound(firstDubboByteBuf);
            ch.writeInbound(secondDubboByteBuf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ch != null) {
                ch.close().await(200, TimeUnit.MILLISECONDS);
            }
        }

        TimeUnit.MILLISECONDS.sleep(100);

        Assertions.assertEquals(2, dubboDubbo.get());
    }

    /**
     * dubbo and telnet request
     *
     *

     * First ByteBuf:
     * ++-------------------------------------------------+
     * ||               dubbo(incomplete)                 |
     * ++-------------------------------------------------+
     * ||
     * Magic Code
     *
     *

     * Second ByteBuf:
     * +--------------------------------------------------+
     * |  dubbo(the remaining)  |     telnet(complete)    |
     * +--------------------------------------------------+
     *
     * @throws InterruptedException
     */
    @Test
    public void testDubboTelnetDecoded() throws InterruptedException, IOException {
        ByteBuf dubboByteBuf = createDubboByteBuf();
        ByteBuf firstDubboByteBuf = dubboByteBuf.copy(0, 50);
        ByteBuf secondLeftDubboByteBuf = dubboByteBuf.copy(50, dubboByteBuf.readableBytes());

        ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("\r\n".getBytes());
        ByteBuf secondByteBuf = Unpooled.wrappedBuffer(secondLeftDubboByteBuf, telnetByteBuf);

        EmbeddedChannel ch = null;
        try {
            Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo");
            URL url = new URL("dubbo", "localhost", 22226);
            NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler());

            MockHandler mockHandler = new MockHandler((msg) -> {
                if (checkTelnetDecoded(msg)) {
                    dubboTelnet.incrementAndGet();
                }
            },
                    new MultiMessageHandler(
                            new DecodeHandler(
                                    new HeaderExchangeHandler(new ExchangeHandlerAdapter() {
                                        @Override
                                        public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) {
                                            if (checkDubboDecoded(msg)) {
                                                dubboTelnet.incrementAndGet();
                                            }
                                            return getDefaultFuture();
                                        }
                                    }))));

            ch = new LocalEmbeddedChannel();
            ch.pipeline()
                    .addLast("decoder", adapter.getDecoder())
                    .addLast("handler", mockHandler);

            ch.writeInbound(firstDubboByteBuf);
            ch.writeInbound(secondByteBuf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ch != null) {
                ch.close().await(200, TimeUnit.MILLISECONDS);
            }
        }

        TimeUnit.MILLISECONDS.sleep(100);

        Assertions.assertEquals(2, dubboTelnet.get());
    }

    private ByteBuf createDubboByteBuf() throws IOException {
        Request request = new Request();
        RpcInvocation rpcInvocation = new RpcInvocation();
        rpcInvocation.setMethodName("sayHello");
        rpcInvocation.setParameterTypes(new Class[]{String.class});
        rpcInvocation.setParameterTypesDesc(ReflectUtils.getDesc(new Class[]{String.class}));
        rpcInvocation.setArguments(new String[]{"dubbo"});
        rpcInvocation.setAttachment("path", DemoService.class.getName());
        rpcInvocation.setAttachment("interface", DemoService.class.getName());
        rpcInvocation.setAttachment("version", "0.0.0");

        request.setData(rpcInvocation);
        request.setVersion("2.0.2");

        ByteBuf dubboByteBuf = Unpooled.buffer();
        ChannelBuffer buffer = new NettyBackedChannelBuffer(dubboByteBuf);
        DubboCodec dubboCodec = new DubboCodec();
        dubboCodec.encode(new MockChannel(), buffer, request);

        return dubboByteBuf;
    }

    private static boolean checkTelnetDecoded(Object msg) {
        if (msg instanceof String && !msg.toString().contains("Unsupported command:")) {
            return true;
        }
        return false;
    }

    private static boolean checkDubboDecoded(Object msg) {
        if (msg instanceof DecodeableRpcInvocation) {
            DecodeableRpcInvocation invocation = (DecodeableRpcInvocation) msg;
            if ("sayHello".equals(invocation.getMethodName())
                    && invocation.getParameterTypes().length == 1
                    && String.class.equals(invocation.getParameterTypes()[0])
                    && invocation.getArguments().length == 1
                    && "dubbo".equals(invocation.getArguments()[0])
                    && DemoService.class.getName().equals(invocation.getAttachment("path"))
                    && DemoService.class.getName().equals(invocation.getAttachment("interface"))
                    && "0.0.0".equals(invocation.getAttachment("version"))) {
                return true;
            }
        }
        return false;
    }

    private static CompletableFuture<Object> getDefaultFuture() {
        CompletableFuture<Object> future = new CompletableFuture<>();
        AppResponse result = new AppResponse();
        result.setValue("default result");
        future.complete(result);
        return future;
    }
}

redpajama_set_name: RedPajamaGithub


text:
from functools import partial

def load_counter(load_type, source, domain_name, extra_tags=None):
    """Make a function to track load by counting touched items

    :param load_type: Load type (`"case"`, `"form"`, `"sms"`). Use one
    of the convenience functions below (e.g., `case_load_counter`)
    rather than passing a string literal.
    :param source: Load source string. Example: `"form_submission"`.
    :param domain_name: Domain name string.
    :param extra_tags: Optional dict of extra metric tags.
    :returns: Function that adds load when called: `add_load(value=1)`.
    """
    from corehq.util.metrics import metrics_counter
    tags = extra_tags or {}
    tags['src'] = source
    tags['domain'] = domain_name
    metric = "commcare.load.%s" % load_type

    def track_load(value=1):
        metrics_counter(metric, value, tags=tags)

    return track_load

def case_load_counter(*args, **kw):
    # grep: commcare.load.case
    return load_counter("case", *args, **kw)

def form_load_counter(*args, **kw):
    # grep: commcare.load.form
    return load_counter("form", *args, **kw)

def ledger_load_counter(*args, **kw):
    """Make a ledger transaction load counter function

    Each item counted is a ledger transaction (not a ledger value).
    """
    # grep: commcare.load.ledger
    return load_counter("ledger", *args, **kw)

def sms_load_counter(*args, **kw):
    """Make a messaging load counter function

    This is used to count all kinds of messaging load, including email
    (not strictly SMS).
    """
    # grep: commcare.load.sms
    return load_counter("sms", *args, **kw)

def ucr_load_counter(engine_id, *args, **kw):
    """Make a UCR load counter function

    This is used to count all kinds of UCR load
    """
    # grep: commcare.load.ucr
    return load_counter("ucr.{}".format(engine_id), *args, **kw)

def schedule_load_counter(*args, **kw):
    """Make a schedule load counter function

    This is used to count load from ScheduleInstances
    """
    # grep: commcare.load.schedule
    return load_counter("schedule", *args, **kw)

def load_counter_for_model(model):
    from corehq.form_processor.models import CommCareCase, XFormInstance
    from corehq.messaging.scheduling.scheduling_partitioned.models import (
        AlertScheduleInstance, TimedScheduleInstance, CaseTimedScheduleInstance, CaseAlertScheduleInstance
    )
    return {
        CommCareCase: case_load_counter,
        XFormInstance: form_load_counter,
        AlertScheduleInstance: schedule_load_counter,
        TimedScheduleInstance: schedule_load_counter,
        CaseTimedScheduleInstance: schedule_load_counter,
        CaseAlertScheduleInstance: schedule_load_counter,
    }.get(model, partial(load_counter, 'unknown'))  # grep: commcare.load.unknown


text:
module Parser
       ()where

import Text.XML.HXT.Core
import Data.String.UTF8
import Control.Monad

odd :: (->) Int Bool
odd a = True

css tag = multi (hasName tag)

testDoc = do
  html <- readFile "test.html"
  let doc = readString [withParseHTML yes, withWarnings no] html
  texts <- runX $ doc //> getText
  mapM_ putStrLn texts

main = do
  html <- readFile "test.html"
  let doc = readString [withParseHTML yes, withWarnings no] html
  links <- runX $ doc //> hasName "a" >>> getAttrValue "href"
  mapM_ putStrLn links


text:
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.firestore.conformance.model;

import androidx.annotation.NonNull;
import com.google.auto.value.AutoValue;
import com.google.firestore.v1.Document;
import java.util.Collections;
import java.util.List;

/** Result from query execution. */
@AutoValue
public abstract class Result {

  /** A list of documents to expect from the query. */
  public abstract List<Document> getDocuments();

  /** Builder for {@link Result}. */
  @AutoValue.Builder
  public abstract static class Builder {
    @NonNull
    public static Result.Builder builder() {
      return new AutoValue_Result.Builder().setDocuments(Collections.emptyList());
    }

    @NonNull
    public abstract Result.Builder setDocuments(@NonNull List<Document> documents);

    @NonNull
    public abstract Result build();
  }
}


text:
package org.switchyard.quickstarts.camel.jpa.binding;

import java.util.Calendar;
import java.util.Random;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.switchyard.component.bean.Reference;
import org.switchyard.component.bean.Service;
import org.switchyard.quickstarts.camel.jpa.binding.domain.Greet;

/**
 * Implementation of scheduler service.
 */
@Service(PeriodicService.class)
public class PeriodicServiceImpl implements PeriodicService {

    // some values to populate entity
    private final static String[] NAMES = {
        "Keith", "David", "Brian", "Rob",
        "Tomo", "Lukasz", "Magesh", "Tom"
    };

    private Logger _logger = Logger.getLogger(PeriodicServiceImpl.class);

    @Inject
    @Reference("StoreReference")
    private StoreService _store;

    @Override
    public void execute() {
        Greet greet = createRandomGreet();
        _logger.info("Sending " + greet + " to JPA store");
        _store.storeGreeting(greet);
    }

    private Greet createRandomGreet() {
        Random random = new Random(System.currentTimeMillis());

        Greet event = new Greet();
        event.setReceiver(NAMES[random.nextInt(NAMES.length)]);
        event.setSender(NAMES[random.nextInt(NAMES.length)]);
        event.setCreatedAt(Calendar.getInstance());
        return event;
    }

}


text:
<?php

declare(strict_types=1);

namespace Zetta\DoctrineUtil\DBAL;

use Doctrine\Common\EventManager;
use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Driver;
use Exception;

class Connection extends \Doctrine\DBAL\Connection
{
    /**
     * @var int
     */
    protected $reconnectAttempts = 0;

    /**
     * @inheritdoc
     */
    public function __construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null)
    {
        if (isset($params['driverOptions']['x_reconnect_attempts']) && method_exists($driver, 'getReconnectExceptions')) {
            // sanity check: 0 if no exceptions are available
            $reconnectExceptions = $driver->getReconnectExceptions();
            $this->reconnectAttempts = empty($reconnectExceptions) ? 0 : (int)$params['driverOptions']['x_reconnect_attempts'];
        }
        parent::__construct($params, $driver, $config, $eventManager);
    }

    /**
     * @inheritdoc
     */
    public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null)
    {
        return $this->executeWrapped('executeQuery', $query, $params, $types, $qcp);
    }

    /**
     * @inheritdoc
     */
    public function query()
    {
        return $this->executeWrapped('query');
    }

    /**
     * @inheritdoc
     */
    public function executeUpdate($query, array $params = [], array $types = [])
    {
        return $this->executeWrapped('executeUpdate', $query, $params, $types);
    }

    /**
     * @inheritdoc
     */
    public function beginTransaction()
    {
        $this->executeWrapped('beginTransaction');
    }

    /**
     * @param Exception $e
     * @param $attempt
     * @return bool
     */
    public function validateReconnectAttempt(Exception $e, $attempt)
    {
        if ($this->getTransactionNestingLevel() <= 1 && $this->reconnectAttempts && $attempt < $this->reconnectAttempts) {
            $reconnectExceptions = $this->_driver->getReconnectExceptions();
            $message = $e->getMessage();
            if (! empty($reconnectExceptions)) {
                foreach ($reconnectExceptions as $reconnectException) {
                    if (strpos($message, $reconnectException) !== false) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * @param $method
     * @param null $query
     * @param array $params
     * @param array $types
     * @param QueryCacheProfile|null $qcp
     * @return mixed
     * @throws Exception
     */
    private function executeWrapped($method, $query = null, array $params = [], $types = [], QueryCacheProfile $qcp = null)
    {
        $stmt = null;
        $attempt = 0;
        $retry = true;
        while ($retry) {
            $retry = false;
            try {
                if ($query !== null && $qcp !== null) {
                    $stmt = parent::$method($query, $params, $types, $qcp);
                } elseif ($query !== null && $qcp === null) {
                    $stmt = parent::$method($query, $params, $types);
                } else {
                    $stmt = parent::$method();
                }
            } catch (Exception $e) {
                error_log('DBAL EXCEPTION THROWN [' . $this->getTransactionNestingLevel() . ']:' . $e->getMessage());
                if ($this->validateReconnectAttempt($e, $attempt)) {
                    error_log('    OK - successfully validated');
                    $this->close();
                    $attempt++;

                    if ($this->_driver->shouldStall($e)) {
                        error_log('    waitstate deemed beneficial, sleeping 5 seconds...');
                        sleep(5);
                    }

                    $retry = true;
                } else {
                    error_log('    FAIL - could not be validated');
                    throw $e;
                }
            }
        }

        return $stmt;
    }
}


text:
package hu.pazsitz.pacuse.tests.cucumber.featuretables.fieldactions.delegates.populator;

import hu.pazsitz.pacuse.tests.cucumber.featuretables.AnnotatedWebElement;

import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

@Test(groups = "unit")
public class ButtonPopulatorActionTests {
	private ButtonPopulatorAction populator = new ButtonPopulatorAction();
	private AnnotatedWebElement element;

	@BeforeMethod
	public void init() {
		element = Mockito.mock(AnnotatedWebElement.class, Mockito.RETURNS_SMART_NULLS);
	}

	@Test
	public void testButtonPopulatorAction() throws Exception {
		populator.doAction(element, "true");
		Mockito.verify(element, Mockito.times(1)).click();
	}

	@Test
	public void testButtonPopulatorActionOnEmpty() throws Exception {
		populator.doAction(element, "");
		Mockito.verify(element, Mockito.times(1)).click();
	}

	@Test
	public void testButtonPopulatorActionOnFalse() throws Exception {
		populator.doAction(element, "false");
		Mockito.verify(element, Mockito.times(1)).click();
	}

}


text:
class NomenclatureChange::StatusToAccepted < NomenclatureChange
  include NomenclatureChange::StatusChangeHelpers
  attr_accessible :created_by_id, :updated_by_id
  build_steps(
    :primary_output, :summary
  )
  validates :status, inclusion: {
    in: self.status_dict,
    message: "%{value} is not a valid status"
  }
  validate :required_primary_output_name_status, if: :primary_output_or_submitting?
  before_validation :set_output_name_status, if: :primary_output_or_submitting?
  before_validation :set_output_rank_id, if: :primary_output_or_submitting?
  before_validation :set_output_parent_id, if: :primary_output_or_submitting?

  def required_primary_output_name_status
    if primary_output && !['N', 'T'].include?(primary_output.name_status)
      errors.add(:primary_output, "Must be N or T taxon")
      return false
    end
    true
  end

  def set_output_name_status
    primary_output && primary_output.new_name_status = 'A'
  end

  def set_output_rank_id
    return true if primary_output && primary_output.new_rank_id.present?
    primary_output && primary_output.taxon_concept &&
      primary_output.new_rank_id = primary_output.taxon_concept.rank_id
  end

  def set_output_parent_id
    return true unless needs_to_set_parent? && primary_output.new_parent_id.nil?
    primary_output && primary_output.taxon_concept &&
      primary_output.new_parent_id = primary_output.default_parent.try(:id)
  end

  def new_output_rank
    primary_output && primary_output.taxon_concept.try(:rank)
  end

  def needs_to_receive_associations?
    false
  end

  def needs_to_relay_associations?
    false
  end

  def needs_to_set_parent?
    primary_output.try(:name_status) == 'T'
  end

end


text:
from django.db import models
from django.contrib.auth.models import User

from taggit.managers import TaggableManager

from projects.models import Project

class Build(models.Model):
    project = models.ForeignKey(Project, related_name='builds')
    date = models.DateTimeField(auto_now_add=True)
    success = models.BooleanField()
    output = models.TextField()
    error = models.TextField()

    class Meta:
        ordering = ['-date']

    def __unicode__(self):
        return u"Build %s for %s (%s)" % (self.project, self.project.user, self.pk)

    @models.permalink
    def get_absolute_url(self):
        return ('builds_detail', [self.project.user.username, self.project.slug, self.pk])


text:
package main

import (
	"os"

	"github.com/kyma-project/test-infra/development/image-url-helper/cmd"
)

func main() {
	if err := cmd.Execute(); err != nil {
		os.Exit(1)
	}
}


text:
<?php

/**
 * Ws_userModel
 * Store user records for role based access control module.
 *
 * @see WsAuth
 * @see Ws_rolesModel
 * @see Ws_permissionsModel
 * @see Ws_role_permModel
 * @see Ws_user_roleModel
 *
 */
class Ws_userModel extends WsModel
{
    public function __construct()
    {
        parent::__construct();

        // mysql/maridb don't detect boolean type properly
        $this->columnType['is_verified'] = 'bool_type';
        $this->columnType['is_active'] = 'bool_type';

        // don't show user salt and verification code in admin or
        // edit forms
        $this->columnType['user_salt'] = 'hidden_type';
        $this->columnType['verification_code'] = 'hidden_type';
        $this->hiddenColumns = array(
            'user_salt',
            'verification_code',
        );

        // set metaName for displaying in grid and form
        $this->metaName = WsLocalize::msg('User Accounts');

        // column headers for grid and form
        $this->columnHeaders = array(
            'id' => WsLocalize::msg('user id'),
            'email' => WsLocalize::msg('mail address'),
            'password' => WsLocalize::msg('password'),
            'is_verified' => WsLocalize::msg('verified account?'),
            'is_active' => WsLocalize::msg('active account?'),
        );
    }

    /**
     * Returns random string of specific length.
     *
     * @param integer $length Length of string.
     * @return string $string Random sting
     *
     */
    public function randomString($length = 50)
    {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
        $string = '';

        for ($p = 0; $p < $length; $p++) {
            $string .= $chars[mt_rand(0, strlen($chars)-1)];
        }

        return $string;
    }

    /**
     * Encript data with sha512 algorithm
     *
     * @param string $data Data to encript
     * @return string $data Encripted data
     *
     */
    public function hashData($data)
    {
        return hash_hmac('sha512', $data, $this->user_salt);
    }

    /**
     * this function is called before every save() to ensure that password is
     * encripted
     *
     * @return boolean
     *
     */
    public function beforeSave()
    {
        // admin account is always verified and active
        if ($this->email == WsConfig::get('auth_mail')) {
            if (WsConfig::get('db_driver') == 'pgsql') {
                $user_model->is_verified = 't';
                $user_model->is_active = 't';
            } else {
                $user_model->is_verified = 1;
                $user_model->is_active = 1;
            }
        }

        /* prepare password and verification code
         * generate user salt
         */
        $this->user_salt = $this->randomString();;
        // salt and hash the password
        $password = $this->user_salt.$this->password;
        $password = $this->hashData($password);

        $this->password = $password;

        return true;
    }

    /*
     * this function is called before every delete() to ensure that nobody can
     * delete administrator's account
     *
     * @return boolean
     *
     */
    public function beforeDelete()
    {

        // prevent removal of admin user account
        if ($this->email == WsConfig::get('auth_mail')) {
            return false;
        }

        return true;
    }
}


text:
require 'capybara/rspec'
require 'spec_helper.rb'

feature "Looking up tickets", js: true do
  scenario "finding tickets" do
    visit 'http://localhost:3000'
    fill_in "keywords", with: "2"
    click_on "Search"

    expect(page).to have_content("A Desc 2")
    expect(page).not_to have_content("A Desc 1")
  end
end


text:
$(document).ready(function(){
    $('[id^="accordion"]').accordion({
        collapsible: true,
        active: false,
        autoHeight: false,
        navigation: true
    });
    $( "#tool_forms_button" ).click( function() {
        $( "#tool_forms" ).toggle( "fast" );
    });

    $("#strings_button").click(function() {
        $.ajax({
            type: "GET",
            url: get_strings,
            dataType: "json",
            success: function(data) {
                $("#tools_span").html("Strings");
                $("#tools_display").text(data.strings);
            }
        });
    });
    $("#stack_button").click(function() {
        $.ajax({
        type: "GET",
        url: get_stackstrings,
        dataType: "json",
        success: function(data) {
            $("#tools_span").html("Stack Strings");
            $("#tools_display").text(data.strings);
        }
        });
    });
    $("#hex_button").click(function() {
        $.ajax({
        type: "GET",
        url: get_hex,
        dataType: "json",
        success: function(data) {
            $("#tools_span").html("Hex");
            $("#tools_display").text(data.strings);
        }
        });
    });
    $("form#form-xor").submit(function(e) {
        e.preventDefault();
        var result = $(this).serialize();
        $.ajax({
            type: "POST",
            url: xor_search,
            data: result,
            dataType: "json",
            success: function(data) {
                $("#xor_search_results").show();
                var options = "";
                for (var i = 0; i < data['keys'].length; i++) {
                    options +='<option value="' + data['keys'][i] + '">' + data['keys'][i] + '</option>';
                }
                $("#xor_key_select").html(options);
                $.ajax({
                    type: "GET",
                    url: get_xor + data['keys'][0],
                    dataType: "json",
                    success: function(data) {
                        $("#tools_span").html("XOR");
                        $("#tools_display").text(data.strings);
                    }
                });
            }
        });
    });
    $("#xor_key_select").change(function() {
        $.ajax({
            type: "GET",
            url: get_xor + $("#xor_key_select").val(),
            dataType: "json",
            success: function(data) {
                $("#tools_span").html("XOR");
                $("#tools_display").text(data.strings);
            }
        });
    });

    var localDialogs = {
    // XXX None of these currently update in-place, so we need to make the
    // submit do a default action for now to refresh the whole page.
    "add-backdoor": {title: "Backdoor", submit: defaultSubmit, href:"" },
    "add-exploit": {title: "Add Exploit", submit: defaultSubmit, href:"" },
    "add-child": {title: "Add Child Sample", submit: defaultSubmit, href:"" },
    "unzip-sample": {title: "Unzip Sample", submit: defaultSubmit, href:"" },
    "delete-sample": {title: "Delete Sample", submit: defaultSubmit, href:"" },
    "download-sample": {title: "Download Sample", submit: defaultSubmit, href:"" },
    };

    $.each(localDialogs, function(id,opt) {
        stdDialog(id,opt, {update: { open: update_dialog}});
    });

    // Moved here, as these appear to be only used in sample tools
    // setup static form for samples details tools tab
    $('#form-add-object-static').prepend($('#form-add-object').contents().clone())
    $('#form-add-object-static').find('#add_object_static').click(function(e) {
        // XXXX For some reason file_upload status is still not displaying here...
        $.proxy(file_upload_dialog, $('#form-add-object-static').parent())();
        add_object_submit(e);
    })

    // For samples_tools_widgets
    var comment_form = $('#form-comments');
    $('#form-comments').find('#id_url_key,#id_subscribable').val(comments_url_key);
    $('#form-add-comment-static').prepend(comment_form.contents().clone());

    $('#form-add-comment-static').submit(function(e) {
        addEditSubmit(e);
    });

    $('#sample_filename').editable(function(value, settings) {
        var revert = this.revert;
        return function(value, settings, elem) {
            var data = {
                'filename': value,
                'id': sample_id_escaped,
            };
            $.ajax({
                type: "POST",
                async: false,
                url: update_sample_filename,
                data: data,
                success: function(data) {
                    if (!data.success) {
                        value = revert;
                        $('#sample_filename_error').text(data.message);
                    }
                }
            });
            return value;
        }(value, settings, this);
        },
        {
            type: 'textarea',
            width: "400px",
            tooltip: "",
            cancel: "Cancel",
            submit: "Ok",
            onblur: 'ignore',
    });
    $("#sample_filenames").tagit({
        allowSpaces: true,
        removeConfirmation: false,
        afterTagAdded: function(event, ui) {
            var my_tags = $("#sample_filenames").tagit("assignedTags");
            update_filenames(my_tags);
        },
        beforeTagRemoved: function(event, ui) {
            if (is_admin != "True") {
                return false;
            }
        },
        afterTagRemoved: function(event, ui) {
            var my_tags = $("#sample_filenames").tagit("assignedTags");
            update_filenames(my_tags);
        },
    });

    function update_filenames(my_tags) {
        if (window.add_filenames) {
            var data = {
                        'id': sample_id_escaped,
                        'tags': my_tags.toString(),
            };
            $.ajax({
                type: "POST",
                url: update_sample_filenames,
                data: data,
                datatype: 'json',
                success: function(data) {
                    if (!data.success) {
                        alert("Failed to update filenames!");
                    }
                }
            });
        }
    }

    $(document).trigger('enable_filenames');

    details_copy_id('Sample');
    toggle_favorite('Sample');
    populate_id(sample_id_escaped, 'Sample');

});


text:
package com.peacecraftec.module.cmd;

import com.peacecraftec.module.Module;

public interface CommandManager {
    public void register(Module module, Object executor);

    public void unregister(Module module, Object executor);

    public void unregisterAll(Module module);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Aspose.Slides;
using Aspose.Cells;
using Aspose.Cells.Drawing;
using Aspose.Slides.Examples;
using Aspose.Slides.Examples.CSharp;
using Aspose.Cells.Rendering;
namespace CSharp.Shapes
{
   public  class ImageAsEMF
    {
   public static void Run()
   {
       string dataDir = RunExamples.GetDataDir_Shapes();
      //ExStart:ImageAsEMF
    Workbook book = new Workbook(dataDir + "chart.xlsx");
    Worksheet sheet = book.Worksheets[0];
    Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions();
    options.HorizontalResolution = 200;
    options.VerticalResolution = 200;
    options.ImageType = ImageType.Emf;

    //Save the workbook to stream
    SheetRender sr = new SheetRender(sheet, options);
    Presentation pres = new Presentation();
    pres.Slides.RemoveAt(0);

    String EmfSheetName="";
    for (int j = 0; j < sr.PageCount; j++)
    {

        EmfSheetName=dataDir + "test" + sheet.Name + " Page" + (j + 1) + ".out.emf";
        sr.ToImage(j, EmfSheetName);

        var bytes = File.ReadAllBytes(EmfSheetName);
        var emfImage = pres.Images.AddImage(bytes);
        ISlide slide= pres.Slides.AddEmptySlide(pres.LayoutSlides.GetByType(SlideLayoutType.Blank));
        var m = slide.Shapes.AddPictureFrame(ShapeType.Rectangle, 0, 0, pres.SlideSize.Size.Width, pres.SlideSize.Size.Height, emfImage);
    }

    pres.Save(dataDir+"Saved.pptx", Aspose.Slides.Export.SaveFormat.Pptx);

       //ExEnd:ImageAsEMF
   }
   }
}


text:
import firebase from 'firebase';

const debug = true;

class Auth {
  static anonymousLogin() {
    firebase.auth().signInAnonymously()
    .then((user) => {
      if (debug) { console.log('signed in successfully: ', user); }
    })
    .catch((error) => {
      if (debug) { console.log('error signing in: ', error); }
    });
  }

  static fbLogin(popup) {
    Auth.login(popup, new firebase.auth.FacebookAuthProvider());
  }

  static googleLogin(popup) {
    Auth.login(popup, new firebase.auth.GoogleAuthProvider());
  }

  static login(popup, provider) {
    provider.addScope('email');
    if (!firebase.auth().currentUser) {
      if (popup) {
        Auth.loginPopup(provider);
      } else {
        Auth.loginRedirect(provider);
      }
    } else if (popup) {
      Auth.linkPopup(provider);
    } else {
      Auth.linkRedirect(provider);
    }
  }

  static loginPopup(provider) {
    firebase.auth().signInWithPopup(provider)
    .catch((error) => {
      if (debug) { console.log('error signing in: ', error); }
    });
  }

  static loginRedirect(provider) {
    firebase.auth().signInWithRedirect(provider)
    .catch((error) => {
      if (debug) { console.log('error signing in: ', error); }
    });
  }

  static linkPopup(provider) {
    firebase.auth().currentUser.linkWithPopup(provider)
    .then((result) => {
      const user = result.user;
      const credential = result.credential;
      if (debug) { console.log('anonymous account successfully upgraded', user, credential); }
    }, (error) => {
      if (error.code === 'auth/credential-already-in-use') {
        firebase.auth().signInWithCredential(error.credential)
        .catch((err) => {
          if (debug) { console.log('error signing in with credential: ', err); }
        });
      } else if (debug) {
        console.log('error upgrading anonymous account: ', error);
      }
    });
  }

  static linkRedirect(provider) {
    firebase.auth().currentUser.linkWithRedirect(provider)
    .then((result) => {
      const user = result.user;
      const credential = result.credential;
      if (debug) { console.log('anonymous account successfully upgraded', user, credential); }
    }, (error) => {
      if (error.code === 'auth/credential-already-in-use') {
        firebase.auth().signInWithCredential(error.credential)
        .catch((err) => {
          if (debug) { console.log('error signing in with credential: ', err); }
        });
      } else if (debug) {
        console.log('error upgrading anonymous account: ', error);
      }
    });
  }

  static logout() {
    firebase.auth().signOut().then(() => {
      if (debug) { console.log('signed out successfully'); }
    }, (error) => {
      if (debug) { console.log('error signing out: ', error); }
    });
  }

}

export default Auth;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `C:/bot/slave/nightly-dist-rustc-win-64/build/src/libstd\collections\hash\state.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>state.rs.html -- source</title>

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

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use clone::Clone;
use default::Default;
use hash;
use marker;

/// A trait representing stateful hashes which can be used to hash keys in a
/// `HashMap`.
///
/// A HashState is used as a factory for instances of `Hasher` which a `HashMap`
/// can then use to hash keys independently. A `HashMap` by default uses a state
/// which will create instances of a `SipHasher`, but a custom state factory can
/// be provided to the `with_hash_state` function.
///
/// If a hashing algorithm has no initial state, then the `Hasher` type for that
/// algorithm can implement the `Default` trait and create hash maps with the
/// `DefaultState` structure. This state is 0-sized and will simply delegate
/// to `Default` when asked to create a hasher.
#[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
pub trait HashState {
    /// Type of the hasher that will be created.
    type Hasher: hash::Hasher;

    /// Creates a new hasher based on the given state of this object.
    fn hasher(&self) -> Self::Hasher;
}

/// A structure which is a factory for instances of `Hasher` which implement the
/// default trait.
///
/// This struct has is 0-sized and does not need construction.
#[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
pub struct DefaultState<H>(marker::PhantomData<H>);

impl<H: Default + hash::Hasher> HashState for DefaultState<H> {
    type Hasher = H;
    fn hasher(&self) -> H { Default::default() }
}

impl<H> Clone for DefaultState<H> {
    fn clone(&self) -> DefaultState<H> { DefaultState(marker::PhantomData) }
}

impl<H> Default for DefaultState<H> {
    fn default() -> DefaultState<H> { DefaultState(marker::PhantomData) }
}

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
from __future__ import print_function, division, absolute_import, unicode_literals

import sys
from functools import partial
from xml.etree import cElementTree as ET

from swid_generator.generators import swid_generator
from swid_generator.package_info import PackageInfo
from swid_generator.settings import DEFAULT_REGID, DEFAULT_ENTITY_NAME
from swid_generator.environments.common import CommonEnvironment
from swid_generator.generators.swid_generator import _create_flat_payload_tag, _create_hierarchic_payload_tag
from swid_generator.generators.swid_generator import software_id_matcher, package_name_matcher
from nose_parameterized import parameterized
from swid_generator.generators.content_creator import _sort_files

if sys.version_info < (2, 7):
    # We need the skip decorators from unittest2 on Python 2.6.
    import unittest2 as unittest
else:
    import unittest

class FileInfoMock(object):
    def __init__(self, name, location, size, mutable, full_pathname, full_pathname_splitted):
        self.name = name
        self.location = location
        self.size = size
        self.mutable = mutable
        self.full_pathname = full_pathname
        self.full_pathname_splitted = full_pathname_splitted

        self.actual_full_pathname = self.full_pathname

class Environment(CommonEnvironment):
    executable = 'asdfasdfa_env'
    os_string = 'SomeTestOS'

    def __init__(self, packages):
        self.packages = packages
        self.installed_states = {
            'install ok installed': True,
            'deinstall ok config-files': False
        }

    def get_package_list(self, include_files=False):
        return filter(self.package_installed, self.packages)

    def package_installed(self, package):
        return self.installed_states.get(package.status, True)

    @staticmethod
    def get_os_string():
        return Environment.os_string

    @staticmethod
    def get_architecture():
        return 'i686'

    def get_files_for_package(self, package):
        return []

class SwidGeneratorTests(unittest.TestCase):

    def setUp(self):

        cowsay_file1 = FileInfoMock('cowsay', 'tests/dumps/package_files/cowsay','4421', False,
                                    'tests/dumps/package_files/cowsay/cowsay',
                                    ['tests', 'dumps', 'package_files', 'cowsay', 'cowsay'])
        cowsay_file2 = FileInfoMock('pony-smaller.cow', 'tests/dumps/package_files/cowsay', '305', True,
                                    'tests/dumps/package_files/cowsay/pony-smaller.cow',
                                    ['tests', 'dumps', 'package_files', 'cowsay', 'pony-smaller.cow'])
        cowsay_file3 = FileInfoMock('copyright.txt', 'tests/dumps/package_files/cowsay/etc', '12854', True,
                                    'tests/dumps/package_files/cowsay/etc/copyright.txt',
                                    ['tests', 'dumps', 'package_files', 'cowsay', 'etc', 'copyright.txt'])

        fortune_file1 = FileInfoMock('fortune', 'tests/dumps/package_files/fortune', '1234', False,
                                     'tests/dumps/package_files/fortune/fortune',
                                     ['tests', 'dumps', 'package_files', 'fortune', 'fortune'])
        fortune_file2 = FileInfoMock('copyright', 'tests/dumps/package_files/fortune', '3333', False,
                                     'tests/dumps/package_files/fortune/copyright',
                                     ['tests', 'dumps', 'package_files', 'fortune', 'copyright'])
        fortune_file3 = FileInfoMock('config.txt', 'tests/dumps/package_files/fortune/usr', '45986', True,
                                     'tests/dumps/package_files/fortune/usr/config.txt',
                                     ['tests', 'dumps', 'package_files', 'usr', 'config.txt'])

        openssh_file1 = FileInfoMock('ssh.conf', '/etc/init/', '555', True, '/etc/init/ssh.conf',
                                     ['etc', 'init', 'ssh.conf'])
        openssh_file2 = FileInfoMock('sshd', '/usr/sbin/', '89484', False, '/usr/sbin/sshd',
                                     ['usr', 'sbin', 'sshd'])

        self.file_list = list()

        self.file_list.append(cowsay_file1)
        self.file_list.append(cowsay_file2)
        self.file_list.append(cowsay_file3)
        self.file_list.append(fortune_file1)
        self.file_list.append(fortune_file2)
        self.file_list.append(fortune_file3)
        self.file_list.append(openssh_file1)
        self.file_list.append(openssh_file2)

        self.packages = [
            PackageInfo('cowsay', '1.0', [cowsay_file1, cowsay_file2, cowsay_file3], 'install ok installed'),
            PackageInfo('fortune', '2.0', [fortune_file1, fortune_file2, fortune_file3], 'install ok installed'),
            PackageInfo('openssh-server', '7000', [openssh_file1, openssh_file2], 'deinstall ok config-files')
        ]

        docker_valid_deb = 'tests/dumps/package_files/docker.deb'
        docker_valid_rpm = 'tests/dumps/package_files/docker.rpm'

        self.file_packages = []

        self.file_packages.append(docker_valid_deb)
        self.file_packages.append(docker_valid_rpm)

        env = Environment(self.packages)
        kwargs = {
            'environment': env,
            'entity_name': DEFAULT_ENTITY_NAME,
            'regid': DEFAULT_REGID
        }
        self.swid_tag_generator = partial(swid_generator.create_swid_tags, **kwargs)

    def test_package_rc_state(self):
        output = self.swid_tag_generator(full=False)
        assert len(list(output)) == 2

    def test_non_pretty_output(self):
        output = self.swid_tag_generator(full=False)
        for idx, document_string in enumerate(output):
            root = ET.fromstring(document_string)

            #Test Entity tag
            assert root[0].attrib['regid'] == DEFAULT_REGID

            #Test SoftwareIdentity tag attributes
            assert root.attrib['version'] == self.packages[idx].version
            assert root.attrib['name'] == self.packages[idx].package
            assert root.attrib['tagId'] == '{os_info}-{architecture}-{pi.package}-{pi.version}'.format(
                os_info=Environment.os_string,
                architecture=Environment.get_architecture(),
                pi=self.packages[idx])

    def test_full_output(self):
        output = self.swid_tag_generator(full=True)
        for document in output:
            root = ET.fromstring(document)
            package_name = root.attrib['name']
            meta_tag = root[1]
            payload = root[2]

            assert meta_tag.attrib['product'] == '{os_info} {architecture}'.format(
                os_info=Environment.os_string, architecture=Environment.get_architecture())

            assert len(payload) == 2

            files = next(p for p in self.packages if p.package == package_name).files
            for directory_tag in payload:
                directory_fullpath = directory_tag.attrib['root'] + "/" + directory_tag.attrib['name']
                for file_tag in directory_tag:
                    test = [f for f in files if f.name == file_tag.attrib['name']
                            and f.location == directory_fullpath]

                    assert len(test) == 1
                    if test[0].mutable == 'True':
                        assert file_tag.attrib['mutable'] == 'True'
                    else:
                        with self.assertRaises(KeyError):
                            file_tag.attrib['mutable']
                    assert file_tag.attrib['size'] == test[0].size

    @parameterized.expand([
        ('cowsay', 1234, 0),
        ('cowsay', '1.0', 1),
        ('non-existent-software-id', 1337, 0)
    ])
    def test_targeted_software_id_test(self, package_name, package_version, expected_count):
        software_id = '{regid}_{os_info}-{architecture}-{package_name}-{package_version}' \
            .format(regid=DEFAULT_REGID,
                    package_name=package_name,
                    package_version=package_version,
                    os_info=Environment.os_string,
                    architecture=Environment.get_architecture())

        matcher = partial(software_id_matcher, value=software_id)
        output = list(self.swid_tag_generator(full=False, matcher=matcher))
        assert len(output) == expected_count

    @parameterized.expand([
        ('cowsay', 1),
        ('whiptail', 0)
    ])
    def test_targeted_package_name_test(self, package_name, expected):
        matcher = partial(package_name_matcher, value=package_name)
        output = list(self.swid_tag_generator(full=False, matcher=matcher))
        assert len(output) == expected

    def test_sort_files(self):

        sorted_files = _sort_files(self.file_list)

        expected_list = list()

        # exactly in these sequence, key-point is entry on index 3
        # /etc/copyright.txt is alphabetical before pony-smaller.cow, but
        # /etc/... is a folder and thus it must have one more nesting
        expected_list.append("/etc/init/ssh.conf")
        expected_list.append("tests/dumps/package_files/cowsay/cowsay")
        expected_list.append("tests/dumps/package_files/cowsay/pony-smaller.cow")
        expected_list.append("tests/dumps/package_files/cowsay/etc/copyright.txt")
        expected_list.append("tests/dumps/package_files/fortune/fortune")
        expected_list.append("tests/dumps/package_files/fortune/copyright")
        expected_list.append("tests/dumps/package_files/fortune/usr/config.txt")
        expected_list.append("/usr/sbin/sshd")

        for index, path in enumerate(expected_list):
            assert sorted_files[index].full_pathname == path

    def test_create_flat_payload(self):
        """
        Expected flat-payload-tag:
        <Payload>
            <Directory name="cowsay" root="tests/dumps/package_files">
                <File SHA256:hash="320c67b.." name="cowsay" size="4421" />
                <File SHA256:hash="62cca7d.." n8060:mutable="true" name="pony-smaller.cow" size="305" />
            </Directory>
            <Directory name="etc" root="tests/dumps/package_files/cowsay">
                <File SHA256:hash="92d4ee8.." n8060:mutable="true" name="copyright.txt" size="12854" />
            </Directory>
        </Payload>
        """

        payload_tag = _create_flat_payload_tag(self.packages[0], 'sha256')

        assert payload_tag[0].attrib['name'] == 'cowsay'
        assert payload_tag[0].attrib['root'] == 'tests/dumps/package_files'
        assert payload_tag[0][0].attrib['name'] == 'cowsay'
        assert payload_tag[0][1].attrib['name'] == 'pony-smaller.cow'

        assert payload_tag[1].attrib['name'] == 'etc'
        assert payload_tag[1].attrib['root'] == 'tests/dumps/package_files/cowsay'
        assert payload_tag[1][0].attrib['name'] == 'copyright.txt'

    def test_create_hierarchic_payload(self):
        """
        Expected hierarchic-payload-tag:
        <Payload>
            <Directory root="tests">
              <Directory name="dumps">
                <Directory name="package_files">
                  <Directory name="cowsay">
                    <File SHA256:hash="320c67b4.." name="cowsay" size="4421" />
                    <File SHA256:hash="62cca7d1.." n8060:mutable="true" name="pony-smaller.cow" size="305" />
                    <Directory name="etc">
                      <File SHA256:hash="92d4ee.." n8060:mutable="true" name="copyright.txt" size="12854" />
                    </Directory>
                  </Directory>
                </Directory>
              </Directory>
            </Directory>
        </Payload>
        """
        payload_tag = _create_hierarchic_payload_tag(self.packages[0], 'sha256')

        assert payload_tag[0].attrib['root'] == 'tests'
        assert payload_tag[0][0].attrib['name'] == 'dumps'
        assert payload_tag[0][0][0].attrib['name'] == 'package_files'
        assert payload_tag[0][0][0][0].attrib['name'] == 'cowsay'
        assert payload_tag[0][0][0][0][0].attrib['name'] == 'cowsay'
        assert payload_tag[0][0][0][0][1].attrib['name'] == 'pony-smaller.cow'
        assert payload_tag[0][0][0][0][2].attrib['name'] == 'etc'
        assert payload_tag[0][0][0][0][2][0].attrib['name'] == 'copyright.txt'


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fl. Crypt. Louvain 123 (1835)

#### Original name
Depazea bifrons J. Kickx f.

### Remarks
null


text:
import urllib2
import sys
import os
import time

'''Download "Entire Issue" of the Congressional Record for the period May 1 - 31 2014.'''

month = 5 # set month to May

# make an archive/ directory if it doesn't already exist
if not os.path.exists(os.getcwd() + "/archive"):
    os.mkdir(os.getcwd() + "/archive")

# try downloading the Congressional Record for May 2014
#for day in range(1,31):
for day in range(1,6):

    # construct the URL from which we will try to retrieve the record
    fileName = "CREC-2014-%02d-%02d.pdf" % (month,day)
    fileURL = "http://beta.congress.gov/crec/2014/%02d/%02d/%s"  % (month,day,fileName)
    localFile = os.getcwd() + "/archive/" + fileName

    # use the urllib2 module to fetch the record
    resp = urllib2.urlopen(fileURL)

    # write the record (PDF file) to a local file
    with open(localFile,"wb") as fout:
        fout.write(resp.read())

    print("Downloaded file %s." % fileURL)

    # inject interval between consecutive requests
    time.sleep(5)


text:
The idea of this project is simple: make the [colormaps of Python's matplotlib library](http://matplotlib.org/examples/color/colormaps_reference.html) available in JavaScript. I came up with it because I needed a colormap in JavaScript for a side project of mine and Google did not spit out any good results, so I decided to do it myself and make it available to the public.

## 🎨 What is a colormap?

If you have found this repository I presume you already know what a colormap is, but just for completeness' sake, a colormap formally is a function *f*: [0, 1] → [0, 255]³ that maps a _number_ onto a _color_, represented by a triplet of 8-bit integers (= the **r**ed, **g**reen, **b**lue values). Or at least that is the convention that I have adopted for this project. Of course, a lot of the time the values you want to colorcode are not between 0 and 1 — in this case, you will have to rescale them first.

## 🚀 How can I use the colormaps?

Most of the magic is contained in the `js-colormaps.js` file, which you need to include like:

```html
<script src="js-colormaps.js"></script>
```

Once you have loaded that file, you have either use the function `evaluate_cmap(x, name, reverse)`  to map a value `x` onto a color using the colormap specified by `name` and `reverse`:

```javascript
>> evaluate_cmap(0.5, 'viridis', false)
Array(3) [ 33, 144, 140 ]
```

Alternatively, you can also directly access every colormap by its name (using the `_r` suffix to reverse it):

```javascript
>> RdBu_r(0.25)
Array(3) [ 106, 172, 208 ]
```

## 🌈 Which colormaps are available?

[All of matplotlib's colormaps](https://matplotlib.org/stable/tutorials/colors/colormaps.html) are available, under the same name that you would use in Python:

![](images/overview.png)

*(Feel free to check out the `overview.html` file to see how this overview figure was created.)*

Additionally, it should not be too hard to modify the code in `create-colormaps.py` to also export other Python-based colormaps to JavaScript, for example, the [scientific colour maps](https://www.fabiocrameri.ch/colourmaps/) by Fabio Crameri.

## ⚖ Copyright

I did not invent any of the colormaps here, I do not own them, and I do not claim that I do. I just tried to make them available to others. If I happen to violate any of your copyrights with this project, please inform me *before* you drag me to court and we can sort this thing out :-)

Regarding my own copyrights: The project is released under the MIT license (see [LICENSE](https://github.com/timothygebhard/js-colormaps/blob/master/LICENSE) file), which pretty much means "Do whatever you want, but don't hold me liable!".


text:
(function TestBufferByteLengthNonSmi() {
  var non_smi_byte_length = %_MaxSmi() + 1;

  var buffer = new ArrayBuffer(non_smi_byte_length);

  var arr = new Uint16Array(buffer);

  assertEquals(non_smi_byte_length, arr.byteLength);
  assertEquals(non_smi_byte_length / 2, arr.length);

  arr = new Uint32Array(buffer);
  assertEquals(non_smi_byte_length, arr.byteLength);
  assertEquals(non_smi_byte_length / 4, arr.length);
})();

(function TestByteOffsetNonSmi() {
  var non_smi_byte_length = %_MaxSmi() + 11;

  var buffer = new ArrayBuffer(non_smi_byte_length);

  var whole = new Uint16Array(buffer);

  assertEquals(non_smi_byte_length, whole.byteLength);
  assertEquals(non_smi_byte_length / 2, whole.length);

  var arr = new Uint16Array(buffer, non_smi_byte_length - 10, 5);

  assertEquals(non_smi_byte_length, arr.buffer.byteLength);
  assertEquals(10, arr.byteLength);
  assertEquals(5, arr.length);
})();


text:
.class Landroid/support/v17/leanback/app/BrowseFragment$12;
.super Landroid/support/v7/widget/RecyclerView$OnScrollListener;
.source "BrowseFragment.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/support/v17/leanback/app/BrowseFragment;->swapToMainFragment()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/support/v17/leanback/app/BrowseFragment;

.field final synthetic val$gridView:Landroid/support/v17/leanback/widget/VerticalGridView;

# direct methods
.method constructor <init>(Landroid/support/v17/leanback/app/BrowseFragment;Landroid/support/v17/leanback/widget/VerticalGridView;)V
    .locals 0

    iput-object p1, p0, Landroid/support/v17/leanback/app/BrowseFragment$12;->this$0:Landroid/support/v17/leanback/app/BrowseFragment;

    iput-object p2, p0, Landroid/support/v17/leanback/app/BrowseFragment$12;->val$gridView:Landroid/support/v17/leanback/widget/VerticalGridView;

    invoke-direct {p0}, Landroid/support/v7/widget/RecyclerView$OnScrollListener;-><init>()V

    return-void
.end method

# virtual methods
.method public onScrollStateChanged(Landroid/support/v7/widget/RecyclerView;I)V
    .locals 5

    if-nez p2, :cond_0

    iget-object v2, p0, Landroid/support/v17/leanback/app/BrowseFragment$12;->val$gridView:Landroid/support/v17/leanback/widget/VerticalGridView;

    invoke-virtual {v2, p0}, Landroid/support/v17/leanback/widget/VerticalGridView;->removeOnScrollListener(Landroid/support/v7/widget/RecyclerView$OnScrollListener;)V

    iget-object v2, p0, Landroid/support/v17/leanback/app/BrowseFragment$12;->this$0:Landroid/support/v17/leanback/app/BrowseFragment;

    invoke-virtual {v2}, Landroid/support/v17/leanback/app/BrowseFragment;->getChildFragmentManager()Landroid/app/FragmentManager;

    move-result-object v1

    sget v2, Landroid/support/v17/leanback/R$id;->scale_frame:I

    invoke-virtual {v1, v2}, Landroid/app/FragmentManager;->findFragmentById(I)Landroid/app/Fragment;

    move-result-object v0

    iget-object v2, p0, Landroid/support/v17/leanback/app/BrowseFragment$12;->this$0:Landroid/support/v17/leanback/app/BrowseFragment;

    iget-object v2, v2, Landroid/support/v17/leanback/app/BrowseFragment;->mMainFragment:Landroid/app/Fragment;

    if-eq v0, v2, :cond_0

    invoke-virtual {v1}, Landroid/app/FragmentManager;->beginTransaction()Landroid/app/FragmentTransaction;

    move-result-object v2

    sget v3, Landroid/support/v17/leanback/R$id;->scale_frame:I

    iget-object v4, p0, Landroid/support/v17/leanback/app/BrowseFragment$12;->this$0:Landroid/support/v17/leanback/app/BrowseFragment;

    iget-object v4, v4, Landroid/support/v17/leanback/app/BrowseFragment;->mMainFragment:Landroid/app/Fragment;

    invoke-virtual {v2, v3, v4}, Landroid/app/FragmentTransaction;->replace(ILandroid/app/Fragment;)Landroid/app/FragmentTransaction;

    move-result-object v2

    invoke-virtual {v2}, Landroid/app/FragmentTransaction;->commit()I

    :cond_0
    return-void
.end method


text:
from os.path import join
from logging import getLogger

import click

from ..database.rfam import filter_models

logger = getLogger(__name__)

# keep this command hidden from help msg
# this option is only available in click v7
@click.command()
@click.option('--operation', type=click.Choice(['bacteria', 'archaea', 'eukarya', 'default']),
              default='default', required=True,
              help='Keep bacteria/archaea/eukarya rRNA models or filter away tRNA, tmRNA, rRNA models (default)')
@click.argument('infile', type=click.File('r'), nargs=1)
@click.argument('outfile', type=click.Path(),  nargs=1, default='rfam_filtered.cm')
@click.pass_context
def cli(ctx, operation, infile, outfile):
    '''Create rfam database for micronota usage.'''
    kingdom_models = {'bacteria': {('RF00001', '5S_rRNA'),
                                   ('RF00177', 'SSU_rRNA_bacteria'),
                                   ('RF02541', 'LSU_rRNA_bacteria')},
                      'archaea': {('RF00001', '5S_rRNA'),
                                  ('RF01959', 'SSU_rRNA_archaea'),
                                  ('RF02540', 'LSU_rRNA_archaea')},
                      'eukarya': {('RF00001', '5S_rRNA'),
                                  ('RF00002', '5_8S_rRNA'),
                                  ('RF01960', 'SSU_rRNA_eukarya'),
                                  ('RF02543', 'LSU_rRNA_eukarya')}}
    if operation == 'default':
        with open(join(outfile), 'w') as out:
            filter_models(infile, out)
    else:
        with open(outfile, 'w') as out:
            filter_models(infile, out, negate=True, models=kingdom_models[kingdom])


text:
#include <click/config.h>
#include <click/router.hh>
#include <click/standard/scheduleinfo.hh>
#include "schedulelinux.hh"
#include <click/error.hh>
#include <click/glue.hh>

ScheduleLinux::ScheduleLinux()
  : _task(this)
{
}

ScheduleLinux::~ScheduleLinux()
{
}

int
ScheduleLinux::initialize(ErrorHandler *errh)
{
  ScheduleInfo::join_scheduler(this, &_task, errh);
  return 0;
}

bool
ScheduleLinux::run_task(Task *)
{
  schedule();
  _task.fast_reschedule();
  return true;
}

void
ScheduleLinux::add_handlers()
{
  add_task_handlers(&_task);
}

ELEMENT_REQUIRES(linuxmodule)
EXPORT_ELEMENT(ScheduleLinux)


text:
require 'nokogiri'
require 'open-uri'
require 'json'

module CodeCitations
  module Plos
    def self.search(name, urls, authors)
      page = 1
      found = []

      authors = "(" +
        authors[0..2].map{|author| "(" + author.split(' ').join(' OR ') + ")"}.join(' OR ') +
      ")"

      search_string = "(everything:\"#{name}\") OR "
      search_string += "(reference:" + [name, authors].map{|s| "\"#{s}\""}.join(' AND ') + ")"

      urls.each do |url|
        search_string += " OR everything:\"#{url}\""
      end

      loop do
        start = (page - 1) * 100
        api_url = "http://api.plos.org/search?q=#{search_string}&api_key=7Jne3TIPu6DqFCK=&rows=100&wt=json&start=#{start}"
        response = open(URI.encode(api_url)).read
        results = JSON.parse(response)['response']['docs']
        break if results.empty?
        results.each do |result|
          doi = result['id']
          next unless doi
          found << doi
        end
        page += 1
      end
      found.uniq
    end
  end
end