text:
package org.mitre.provenance.npe;

import java.util.Calendar;
import java.util.Date;

import java.util.logging.Logger;
import org.mitre.provenance.EdgeMarking;
import org.mitre.provenance.PLUSException;
import org.mitre.provenance.plusobject.AbstractDirectedEdge;
import org.mitre.provenance.plusobject.PLUSObject;
import org.mitre.provenance.tools.PLUSUtils;

/**
 * A Non-Provenance Edge (NPE) is an edge that expresses a relationship between a PLUSObject, and a non-PLUSObject data structure
 * that is stored outside of a provenance store.  For example, to express the fact that a PLUSObject is equivalent to, or
 * the same as some other item of data in another store, a non-provenance edge between the PLUSObject and the other data item
 * might be created.
 *
 *
Non-Provenance edges always have the constraint that the "from" portion of the edge must be a provenance object, that is,
 * it must have a valid PLUS OID.
 *
 *
NPEs may connect two provenance objects.  If an NPE connects a PLUSObject to something else, it is essentially only a single atomic
 * value.  That is, if the "to" end of the NPE does not refer to a PLUSObject, there is no further way to elaborate that data.  This is
 * an intentional constraint placed on NPEs; they are envisioned to be used as a way to connect to external sources of data by reference,
 * but it isn't within the scope of PLUS to store arbitrary graph information.  As a result, there is no way to connect a PLUSObject to
 * another node with an arbitrary set of properties or metadata.
 *
 *
Common use cases for NPEs will be when you want to associate external identifiers for items (like a URI/URL, or a unique ID in a
 * different database outside of the scope of PLUS)
 *
 *
Here are a few examples of valid NPEs, let's start by assuming that "A" refers to a PLUSDataObject node, and "B" refers to another
 * "PLUSDataObject" node.

 *
A -- (similar to) --> B

 *
A -- (URI) --> http://www.google.com/

 *
A -- (reviewed by) --> "James Smith"

 *
A -- (comment) --> "I think this looks goofy"

 *

 *
 * @author dmallen
 */
public class NonProvenanceEdge extends AbstractDirectedEdge {
	/** The unique ID of the NPE itself */
	protected String oid;

	/** The time when the NPE was created, in milliseconds since the epoch */
	protected long created;

	/** The ID of the head of the edge */
	protected String from;

	/** The ID of the tail of the edge */
	protected String to;

	/** The type of the edge */
	protected String type;

	/** Default NPE edge type to use when you are using an NPE to indicate hashed content. */
	public static final String NPE_TYPE_CONTENT_HASH = "content hash";

	/** Default NPE edge type to indicate when you are using an NPE to indicate a URI for a resource */
	public static final String NPE_TYPE_URI = "URI";

	/** Default NPE edge type indicating that the edge expresses an "alias" relationship. */
	public static final String NPE_TYPE_ALIAS = "alias";

	/** Default NPE edge type indicating that the edge expresses a "containment" relationship */
	public static final String NPE_TYPE_CONTAINMENT = "contains";

	/** Default NPE edge type indicating a set of sequenced steps */
	public static final String NPE_TYPE_SEQUENCE_STEP = "sequence step";

	protected static Logger log = Logger.getLogger(NonProvenanceEdge.class.getName());

	/**
	 * Create a new NPE
	 * @param from the ID of the starting object.  This must be a PLUSObject ID.
	 * @param to the destination of the edge (can be any string, see examples)
	 * @param type the type of the edge (can be anything, but see provided example edge types)
	 * @throws PLUSException
	 */
	public NonProvenanceEdge(String from, String to, String type) throws PLUSException {
		// this is for a NEW NPE.
		this(PLUSUtils.generateID(), from, to, type, System.currentTimeMillis());
	} // End NonProvenanceEdge

	/**
	 * Create a new NPE between two PLUSObjects.
	 * @param from the head of the edge
	 * @param to the tail of the edge
	 * @param type the type of the edge (can be anything, but see provided example edge types)
	 * @throws PLUSException
	 */
	public NonProvenanceEdge(PLUSObject from, PLUSObject to, String type) throws PLUSException {
		this(PLUSUtils.generateID(), from.getId(), to.getId(), type, System.currentTimeMillis());
	}

	/**
	 * Create a new NPE
	 * @param from the head of the edge
	 * @param npid a non-provenance identifier (can be anything, but see provided examples for how to use this)
	 * @param type the type of the edge (can be anything, but see provided example edge types)
	 * @throws PLUSException
	 */
	public NonProvenanceEdge(PLUSObject from, String npid, String type) throws PLUSException {
		this(PLUSUtils.generateID(), from.getId(), npid, type, System.currentTimeMillis());
	}

	/**
	 * Raw constructor.  No touchy!   You probably shouldn't be using this.
	 * @param oid
	 * @param from
	 * @param to
	 * @param type
	 * @param created
	 * @throws PLUSException if the 'from' side of the link is not a PLUS ID.
	 */
	public NonProvenanceEdge(String oid, String from, String to, String type, long created) throws PLUSException {
		if(!PLUSUtils.isPLUSOID(from)) throw new PLUSException("The from portion of all NonProvenanceEdge objects must be a valid PLUS ID");

		setCreated(created);
		setId(oid);
		setFrom(from);
		setTo(to);
		setType(type);
		setFromMarking(EdgeMarking.SHOW);
		setToMarking(EdgeMarking.SHOW);
	}

	/** Return the head identifier of the edge */
	public String getFrom() { return from; }

	/** Set the head identifier of the edge */
	protected void setFrom(String from) { this.from = from; }

	/** Get the tail identifier of the edge */
	public String getTo() { return to; }

	/** Set the tail identifier of the edge */
	protected void setTo(String to) { this.to = to; }

	/** Return the type of the edge */
	public String getType() { return type; }

	/** Set the type of the edge */
	public void setType(String type) { this.type = type; }

	/** Get the edge's ID.  Note that this is *not* an incident node ID, it is the edge itself's ID */
	public String getId() { return oid; }

	/** Set the edge's ID. */
	protected void setId(String oid) { this.oid = oid; }

	/** Get the edge's create time (ms since the epoch) */
	public long getCreated() { return created; }

	/** Return the edge's creation time as a java Date. */
	public Date getCreatedAsDate() { return new java.util.Date(created); }

	/** Set the edge's created time */
	protected void setCreated(long creationTime) { created = creationTime; }

	/**
	 * Sets the object's created timestamp to this moment in milliseconds since the epoch, UTC
	 */
	public void setCreated() {
		Calendar calInitial = Calendar.getInstance();
        int offsetInitial = calInitial.get(Calendar.ZONE_OFFSET)
                + calInitial.get(Calendar.DST_OFFSET);

        long current = System.currentTimeMillis();

        // Check right time
        created = current - offsetInitial;
	}

	public String toString() {
		return "NPE: from=" + getFrom() + " to=" + getTo() + " type=" + getType();
	}
} // End NonProvenanceEdge


text:
/*global describe, beforeEach, it*/
'use strict';

var path    = require('path');
var helpers = require('yeoman-generator').test;

describe('demo generator', function () {
	beforeEach(function (done) {
		helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
			if (err) {
				return done(err);
			}

			this.app = helpers.createGenerator('demo:app', [
				'../../app'
			]);
			done();
		}.bind(this));
	});

	it('creates expected files', function (done) {
		var expected = [
			'.jshintrc',
			'.editorconfig',
			'README.md',
			'index.html',
			'css/index.css',
			'js/index.js',
			'bower.json',
			'package.json'
		];

		helpers.mockPrompt(this.app, {
			'title': 'My Awesome Demo'
		});
		this.app.options['skip-install'] = true;
		this.app.run({}, function () {
			helpers.assertFiles(expected);
			done();
		});
	});
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Mini\Model;

use \PDO;

class ListDescriptor
{
    public const DIR_ASC = 1;
    public const DIR_DESC = 2;

    /** @var int */
    public $offset = 0;
    /** @var int */
    public $limit;
    /** @var int */
    public $direction = self::DIR_DESC;
    /** @var string */
    public $orderBy;
    /** @var string[]|null */
    public $ids = [];

    protected static $idField = 'id';
    protected static $idType = PDO::PARAM_STR;

    protected $query = '';
    protected $tempTables = [];
    private $params = [];
    private $paramTypes = [];
    private $queryBuilt = false;

    function __constructor() {
        $this->ids = [];
        $this->reset();
    }

    protected function addParam($value, int $type = PDO::PARAM_STR): void
    {
        $this->params[] = $value;
        $this->paramType[count($this->params) - 1] = $type;
    }

    private function addLimit(): void
    {
        if($this->limit) {

            if($this->offset > 0) {
                $this->query .= ' LIMIT ?,?';
                $this->addParam($this->offset, PDO::PARAM_INT);
                $this->addParam($this->limit, PDO::PARAM_INT);
            }
            else {
                $this->query .= ' LIMIT ?';
                $this->addParam($this->limit, PDO::PARAM_INT);
            }
        }
    }

    private function addOrder(): void
    {
        if($this->orderBy) {
            $this->query .= ' ORDER BY '.$this->orderBy;
            if($this->direction == self::DIR_ASC) {
                $this->query .= ' ASC';
            }
            else {
                $this->query .= ' DESC';
            }
        }
    }

    protected function getTempName(string $param): string
    {
        return 'tempvals'.$param;
    }

    /**
     * @return string[]
     */
    protected function addWhere(): array
    {
        $where = [];

        if($this->ids && count($this->ids)) {
            $this->tempTables['ids'] = self::$idType;
            $tableName = $this->getTempName('ids');

            $this->query .= ' INNER JOIN '.$tableName.' ON '.$tableName.'.value = '.static::$idField;
        }

        return $where;
    }

    public function makeSQLQuery(): string
    {
        if(!$this->queryBuilt) {
            $where = $this->addWhere();
            if(count($where)) {
                $this->query .= ' WHERE '.implode(' AND ', $where);
            }
            $this->addOrder();
            $this->addLimit();
            $this->queryBuilt = true;
        }

        return $this->query;
    }

    public function bindParams(\PDOStatement $query): void
    {
        foreach($this->params as $i => $value) {
            $type = $this->paramTypes[$i] ?? PDO::PARAM_STR;
            Store::BindNullable($query, $i + 1, $value, $type);
        }
    }

    private function dbTypeFromPDO(int $pdoType): string
    {
        switch($pdoType) {
            case PDO::PARAM_INT:
                return "int(10)";
            default:
                return "varchar(535)";
        }
    }

    public function hasTempTables(): bool
    {
        return count($this->tempTables) > 0;
    }

    public function makeTempTables(PingablePDO $db): void
    {
        $value;
        $i;
        foreach($this->tempTables as $name => $type) {
            $tableName = $this->getTempName($name);

            $sql = 'CREATE TEMPORARY TABLE '.$tableName.' (`value` '.$this->dbTypeFromPDO($type).' CHARACTER SET utf8 NOT NULL, `index` varchar(535) CHARACTER SET utf8 NOT NULL)';
            $createQ = $db->prepare($sql);
            $createQ->execute();

            $sql = 'INSERT INTO '.$tableName.' (`value`,`index`) VALUES (?,?)';
            $query = $db->prepare($sql);
            $query->bindParam(1, $value, $type);
            $query->bindParam(2, $i);
            foreach($this->{$name} as $i => $value) {
                $query->execute();
            }
        }
    }

    public function removeTempTables(): string
    {
        $sql = '';
        foreach($this->tempTables as $name => $type) {
            $sql .= "DROP TABLE IF EXISTS `".$this->getTempName($name)."`;";
        }
        return $sql;
    }

    public function reset(): void
    {
        $this->query = '';
        $this->params = [];
        $this->paramTypes = [];
        $this->tempTables = [];
        $this->queryBuilt = false;
    }
}


text:
// Copyright 2017 Google Inc.
//
// 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.cloud.sme.pubsub;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.google.api.core.ApiFuture;
import com.google.api.gax.batching.BatchingSettings;
import com.google.cloud.sme.Entities;
import com.google.cloud.sme.common.ActionReader;
import com.google.cloud.sme.common.FileActionReader;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.ProjectTopicName;
import com.google.pubsub.v1.PubsubMessage;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import org.joda.time.DateTime;
import org.threeten.bp.Duration;

/** A basic Pub/Sub publisher for purposes of demonstrating use of the API. */
public class Publisher {
  public static class Args {
    @Parameter(
        names = {"--project", "-p"},
        required = true,
        description = "The Google Cloud Pub/Sub project in which the topic exists.")
    public String project = null;
  }

  private static final String SOURCE_DATA = "actions.csv";
  private static final String TIMESTAMP_KEY = "publish_time";
  private static final String TOPIC = "pubsub-e2e-example";
  private static final int MESSAGE_COUNT = 10000000;

  private final Args args;
  private com.google.cloud.pubsub.v1.Publisher publisher;
  private ActionReader actionReader;
  private AtomicLong awaitedFutures;
  private ExecutorService executor = Executors.newCachedThreadPool();

  private Stats stats;

  private Publisher(Args args, ActionReader actionReader) {
    this.args = args;
    this.actionReader = actionReader;
    this.awaitedFutures = new AtomicLong();
    this.stats = new Stats();

    ProjectTopicName topic = ProjectTopicName.of(args.project, TOPIC);
    com.google.cloud.pubsub.v1.Publisher.Builder builder =
        com.google.cloud.pubsub.v1.Publisher.newBuilder(topic);
    builder.setBatchingSettings(
        BatchingSettings.newBuilder()
            // Message sizes are uniform, so it is not interesting to think about
            // the size of messages sent.
            .setRequestByteThreshold(1_000_000_000L)
            // Try to batch as many messages as possible into a batch.
            .setElementCountThreshold(1000L)
            // Wait longer than default to fill up a batch.
            .setDelayThreshold(Duration.ofMillis(50))
            .build());
    try {
      this.publisher = builder.build();
    } catch (Exception e) {
      System.out.println("Could not create publisher: " + e);
      System.exit(1);
    }
  }

  private void Publish(Entities.Action publishAction) {
    awaitedFutures.incrementAndGet();
    final long publishTime = DateTime.now().getMillis();
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.putLong(publishAction.getItemId());
    PubsubMessage message =
        PubsubMessage.newBuilder()
            .setData(ByteString.copyFrom(buffer))
            .putAttributes(TIMESTAMP_KEY, Long.toString(publishTime))
            .build();
    ApiFuture<String> response = publisher.publish(message);
    response.addListener(
        () -> {
          try {
            stats.recordLatency(DateTime.now().getMillis() - publishTime);
            response.get();
          } catch (Exception e) {
            System.out.println("Could not publish a message: " + e);
          } finally {
            awaitedFutures.decrementAndGet();
          }
        },
        executor);
  }

  private void run() {
    stats.start();
    awaitedFutures.incrementAndGet();

    long count = 0;
    Entities.Action nextAction = actionReader.next();
    for (int i = 0; i < MESSAGE_COUNT; ++i) {
      Publish(nextAction);
      if ((i + 1) % 100000 == 0) {
        System.out.println("Published " + (i + 1) + " messages.");
      }
      nextAction = actionReader.next();
    }
    awaitedFutures.decrementAndGet();
  }

  private void waitForPublishes() {
    try {
      while (awaitedFutures.longValue() > 0) {
        Thread.sleep(5000);
      }
    } catch (InterruptedException e) {
      System.out.println("Error while waiting for completion: " + e);
    }
    stats.stop(DateTime.now().getMillis());
    executor.shutdownNow();
  }

  private void shutdown() {
    try {
      publisher.shutdown();
    } catch (Exception e) {
      System.out.println("Error while shutting down: " + e);
    }
  }

  private void printStats() {
    Map<Double, Long> latencies = stats.getLatencies();
    Long throughput = stats.getThroughputMessages();
    System.out.println("Publishing complete.");
    System.out.println("Published " + stats.getMessageCount() + " messages.");
    System.out.println("Publish latency");
    for (Map.Entry<Double, Long> latency : latencies.entrySet()) {
      System.out.println(" " + latency.getKey() + "th percentile: " + latency.getValue() + "ms");
    }
    System.out.println("Throughput: " + throughput + " messages/s");
  }

  public static void main(String[] args) {
    Args parsedArgs = new Args();
    JCommander.newBuilder().addObject(parsedArgs).build().parse(args);

    ActionReader actionReader = new FileActionReader(SOURCE_DATA);

    Publisher p = new Publisher(parsedArgs, actionReader);

    p.run();
    p.waitForPublishes();
    p.shutdown();
    p.printStats();
    System.exit(0);
  }
}


text:
var eventMessageChunker = require('../../lib/event-stream/event-message-chunker').eventMessageChunker;
var testEventMessages = require('./test-event-messages.fixture');

describe('eventMessageChunker', function() {
    var eventMessagesPayload = Buffer.concat([
        testEventMessages.recordEventMessage,
        testEventMessages.statsEventMessage,
        testEventMessages.endEventMessage
    ]);

    it('should split individual messages', function() {
        var messages = eventMessageChunker(eventMessagesPayload);

        expect(messages.length).to.equal(3);
    });

    it('should maintain event ordering', function() {
        var mockEventMessages = [
            testEventMessages.recordEventMessage,
            testEventMessages.statsEventMessage,
            testEventMessages.recordEventMessage,
            testEventMessages.endEventMessage
        ];
        var eventMessagesPayload = Buffer.concat(mockEventMessages);

        var messages = eventMessageChunker(eventMessagesPayload);

        expect(messages.length).to.equal(4);
        for (var i = 0; i < messages.length; i++) {
            expect(messages[i].toString('base64')).to.equal(mockEventMessages[i].toString('base64'));
        }
    });
});


text:
NODE_BIN = ./node_modules/.bin

#
# Tasks
#

validate:
	@${NODE_BIN}/standard *.js

test:
	@${NODE_BIN}/tape test/*.js

ci: validate test

.PHONY: test validate ci


text:
namespace moon
{

// ========================================================
// struct Symbol:
// ========================================================

struct Symbol final
{
    static constexpr int LineNumBuiltIn = -1;

    enum class Type : UInt8
    {
        Undefined,
        IntLiteral,
        FloatLiteral,
        BoolLiteral,
        StrLiteral,
        Identifier,

        // Number of types. Internal use.
        Count
    };

    union Value
    {
        Int64           asInteger;
        Float64         asFloat;
        bool            asBoolean;
        ConstRcString * asString; // Reference held if type == StrLiteral | Identifier.

        Value() noexcept { asInteger = 0; }
    };

    ConstRcString * name;    // Pointer to the symbol name in the parent table. Not owned/referenced by Symbol.
    const Value     value;   // Intrinsic value of the symbol.
    const int       lineNum; // Line number in the source file where it was found. Negative for built-ins.
    const Type      type;    // Type that defines the symbol's value.

    // Value conversion helpers:
    static Value valueFromIntegerStr(const char * cstr);
    static Value valueFromFloatStr(const char * cstr);
    static Value valueFromBoolStr(const char * cstr);
    static Value valueFromRcStr(ConstRcString * rstr); // Adds a ref

    // Compare this type and value for equality with the provided params.
    bool cmpEqual(Type otherType, Value otherValue) const;

    // Compare the provide string (or hash thereof) for equality with this symbol's *name*.
    bool cmpEqual(const char * otherName) const;
    bool cmpEqual(const UInt32 otherNameHash) const noexcept
    {
        return name->hashVal == otherNameHash;
    }

    // Test if the symbol's name is equal to one of the built-in types, e.g.: int, float, string, etc.
    bool isBuiltInTypeId() const;

    // Print the symbol as a table row for use by the SymbolTable.
    void print(std::ostream & os) const;
};

std::string toString(const Symbol & symbol); // Symbol value to string.
std::string toString(Symbol::Type type);     // Symbol type to string.

// ========================================================
// class SymbolTable:
// ========================================================

class SymbolTable final
    : public Registry<const Symbol *>
{
public:

     SymbolTable();
    ~SymbolTable();

    // Symbol access by name/id. Null returned if not found.
    const Symbol * findSymbol(ConstRcString * const name) const { return findInternal(name); }
    const Symbol * findSymbol(const char * name) const          { return findInternal(name); }

    // Add new symbol. Symbol must NOT be in the table. Fails with an assertion
    // if a symbol with the same NAME is already present. Returns the new symbol.
    // Note: The symbol table will add ref to the name string, so generally you'll
    // want to pass this method a string acquired from newConstRcString().
    const Symbol * addSymbol(ConstRcString * name, int declLineNum, Symbol::Type type, Symbol::Value value);
    const Symbol * addSymbol(const char * name, int declLineNum, Symbol::Type type, Symbol::Value value);

    // Find a registered literal value with the equivalent string value or define a new one.
    // The name used to register the new literal will be auto-generated.
    const Symbol * findOrDefineLiteral(ConstRcString * valueStr, int declLineNum, Symbol::Type typeWanted);
    const Symbol * findOrDefineLiteral(const char * valueStr, int declLineNum, Symbol::Type typeWanted);

    // Find a registered identifier with the given name or define a new one.
    const Symbol * findOrDefineIdentifier(ConstRcString * name, int declLineNum);
    const Symbol * findOrDefineIdentifier(const char * name, int declLineNum);

    // Shorthand to define built-in strings or number values:
    const Symbol * findOrDefineIntLiteral(Int64 value);
    const Symbol * findOrDefineFloatLiteral(Float64 value);
    const Symbol * findOrDefineBoolLiteral(bool value);
    const Symbol * findOrDefineStrLiteral(const char * valueStr);

    // Print the whole table in table format (no pun intended).
    void print(std::ostream & os) const;

    // Auto-generated name for literal symbol types (IntLiteral, FloatLiteral, BoolLiteral, StrLiteral only).
    ConstRcStrUPtr generateSymbolName(Symbol::Type type);

private:

    // For generated names.
    UInt32 nextSymId = 0;

    // Symbols are allocated from here. The table holds pointers into this pool.
    Pool<Symbol, MOON_SYMBOL_POOL_GRANULARITY> symbolPool;
};

inline std::ostream & operator << (std::ostream & os, const SymbolTable & symTable)
{
    symTable.print(os);
    return os;
}

} // namespace moon {}

#endif // MOON_SYMBOL_TABLE_HPP


text:
package pw.mario.faces.credential.filter;

import java.io.IOException;

import javax.faces.application.ResourceHandler;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(servletNames="Faces Servlet")
public class NoCacheFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if (!req.getRequestURI().startsWith(req.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) {
            res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            res.setHeader("Pragma", "no-cache");
            res.setDateHeader("Expires", 0);
        }

        chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

}


text:
'use strict'
const cli = require('heroku-cli-util')

const HOST = process.env.HEROKU_REDIS_HOST || 'redis-api.heroku.com'
const ADDON = process.env.HEROKU_REDIS_ADDON_NAME || 'heroku-redis'

module.exports = (context, heroku) => {
  return {
    request(path, method, body) {
      let headers = { Accept: 'application/json' }
      if (process.env.HEROKU_HEADERS) {
        Object.assign(headers, JSON.parse(process.env.HEROKU_HEADERS))
      }
      return heroku[(method || 'GET').toLowerCase()](path, {
        host: HOST,
        auth: `${context.auth.username}:${context.auth.password}`,
        headers,
        body,
      })
    },

    makeAddonsFilter(filter) {
      if (filter) {
        filter = filter.toUpperCase()
      }

      function matches(addon) {
        for (let i = 0; i < addon.config_vars.length; i++) {
          let cfgName = addon.config_vars[i].toUpperCase()
          if (cfgName.indexOf(filter) >= 0) {
            return true
          }
        }
        if (addon.name.toUpperCase().indexOf(filter) >= 0) {
          return true
        }
        return false
      }

      function onResponse(addons) {
        let redisAddons = []
        for (let i = 0; i < addons.length; i++) {
          let addon = addons[i]
          let service = addon.addon_service.name

          if (service.indexOf(ADDON) === 0 && (!filter || matches(addon))) {
            redisAddons.push(addon)
          }
        }
        return redisAddons
      }

      return onResponse
    },

    async getRedisAddon(addonsList) {
      addonsList = addonsList || heroku.get(`/apps/${context.app}/addons`)

      let addonsFilter = this.makeAddonsFilter(context.args.database)
      let addons = addonsFilter(await addonsList)

      if (addons.length === 0) {
        cli.exit(1, 'No Redis instances found.')
      } else if (addons.length > 1) {
        let names = addons.map(function (addon) {
          return addon.name
        })
        cli.exit(1, `Please specify a single instance. Found: ${names.join(', ')}`)
      }

      return addons[0]
    },

    async info() {
      let addons = await heroku.get(`/apps/${context.app}/addons`)
      // filter out non-redis addons
      addons = this.makeAddonsFilter(context.args.database)(addons)
      // get info for each db
      let databases = addons.map((addon) => {
        return {
          addon: addon,
          redis: this.request(`/redis/v0/databases/${addon.name}`).catch(function (err) {
            if (err.statusCode !== 404) {
              throw err
            }
            return null
          }),
        }
      })

      if (context.flags.json) {
        let redii = []
        for (let db of databases) {
          let redis = await db.redis
          if (redis == null) {
            continue
          }

          redis.app = db.addon.app
          redis.config_vars = db.addon.config_vars
          const { formation, metaas_source, port, ...filteredRedis } = redis
          redii.push(filteredRedis)
        }
        cli.styledJSON(redii)
        return
      }

      // print out the info of the addon and redis db info
      for (let db of databases) {
        const redis = await db.redis
        if (redis === null) {
          continue
        }

        cli.styledHeader(`${db.addon.name} (${db.addon.config_vars.join(', ')})`)
        cli.styledHash(
          redis.info.reduce(function (memo, row) {
            memo[row.name] = row.values
            return memo
          }, {}),
          redis.info.map(function (row) {
            return row.name
          }),
        )
      }
    },
  }
}


text:
Meteor.publishComposite("revisionsQueue", function(status, limit) {

	return {
		find: function() {
			return Revisions.find({status: status}, {limit: limit, sort: {createdAt: -1}});
		},
		children: [{
			find: function(revision) {
				switch (revision.contentType) {
					case "Anime":
						if (revision.type === "Revision") {
							return Anime.find({_id: revision.content._id});
						}
				}
			}
		}]
	};
});


text:
如果期望使用Spock测试一个Spring Boot应用,你应该将Spock的spock-spring模块依赖添加到应用的构建中。spock-spring将Spring的测试框架集成到了Spock里。

注意你不能使用上述提到的@SpringApplicationConfiguration注解,因为[Spock找不到@ContextConfiguration元注解](https://code.google.com/p/spock/issues/detail?id=349)。为了绕过该限制,你应该直接使用@ContextConfiguration注解,并使用Spring Boot特定的上下文加载器来配置它。
```java
@ContextConfiguration(loader = SpringApplicationContextLoader.class)
class ExampleSpec extends Specification {
// ...
}
```
**注**:上面描述的注解在Spock中可以使用,比如,你可以使用@WebIntegrationTest注解你的Specification以满足测试需要。


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.ignaciorivas.moviezcity" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>Client</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" version="1" />

    <preference name="StatusBarOverlaysWebView" value="false" />
    <preference name="StatusBarBackgroundColor" value="#000000" />

    <preference name="DisallowOverscroll" value="true" />
    <preference name="Orientation" value="portrait" />
    <preference name="webviewbounce" value="false" />
    <preference name="KeyboardDisplayRequiresUserAction" value="false" />
    <preference name="permissions" value="none" />
    <preference name="target-device" value="universal" />
    <preference name="fullscreen" value="false" />
    <preference name="prerendered-icon" value="true" />
    <preference name="stay-in-webview" value="false" />
    <preference name="detect-data-types" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="disable-cursor" value="false" />
    <preference name="android-minSdkVersion" value="14" />
    <preference name="android-installLocation" value="auto" />
    <preference name="EnableViewportScale" value="false" />

    <access origin="*" />

    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />

    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>


text:
import React from 'react'

const style = {
  horizontal: {
    display: 'flex',
    flexDirection: 'row',
    height: '100%',
    flexGrow: 1
  },
  vertical: {
    display: 'flex',
    flexDirection: 'column',
    height: '100%',
    flexGrow: 1
  }
}

/**
 * A <Layout> component is a container for a variable number of
 * <Window> components which controls the type of layout imposed on
 * them.
 */
export default class Layout extends React.Component {

  render() {

    const windows = this.props.children

    if (!windows.length) return

    // single or split layout
    if (windows.length < 3) {
      return
{windows}

    }

    // tile layout
    const [first, ...rest] = windows
    return (

        {first}

          {rest}

    )
  }
}

Layout.propTypes = {
  children: React.PropTypes.node
}


text:
typedef struct page_header_s
{
  void	*next_page;
  int	next_idx;
} page_header_t;

// dynamoRIO now redefine PAGE_SIZE here it's just not define
// So if it does not exist just use the most common value of
// today page size
#ifndef PAGE_SIZE
#define PAGE_SIZE 4096
#endif

#define MAX_IDX_ACCESS (PAGE_SIZE - sizeof(page_header_t)) / sizeof(access_t)
#define MAX_IDX_ORIG (PAGE_SIZE - sizeof(page_header_t)) / sizeof(orig_t)
#define MAX_IDX_INSTR (PAGE_SIZE - sizeof(page_header_t))

typedef struct access_page_s
{
  page_header_t	header;
  access_t	accesses[MAX_IDX_ACCESS];
} access_page_t;

typedef struct orig_page_s
{
  page_header_t	header;
  orig_t	origs[MAX_IDX_ORIG];
} orig_page_t;

typedef struct instr_page_s
{
  page_header_t	header;
  char		instrs[MAX_IDX_INSTR];
} instr_page_t;

struct malloc_s;

void *alloc_instr(struct malloc_s *block, unsigned int size);
access_t *alloc_access(struct malloc_s *block);
void free_last_access(struct malloc_s *block);
orig_t *alloc_orig(struct malloc_s *block);
void free_last_orig(struct malloc_s *block);
void custom_free_pages(struct malloc_s *block);
#endif


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

/**
 * wx_vacation_card
 * wx_vacation_opportunity
 */
class AddWxVacationOpportunity extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('wx_vacation_opportunity', function(Blueprint $t) {
            $t->bigIncrements('id');
            $t->string('name', 64);
            $t->bigInteger('wx_casa_id')->unsigned()->references('wx_casa')->on('id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('wx_vacation_opportunity');
    }
}


text:
using System;

namespace Paladino.Models
{
    /// <summary>
	/// Client API for the page
	/// </summary>
	public interface IPage
    {
        /// <summary>
        /// Gets/sets the id.
        /// </summary>
        Guid Id { get; }

        /// <summary>
        /// Gets whether this is a draft.
        /// </summary>
        bool IsDraft { get; }

        /// <summary>
        /// Gets/sets the group needed to view the page.
        /// </summary>
        Guid GroupId { get; }

        /// <summary>
        /// Gets/sets the parent id.
        /// </summary>
        Guid ParentId { get; }

        /// <summary>
        /// Gets/sets the title.
        /// </summary>
        string Title { get; }

        /// <summary>
        /// Gets/sets the optional navigation title.
        /// </summary>
        string NavigationTitle { get; }

        /// <summary>
        /// Gets/sets the permalink.
        /// </summary>
        string Permalink { get; }

        /// <summary>
        /// Gets/sets the meta keywords.
        /// </summary>
        string Keywords { get; }

        /// <summary>
        /// Gets/sets the meta description.
        /// </summary>
        string Description { get; }

        /// <summary>
        /// Gets/sets the template name.
        /// </summary>
        string TemplateName { get; }

        /// <summary>
        /// Gets/sets the created date.
        /// </summary>
        DateTime Created { get; }

        /// <summary>
        /// Gets/sets the updated date.
        /// </summary>
        DateTime Updated { get; }

        /// <summary>
        /// Gets/sets the published date.
        /// </summary>
        DateTime Published { get; }

        /// <summary>
        /// Gets/sets the published date.
        /// </summary>
        DateTime LastPublished { get; }
    }
}


text:
require "rails_helper"

RSpec.describe AccountPriceGroupMembersController do
  let(:facility) { create(:facility) }

  describe "search_results" do
    # Ignore validation errors, e.g. number format
    before { allow(AccountValidator::ValidatorFactory).to receive(:instance).and_return(AccountValidator::ValidatorDefault.new) }

    let(:partial_account_number) { build(:nufs_account).account_number[0..-4] }
    let(:price_group) { create(:price_group, facility: facility) }
    let!(:global_account) { create(:nufs_account, :with_account_owner, account_number: "#{partial_account_number}234") }
    let!(:facility_purchase_order) { create(:purchase_order_account, :with_account_owner, account_number: "#{partial_account_number}894", facility: facility) }
    let!(:other_facility_purchase_order) { create(:purchase_order_account, :with_account_owner, account_number: "#{partial_account_number}542", facility: create(:facility)) }

    let(:user) { create(:user, :facility_administrator, facility: facility) }

    it "limits the results to global and the facility" do
      sign_in user

      get :search_results, params: { facility_id: facility.url_name, price_group_id: price_group.id, search_term: partial_account_number }
      expect(assigns[:accounts]).to contain_exactly(global_account, facility_purchase_order)
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<data xmlns="ns:workflow" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns:workflow resource:WorkflowData">
	<documentTypes xmlns="ns:workflow/DocumentType" xsi:schemaLocation="ns:workflow/DocumentType resource:DocumentType">
		<documentType>
			<name>KcComplianceMaintenanceDocument</name>
			<description>Parent of Compliance maintenance documents in KC</description>
			<label>KcComplianceMaintenanceDocument</label>
			<parent>KcMaintenanceDocument</parent>
			<routePaths>
				<routePath>
					<start name="Initiated" />
				</routePath>
			</routePaths>
			<routeNodes>
				<start name="Initiated">
					<activationType>P</activationType>
					<mandatoryRoute>false</mandatoryRoute>
					<finalApproval>false</finalApproval>
				</start>
			</routeNodes>
		</documentType>
	</documentTypes>
</data>


text:
<?php

namespace sndsgd\form\rule;

/**
 * Ensure a value is a number
 */
class NumericRule extends RuleAbstract
{
    /**
     * @inheritDoc
     */
    public function getDescription(): string
    {
        return _("numeric");
    }

    /**
     * @inheritDoc
     */
    public function getErrorMessage(): string
    {
        if ($this->errorMessage) {
            return $this->errorMessage;
        }
        return _("must be numeric");
    }

    /**
     * @inheritDoc
     */
    public function validate(
        &$value,
        \sndsgd\form\Validator $validator = null
    ): bool
    {
        if ($value === 0 || is_numeric($value)) {
            $value = floatval($value);
            return true;
        }
        return false;
    }
}


text:
//********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************

#ifndef FUML_SEMANTICS_ACTIVITIES_CENTRALBUFFERNODEACTIVATION_HPP
#define FUML_SEMANTICS_ACTIVITIES_CENTRALBUFFERNODEACTIVATION_HPP

#include <memory>
#include <string>
// forward declarations
template<class T> class Bag;

//*********************************
// generated Includes
#include <map> // used for Persistence
#include <vector> // used for Persistence
namespace persistence
{
	namespace interfaces
	{
		class XLoadHandler; // used for Persistence
		class XSaveHandler; // used for Persistence
	}
}

namespace fUML
{
	class fUMLFactory;
}

//Forward Declaration for used types
namespace fUML::Semantics::Activities
{
	class ActivityEdgeInstance;
	class ActivityNodeActivationGroup;
	class Token;
}
namespace uml
{
	class ActivityNode;
}

// namespace macro header include
#include "fUML/fUML.hpp"

// base class includes
#include "fUML/Semantics/Activities/ObjectNodeActivation.hpp"

//*********************************
namespace fUML::Semantics::Activities
{

	class FUML_API CentralBufferNodeActivation: virtual public ObjectNodeActivation
	{
		public:
 			CentralBufferNodeActivation(const CentralBufferNodeActivation &) {}

		protected:
			CentralBufferNodeActivation(){}

		public:
			virtual std::shared_ptr<ecore::EObject> copy() const = 0;

			//destructor
			virtual ~CentralBufferNodeActivation() {}

			//*********************************
			// Operations
			//*********************************
			virtual void fire(std::shared_ptr<Bag<fUML::Semantics::Activities::Token>> incomingTokens) = 0;

			//*********************************
			// Attribute Getters & Setters
			//*********************************

			//*********************************
			// Reference Getters & Setters
			//*********************************

			//*********************************
			// Union Reference Getters
			//*********************************

			//*********************************
			// Container Getter
			//*********************************
			virtual std::shared_ptr<ecore::EObject> eContainer() const = 0;

			//*********************************
			// Persistence Functions
			//*********************************
			virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) = 0;
			virtual void resolveReferences(const int featureID, std::vector<std::shared_ptr<ecore::EObject> > references) = 0;
			virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const = 0;

		protected:
			//*********************************
			// Attribute Members
			//*********************************

			//*********************************
			// Reference Members
			//*********************************
	};
}
#endif /* end of include guard: FUML_SEMANTICS_ACTIVITIES_CENTRALBUFFERNODEACTIVATION_HPP */


text:
var Guacamole = Guacamole || {};

/**
 * A writer which automatically writes to the given output stream with arbitrary
 * binary data, supplied as ArrayBuffers.
 *
 * @constructor
 * @param {Guacamole.OutputStream} stream The stream that data will be written
 *                                        to.
 */
Guacamole.ArrayBufferWriter = function(stream) {

    /**
     * Reference to this Guacamole.StringWriter.
     * @private
     */
    var guac_writer = this;

    // Simply call onack for acknowledgements
    stream.onack = function(status) {
        if (guac_writer.onack)
            guac_writer.onack(status);
    };

    /**
     * Encodes the given data as base64, sending it as a blob. The data must
     * be small enough to fit into a single blob instruction.
     *
     * @private
     * @param {Uint8Array} bytes The data to send.
     */
    function __send_blob(bytes) {

        var binary = "";

        // Produce binary string from bytes in buffer
        for (var i=0; i<bytes.byteLength; i++)
            binary += String.fromCharCode(bytes[i]);

        // Send as base64
        stream.sendBlob(window.btoa(binary));

    }

    /**
     * The maximum length of any blob sent by this Guacamole.ArrayBufferWriter,
     * in bytes. Data sent via
     * [sendData()]{@link Guacamole.ArrayBufferWriter#sendData} which exceeds
     * this length will be split into multiple blobs. As the Guacamole protocol
     * limits the maximum size of any instruction or instruction element to
     * 8192 bytes, and the contents of blobs will be base64-encoded, this value
     * should only be increased with extreme caution.
     *
     * @type {Number}
     * @default {@link Guacamole.ArrayBufferWriter.DEFAULT_BLOB_LENGTH}
     */
    this.blobLength = Guacamole.ArrayBufferWriter.DEFAULT_BLOB_LENGTH;

    /**
     * Sends the given data.
     *
     * @param {ArrayBuffer|TypedArray} data The data to send.
     */
    this.sendData = function(data) {

        var bytes = new Uint8Array(data);

        // If small enough to fit into single instruction, send as-is
        if (bytes.length <= guac_writer.blobLength)
            __send_blob(bytes);

        // Otherwise, send as multiple instructions
        else {
            for (var offset=0; offset<bytes.length; offset += guac_writer.blobLength)
                __send_blob(bytes.subarray(offset, offset + guac_writer.blobLength));
        }

    };

    /**
     * Signals that no further text will be sent, effectively closing the
     * stream.
     */
    this.sendEnd = function() {
        stream.sendEnd();
    };

    /**
     * Fired for received data, if acknowledged by the server.
     * @event
     * @param {Guacamole.Status} status The status of the operation.
     */
    this.onack = null;

};

/**
 * The default maximum blob length for new Guacamole.ArrayBufferWriter
 * instances.
 *
 * @constant
 * @type {Number}
 */
Guacamole.ArrayBufferWriter.DEFAULT_BLOB_LENGTH = 6048;


text:
Ruby wrapper for [AChecker Web Accessibility Checker](http://achecker.ca)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'achecker'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install achecker

## Usage

```ruby
   require 'achecker'

   # replace with the web service id provided for registered users of achecker.
   id = "222c0b31450b95b0e010f5f83d9c9683f95ca89a"
   checker = AChecker::Api.new(id)
   result = checker.check("https://example.com")
```

Optionally you can provide the achecker URL:

```ruby
   require 'achecker'

   # replace with the web service id provided for registered users of achecker.
   id = "222c0b31450b95b0e010f5f83d9c9683f95ca89a"
   checker = AChecker::Api.new(id, "https://achecker.ca/checkacc.php")
   result = checker.check("https://example.com")
```

## Contributing

1. Fork it ( https://github.com/rmagrin/achecker/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

## License

Copyright (c) 2014 Rafael Magrin

MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package org.jetbrains.plugins.scala.lang.psi.api.expr
package xml

trait ScXmlEndTag extends ScXmlPairedTag {
  def getOpeningTag: ScXmlStartTag = {
    if (getParent != null && getParent.getFirstChild.isInstanceOf[ScXmlStartTag]) {
      return getParent.getFirstChild.asInstanceOf[ScXmlStartTag]
    }
    null
  }

  override def getMatchedTag: ScXmlPairedTag = getOpeningTag
}


text:
module AttrDefaults
  module Initialize
    def initialize *args, &block
      defaults = class << self.class
        @attr_defaults
      end

      unless defaults.nil?
        defaults.each do |attrs,default|
          attrs.each do |attr|
            instance_variable_set :"@#{attr}", default.call
          end
        end
      end

      super *args, &block
    end
  end

  module_function

  def included klass
    klass.prepend Initialize

    class << klass
      [:attr, :attr_writer, :attr_reader, :attr_accessor].each do |method|
        define_method method do |*attrs, &block|
          super *attrs

          unless block.nil?
            defaults = class << self
              @attr_defaults ||= {}
            end

            defaults[attrs] = block
          end
        end
      end
    end
  end
end


text:
<?php

namespace DreamCommerce\ShopAppstoreLib\Resource;

use DreamCommerce\ShopAppstoreLib\Resource;
use DreamCommerce\ShopAppstoreLib\Exception;

/**
 * Resource ApplicationConfig
 *
 * @package DreamCommerce\ShopAppstoreLib\Resource
 * @link https://developers.shoper.pl/developers/api/resources/application-config
 */
class ApplicationConfig extends Resource
{
    /**
     * Shop URL - string
     */
    const CONFIG_SHOP_URL = 'shop_url';

    /**
     * Full shop name - string
     */
    const CONFIG_SHOP_NAME = 'shop_name';

    /**
     * Shop mail e-mail address - string
     */
    const CONFIG_SHOP_EMAIL = 'shop_email';

    /**
     * Company name - string
     */
    const CONFIG_SHOP_COMPANY_NAME = 'shop_company_name';

    /**
     * Shop phone number - string
     */
    const CONFIG_SHOP_PHONE = 'shop_phone';

    /**
     * Tax identifier - integer
     */
    const CONFIG_SHOP_TAX_ID = 'shop_tax_id';

    /**
     * Shop address line 1 - string
     */
    const CONFIG_SHOP_ADDRESS_1 = 'shop_address_1';

    /**
     * Shop address line 2 - string
     */
    const CONFIG_SHOP_ADDRESS_2 = 'shop_address_2';

    /**
     * Shop city - string
     */
    const CONFIG_SHOP_CITY = 'shop_city';

    /**
     * Shop postcode - string
     */
    const CONFIG_SHOP_ZIP_CODE = 'shop_zip_code';

    /**
     * Shop province - string
     */
    const CONFIG_SHOP_PROVINCE = 'shop_province';

    /**
     * Shop country code - string
     */
    const CONFIG_SHOP_COUNTRY = 'shop_country';

    /**
     * Shop trade - string
     */
    const CONFIG_SHOP_TRADE = 'shop_trade';

    /**
     * Shop trade code, available values:
     *  - children
     *  - books_and_multimedia
     *  - clothes
     *  - computers
     *  - delicatessen
     *  - gifts_and_accessories
     *  - health_and_beauty
     *  - hobby
     *  - home_and_garden
     *  - automotive
     *  - consumer_electronics
     *  - sport_and_travel
     *  - other
     */
    const CONFIG_SHOP_TRADE_CODE = 'shop_trade_code';

    /**
     * Company identification number - integer
     */
    const CONFIG_SHOP_REGON = 'shop_regon';

    /**
     * Is shop disabled - boolean
     */
    const CONFIG_SHOP_OFF = 'shop_off';

    /**
     * Shop full address - string
     */
    const CONFIG_SHOP_FULL_ADDRESS = 'shop_full_address';

    /**
     * Default tax value identifier - integer
     */
    const CONFIG_PRODUCT_DEFAULTS_TAX_ID = 'product_defaults_tax_id';

    /**
     * Default product code generating method, available values:
     *  - 1 - no method
     *  - 2 - following ID
     *  - 3 - random
     */
    const CONFIG_PRODUCT_DEFAULTS_CODE = 'product_defaults_code';

    /**
     * Default stock value - integer
     */
    const CONFIG_PRODUCT_DEFAULTS_STOCK = 'product_defaults_stock';

    /**
     * Default stock value warning level - integer
     */
    const CONFIG_PRODUCT_DEFAULTS_WARN_LEVEL = 'product_defaults_warn_level';

    /**
     * Default ordering factor value - integer
     */
    const CONFIG_PRODUCT_DEFAULTS_ORDER = 'product_defaults_order';

    /**
     * Is product active in default - boolean
     */
    const CONFIG_PRODUCT_DEFAULTS_ACTIVE = 'product_defaults_active';

    /**
     * Default product weight - float
     */
    const CONFIG_PRODUCT_DEFAULTS_WEIGHT = 'product_defaults_weight';

    /**
     * Default measurement unit identifier - integer
     */
    const CONFIG_PRODUCT_DEFAULTS_UNIT_ID = 'product_defaults_unit_id';

    /**
     * Default availability identifier - integer
     */
    const CONFIG_PRODUCT_DEFAULTS_AVAILABILITY_ID = 'product_defaults_availability_id';

    /**
     * Default product delivery identifier - integer
     */
    const CONFIG_PRODUCT_DEFAULTS_DELIVERY_ID = 'product_defaults_delivery_id';

    /**
     * Allow to set currency per product - boolean
     */
    const CONFIG_SHOPPING_ALLOW_PRODUCT_DIFFERENT_CURRENCY = 'shopping_allow_product_different_currency';

    /**
     * Defined price levels (1-3) - integer
     */
    const CONFIG_SHOPPING_PRICE_LEVELS = 'shopping_price_levels';

    /**
     * Save basket contents - boolean
     */
    const CONFIG_SHOPPING_SAVE_BASKET = 'shopping_save_basket';

    /**
     * Update stock values on buy - boolean
     */
    const CONFIG_SHOPPING_UPDATE_STOCK_ON_BUY = 'shopping_update_stock_on_buy';

    /**
     * Actions performed upon product adding, available values:
     *  - 1 - refresh page and do not redirect to the basket
     *  - 2 - refresh page and perform redirection to the basket
     *  - 3 - do not refresh page, show confirmation message
     */
    const CONFIG_SHOPPING_BASKET_ADDING = 'shopping_basket_adding';

    /**
     * Allow buying without registration - boolean
     */
    const CONFIG_SHOPPING_ALLOW_TO_BU_NOT_REG = 'shopping_allow_to_buy_not_reg';

    /**
     * Share order via link - boolean
     */
    const CONFIG_SHOPPING_ORDER_VIA_TOKEN = 'shopping_order_via_token';

    /**
     * Require order confirmation - boolean
     */
    const CONFIG_SHOPPING_CONFIRM_ORDER = 'shopping_confirm_order';

    /**
     * Minimal product quantity - float
     */
    const CONFIG_SHOPPING_MIN_PROD_QUANTITY = 'shopping_min_prod_quantity';

    /**
     * Minimal order value - float
     */
    const CONFIG_SHOPPING_MIN_ORDER_VALUE = 'shopping_min_order_value';

    /**
     * Disable shopping - boolean
     */
    const CONFIG_SHOPPING_OFF = 'shopping_off';

    /**
     * Allow to buy zero-priced products - boolean
     */
    const CONFIG_SHOPPING_PRODUCTS_ALLOW_ZERO = 'shopping_products_allow_zero';

    /**
     * Allow to sell more products than stock value - boolean
     */
    const CONFIG_SHOPPING_ALLOW_OVERSELLING = 'shopping_allow_overselling';

    /**
     * Order status after parcel is created - integer|null
     */
    const CONFIG_SHOPPING_PARCEL_CREATE_STATUS_ID = 'shopping_parcel_create_status_id';

    /**
     * Order status after parcel is sent - integer|null
     */
    const CONFIG_SHOPPING_PARCEL_SEND_STATUS_ID = 'shopping_parcel_send_status_id';

    /**
     * Order status after receiving payment - integer|null
     */
    const CONFIG_SHOPPING_CHANGE_STATUS_PAYMENT_MADE_ID = 'shopping_change_status_payment_made_id';

    /**
     * Order status after refund has been made - integer|null
     */
    const CONFIG_SHOPPING_CHANGE_STATUS_REFUND_MADE_ID = 'shopping_change_status_refund_made_id';

    /**
     * Show shipping and payment, available values:
     *  - 0 - show in basket
     *  - 1 - show as separated step
     */
    const CONFIG_SHOPPING_SHIPPING_EXTRA_STEP = 'shopping_shipping_extra_step';

    /**
     * Products marking as "new" mode, available values:
     *  - 0 - manual
     *  - 1 - automatic, based on product creation date
     */
    const CONFIG_SHOPPING_NEWPRODUCTS_MODE = 'shopping_newproducts_mode';

    /**
     * Automatic mode - number of days after product creation it will be marked as "new" - integer
     */
    const CONFIG_SHOPPING_NEWPRODUCTS_DAYS = 'shopping_newproducts_days';

    /**
     * Marking as "bestseller" mode:
     *  - 0 - manual
     *  - 1- automatic, based on users orders
     */
    const CONFIG_SHOPPING_BESTSELLER_MODE = 'shopping_bestseller_mode';

    /**
     * Only for automatic mode - days count when product is marked as bestseller, available values:
     *  - 7 - last 7 days
     *  - 30 - last 30 days
     *  - 90 - last 90 days
     *  - 0 - lifetime
     */
    const CONFIG_SHOPPING_BESTSELLER_DAYS = 'shopping_bestseller_days';

    /**
     * Bestseller calculation algorithm:
     *  - 1 - most orders count
     *  - 2 - most orders amount
     */
    const CONFIG_SHOPPING_BESTSELLER_ALGORITHM = 'shopping_bestseller_algorithm';

    /**
     * Field which products are identified by - for price comparison websites, available values:
     *  - code - product code
     *  - additional_isbn - ISBN code
     *  - additional_kgo - KGO price
     *  - additional_bloz7 - BLOZ7 code
     *  - additional_bloz12 - BLOZ12 code
     */
    const CONFIG_SHOPPING_PRICE_COMPARISON_FIELD = 'shopping_price_comparison_field';

    const CONFIG_SHOPPING_PROMO_CODES_ENABLE = 'shopping_promo_codes_enable';

    /**
     * Notify on product availabilities - boolean
     */
    const CONFIG_PRODUCT_NOTIFIES_ENABLE = 'product_notifies_enable';

    /**
     * Enable user registration - boolean
     */
    const CONFIG_REGISTRATION_ENABLE = 'registration_enable';

    /**
     * Require registration confirmation - boolean
     */
    const CONFIG_REGISTRATION_CONFIRM = 'registration_confirm';

    /**
     * Only signed in users see price - boolean
     */
    const CONFIG_REGISTRATION_LOGIN_TO_SEE_PRICE = 'registration_login_to_see_price';

    /**
     * New users address requirements:
     *  - 0 - only email address and password
     *  - 1 - full address details
     */
    const CONFIG_REGISTRATION_REQUIRE_ADDRESS = 'registration_require_address';

    /**
     * Force payment price addition even if free shipping is present - boolean
     */
    const CONFIG_SHIPPING_ADD_PAYMENT_COST_TO_FREE_SHIPPING = 'shipping_add_payment_cost_to_free_shipping';

    /**
     * Enable volumetric weight - boolean
     */
    const CONFIG_SHIPPING_VOLUMETRIC_WEIGHT_ENABLE = 'shipping_volumetric_weight_enable';

    /**
     * Product search mode:
     *  - 1 - only in product name
     *  - 2 - in product name and other details
     */
    const CONFIG_PRODUCT_SEARCH_TYPE = 'product_search_type';

    /**
     * Only for product name search - require exact phrase
     */
    const CONFIG_PRODUCT_SEARCH_ALL_TOKENS = 'product_search_all_tokens';

    /**
     * Only for product details search - include product code
     */
    const CONFIG_PRODUCT_SEARCH_CODE = 'product_search_code';

    /**
     * Only for product details search - include product short description
     */
    const CONFIG_PRODUCT_SEARCH_SHORT_DESCRIPTION = 'product_search_short_description';

    /**
     * Only for product details search - include product description - boolean
     */
    const CONFIG_PRODUCT_SEARCH_DESCRIPTION = 'product_search_description';

    /**
     * Status identifier which sends email with files - integer
     */
    const CONFIG_DIGITAL_PRODUCT_UNLOCKING_STATUS_ID = 'digital_product_unlocking_status_id';

    /**
     * Product link expiration time (days) - integer
     */
    const CONFIG_DIGITAL_PRODUCT_LINK_EXPIRATION_TIME = 'digital_product_link_expiration_time';

    /**
     * Maximum downloads number per user - integer
     */
    const CONFIG_DIGITAL_PRODUCT_NUMBER_OF_DOWNLOADS = 'digital_product_number_of_downloads';

    /**
     * Enable product comments - boolean
     */
    const CONFIG_COMMENT_ENABLE = 'comment_enable';

    /**
     * Only registered users are allowed to post comments - boolean
     */
    const CONFIG_COMMENT_FOR_USERS = 'comment_for_users';

    /**
     * Is comments moderation enabled - boolean
     */
    const CONFIG_COMMENT_MODERATION = 'comment_moderation';

    /**
     * Is loyalty program enabled - boolean
     */
    const CONFIG_LOYALTY_ENABLE = 'loyalty_enable';

    /**
     * Blog items per page count
     */
    const CONFIG_BLOG_ITEMS_PER_PAGE = 'blog_items_per_page';

    /**
     * Enable blog comments
     */
    const CONFIG_BLOG_COMMENTS_ENABLE = 'blog_comments_enable';

    /**
     * Only registered users are allowed to post blog comments
     */
    const CONFIG_BLOG_COMMENTS_FOR_USERS = 'blog_comments_for_users';

    /**
     * Is blog comments moderation enabled - boolean
     */
    const CONFIG_BLOG_COMMENTS_MODERATION = 'blog_comments_moderation';

    /**
     * Allow to download blog attached files - boolean
     */
    const CONFIG_BLOG_DOWNLOAD_FOR_USERS = 'blog_download_for_users';

    /**
     * Default URL schema for blog, available values:
     *  - 1 - /:lang/(n|blog)/:newsId
     *  - 2 - /:lang/(n|blog)/:newsName/:newsId
     *  - 3 - /:lang/(n|blog)/:newsYear/:newsName/:newsId
     *  - 4 - /:lang/(n|blog)/:newsYear/:newsMonth/:newsName/:newsId
     *  - 5 - /:lang/(n|blog)/:newsYear/:newsMonth/:newsDay/:newsName/:newsId
     */
    const CONFIG_BLOG_NEWS_DEFAULT_URL_FORMAT = 'blog_news_default_url_format';

    /**
     * Default blog category URL format, available values:
     *  - 1 - /:lang/(n|blog)/category/:categoryId
     *  - 2 - /:lang/(n|blog)/category/:categoryName/:categoryId
     */
    const CONFIG_BLOG_CATEGORY_DEFAULT_URL_FORMAT = 'blog_category_default_url_format';

    /**
     * Use new blog URL namespace, available values:
     *  - 0 - /:lang/n/*
     *  - 1 - /:lang/blog/*
     */
    const CONFIG_BLOG_USE_NEW_URL_NAMESPACE = 'blog_use_new_url_namespace';

    /**
     * Shop timezone (eg. "Europe/Warsaw") - string
     */
    const CONFIG_LOCALE_TIMEZONE = 'locale_timezone';

    /**
     * Shop weight unit:
     *  - KILOGRAM
     *  - GRAM
     *  - LBS
     */
    const CONFIG_LOCALE_DEFAULT_WEIGHT = 'locale_default_weight';

    /**
     * Default shop language name - language_REGION format (eg. "pl_PL") - string
     */
    const CONFIG_DEFAULT_LANGUAGE_NAME = 'default_language_name';

    /**
     * Default shop language identifier - integer
     */
    const CONFIG_DEFAULT_LANGUAGE_ID = 'default_language_id';

    /**
     * Default currency name - ISO 4217 ("PLN") - string
     */
    const CONFIG_DEFAULT_CURRENCY_NAME = 'default_currency_name';

    /**
     * Default currency identifier - integer
     */
    const CONFIG_DEFAULT_CURRENCY_ID = 'default_currency_id';

    protected $isSingleOnly = true;
    protected $name = 'application-config';
}


text:
package cz.cuni.mff.d3s.spl.demo.sandbox.priorities.adjust;

import java.util.Map;

public abstract class Adjust implements Runnable {
	protected volatile boolean terminate;
	protected Map<Thread, Long> startTimes;

	public void shutdown() {
		terminate = true;
	}

	public void init(Map<Thread, Long> st) {
		startTimes = st;
	}

	public void requestComplete(Thread currentThread) {
	}

	protected void sleep(long millis) {
		if (millis <= 0) {
			return;
		}

		try {
			Thread.sleep(millis, 0);
		} catch (InterruptedException e) {
		}
	}
}


text:
import chess.pgn
import sys

def ParseGames(fn):
    f = file(fn, 'r')
    while True:
        game = chess.pgn.read_game(f)
        if game is None:
            break
        else:
            yield game

def Positions(game):
    node = game
    ar = []
    while node.variations:
        ar.append(node)
        next_node = node.variation(0)
        node = next_node
    ar.append(node)
    return ar

for fn in sys.argv[1:]:
    for game in ParseGames(fn):
        for ply, node in enumerate(Positions(game)):
            print ply, node.board().fen()


text:
package org.apache.isis.viewer.html.context;

import java.util.List;

import org.apache.isis.applib.Identifier;
import org.apache.isis.applib.annotation.ActionSemantics;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.applib.filter.Filter;
import org.apache.isis.core.commons.authentication.AuthenticationSession;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.consent.Allow;
import org.apache.isis.core.metamodel.consent.Consent;
import org.apache.isis.core.metamodel.consent.InteractionInvocationMethod;
import org.apache.isis.core.metamodel.facetapi.Facet;
import org.apache.isis.core.metamodel.facetapi.FeatureType;
import org.apache.isis.core.metamodel.facetapi.MultiTypedFacet;
import org.apache.isis.core.metamodel.interactions.ActionInvocationContext;
import org.apache.isis.core.metamodel.interactions.UsabilityContext;
import org.apache.isis.core.metamodel.interactions.VisibilityContext;
import org.apache.isis.core.metamodel.runtimecontext.RuntimeContext;
import org.apache.isis.core.metamodel.spec.ActionType;
import org.apache.isis.core.metamodel.spec.Instance;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
import org.apache.isis.core.metamodel.spec.feature.ObjectActionParameter;

/**
 * Has no functionality but makes it easier to write tests that require an
 * instance of an {@link Identifier}.
 *
 * <p>
 * Was previously DummyAction, in the web viewer project. Only used by tests
 * there.
 */
public class ObjectActionNoop implements ObjectAction {

    public boolean[] canParametersWrap() {
        return null;
    }

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

    @Override
    public ObjectAdapter execute(final ObjectAdapter target, final ObjectAdapter[] parameters) {
        return null;
    }

    @Override
    public List<ObjectAction> getActions() {
        return null;
    }

    @Override
    public ObjectAdapter[] getDefaults(final ObjectAdapter target) {
        return null;
    }

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

    @Override
    public boolean containsFacet(final Class<? extends Facet> facetType) {
        return false;
    }

    @Override
    public boolean containsDoOpFacet(final Class<? extends Facet> facetType) {
        return false;
    }

    @Override
    public <T extends Facet> T getFacet(final Class<T> cls) {
        return null;
    }

    @Override
    public Class<? extends Facet>[] getFacetTypes() {
        return new Class[0];
    }

    @Override
    public List<Facet> getFacets(final Filter<Facet> filter) {
        return null;
    }

    @Override
    public void addFacet(final Facet facet) {
    }

    @Override
    public void addFacet(final MultiTypedFacet facet) {
    }

    @Override
    public void removeFacet(final Facet facet) {
    }

    @Override
    public void removeFacet(final Class<? extends Facet> facetType) {
    }

    @Override
    public Identifier getIdentifier() {
        return null;
    }

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

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

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

    @Override
    public ObjectSpecification getOnType() {
        return null;
    }

    @Override
    public ObjectAdapter[][] getChoices(final ObjectAdapter target) {
        return null;
    }

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

    @Override
    public List<ObjectActionParameter> getParameters() {
        return null;
    }

    @Override
    public List<ObjectActionParameter> getParameters(final Filter<ObjectActionParameter> filter) {
        return null;
    }

    @Override
    public ObjectActionParameter getParameterById(final String paramId) {
        return null;
    }

    @Override
    public ObjectActionParameter getParameterByName(final String paramName) {
        return null;
    }

    @Override
    public ObjectSpecification getReturnType() {
        return null;
    }

    @Override
    public ActionType getType() {
        return null;
    }

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

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

    @Override
    public boolean promptForParameters(final ObjectAdapter target) {
        return false;
    }

    @Override
    public VisibilityContext<?> createVisibleInteractionContext(final AuthenticationSession session, final InteractionInvocationMethod invocationMethod, final ObjectAdapter targetObjectAdapter, Where where) {
        return null;
    }

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

    @Override
    public Consent isVisible(final AuthenticationSession session, final ObjectAdapter target, Where where) {
        return Allow.DEFAULT;
    }

    @Override
    public Consent isUsable(final AuthenticationSession session, final ObjectAdapter target, Where where) {
        return Allow.DEFAULT;
    }

    @Override
    public Consent isProposedArgumentSetValid(final ObjectAdapter object, final ObjectAdapter[] parameters) {
        return Allow.DEFAULT;
    }

    @Override
    public ObjectAdapter realTarget(final ObjectAdapter target) {
        return target;
    }

    @Override
    public ObjectSpecification getSpecification() {
        return null;
    }

    @Override
    public UsabilityContext<?> createUsableInteractionContext(final AuthenticationSession session, final InteractionInvocationMethod invocationMethod, final ObjectAdapter target, Where where) {
        return null;
    }

    @Override
    public ActionInvocationContext createActionInvocationInteractionContext(final AuthenticationSession session, final InteractionInvocationMethod invocationMethod, final ObjectAdapter object, final ObjectAdapter[] candidateArguments) {
        return null;
    }

    // /////////////////////////////////////////////////////////////
    // isAction, isAssociation
    // /////////////////////////////////////////////////////////////

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

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

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

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

    // /////////////////////////////////////////////////////////////
    // getInstance
    // /////////////////////////////////////////////////////////////

    @Override
    public Instance getInstance(final ObjectAdapter adapter) {
        final ObjectAction specification = this;
        return adapter.getInstance(specification);
    }

    @Override
    public List<ObjectSpecification> getParameterTypes() {
        return null;
    }

    public RuntimeContext getRuntimeContext() {
        // TODO Auto-generated method stub
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.apache.isis.core.metamodel.spec.feature.ObjectFeature#getFeatureType
     * ()
     */
    @Override
    public FeatureType getFeatureType() {
        return FeatureType.ACTION;
    }

    @Override
    public ActionSemantics.Of getSemantics() {
        return ActionSemantics.Of.NON_IDEMPOTENT;
    }

}


text:
#ifndef HARFBUZZ_GSUB_H
#define HARFBUZZ_GSUB_H

#include "harfbuzz-gdef.h"
#include "harfbuzz-buffer.h"

HB_BEGIN_HEADER

/* Lookup types for glyph substitution */

#define HB_GSUB_LOOKUP_SINGLE        1
#define HB_GSUB_LOOKUP_MULTIPLE      2
#define HB_GSUB_LOOKUP_ALTERNATE     3
#define HB_GSUB_LOOKUP_LIGATURE      4
#define HB_GSUB_LOOKUP_CONTEXT       5
#define HB_GSUB_LOOKUP_CHAIN         6
#define HB_GSUB_LOOKUP_EXTENSION     7
#define HB_GSUB_LOOKUP_REVERSE_CHAIN 8

/* A pointer to a function which selects the alternate glyph.  `pos' is
   the position of the glyph with index `glyphID', `num_alternates'
   gives the number of alternates in the `alternates' array.  `data'
   points to the user-defined structure specified during a call to
   HB_GSUB_Register_Alternate_Function().  The function must return an
   index into the `alternates' array.                                   */

typedef HB_UShort  (*HB_AltFunction)(HB_UInt    pos,
				      HB_UShort   glyphID,
				      HB_UShort   num_alternates,
				      HB_UShort*  alternates,
				      void*       data );

struct  HB_GSUBHeader_
{
  HB_GDEFHeader*  gdef;

  /* the next two fields are used for an alternate substitution callback
     function to select the proper alternate glyph.                      */

  void*            data;
  HB_AltFunction  altfunc;

  HB_UInt         offset;

  HB_16Dot16         Version;

  HB_ScriptList   ScriptList;
  HB_FeatureList  FeatureList;
  HB_LookupList   LookupList;
};

typedef struct HB_GSUBHeader_   HB_GSUBHeader;
typedef HB_GSUBHeader*  HB_GSUB;

HB_Error  HB_Load_GSUB_Table( HB_Stream       stream,
			      HB_GSUBHeader** gsub,
			      HB_GDEFHeader*  gdef,
                              HB_Stream       gdefStream );

HB_Error  HB_Done_GSUB_Table( HB_GSUBHeader*  gsub );

HB_Error  HB_GSUB_Select_Script( HB_GSUBHeader*  gsub,
				 HB_UInt         script_tag,
				 HB_UShort*       script_index );

HB_Error  HB_GSUB_Select_Language( HB_GSUBHeader*  gsub,
				   HB_UInt         language_tag,
				   HB_UShort        script_index,
				   HB_UShort*       language_index,
				   HB_UShort*       req_feature_index );

HB_Error  HB_GSUB_Select_Feature( HB_GSUBHeader*  gsub,
				  HB_UInt         feature_tag,
				  HB_UShort        script_index,
				  HB_UShort        language_index,
				  HB_UShort*       feature_index );

HB_Error  HB_GSUB_Query_Scripts( HB_GSUBHeader*  gsub,
				 HB_UInt**       script_tag_list );

HB_Error  HB_GSUB_Query_Languages( HB_GSUBHeader*  gsub,
				   HB_UShort        script_index,
				   HB_UInt**       language_tag_list );

HB_Error  HB_GSUB_Query_Features( HB_GSUBHeader*  gsub,
				  HB_UShort        script_index,
				  HB_UShort        language_index,
				  HB_UInt**       feature_tag_list );

HB_Error  HB_GSUB_Add_Feature( HB_GSUBHeader*  gsub,
			       HB_UShort        feature_index,
			       HB_UInt          property );

HB_Error  HB_GSUB_Clear_Features( HB_GSUBHeader*  gsub );

HB_Error  HB_GSUB_Register_Alternate_Function( HB_GSUBHeader*  gsub,
					       HB_AltFunction  altfunc,
					       void*            data );

HB_Error  HB_GSUB_Apply_String( HB_GSUBHeader*   gsub,
				HB_Buffer        buffer );

HB_END_HEADER

#endif /* HARFBUZZ_GSUB_H */


text:
require "cgi"
require "secure_headers/utils/cookies_config"

module SecureHeaders
  class CookiesConfigError < StandardError; end
  class Cookie

    class << self
      def validate_config!(config)
        CookiesConfig.new(config).validate!
      end
    end

    attr_reader :raw_cookie, :config

    COOKIE_DEFAULTS = {
      httponly: true,
      secure: true,
      samesite: { lax: true },
    }.freeze

    def initialize(cookie, config)
      @raw_cookie = cookie
      unless config == OPT_OUT
        config ||= {}
        config = COOKIE_DEFAULTS.merge(config)
      end
      @config = config
      @attributes = {
        httponly: nil,
        samesite: nil,
        secure: nil,
      }

      parse(cookie)
    end

    def to_s
      @raw_cookie.dup.tap do |c|
        c << "; secure" if secure?
        c << "; HttpOnly" if httponly?
        c << "; #{samesite_cookie}" if samesite?
      end
    end

    def secure?
      flag_cookie?(:secure) && !already_flagged?(:secure)
    end

    def httponly?
      flag_cookie?(:httponly) && !already_flagged?(:httponly)
    end

    def samesite?
      flag_samesite? && !already_flagged?(:samesite)
    end

    private

    def parsed_cookie
      @parsed_cookie ||= CGI::Cookie.parse(raw_cookie)
    end

    def already_flagged?(attribute)
      @attributes[attribute]
    end

    def flag_cookie?(attribute)
      return false if config == OPT_OUT
      case config[attribute]
      when TrueClass
        true
      when Hash
        conditionally_flag?(config[attribute])
      else
        false
      end
    end

    def conditionally_flag?(configuration)
      if(Array(configuration[:only]).any? && (Array(configuration[:only]) & parsed_cookie.keys).any?)
        true
      elsif(Array(configuration[:except]).any? && (Array(configuration[:except]) & parsed_cookie.keys).none?)
        true
      else
        false
      end
    end

    def samesite_cookie
      if flag_samesite_lax?
        "SameSite=Lax"
      elsif flag_samesite_strict?
        "SameSite=Strict"
      elsif flag_samesite_none?
        "SameSite=None"
      end
    end

    def flag_samesite?
      return false if config == OPT_OUT || config[:samesite] == OPT_OUT
      flag_samesite_lax? || flag_samesite_strict? || flag_samesite_none?
    end

    def flag_samesite_lax?
      flag_samesite_enforcement?(:lax)
    end

    def flag_samesite_strict?
      flag_samesite_enforcement?(:strict)
    end

    def flag_samesite_none?
      flag_samesite_enforcement?(:none)
    end

    def flag_samesite_enforcement?(mode)
      return unless config[:samesite]

      if config[:samesite].is_a?(TrueClass) && mode == :lax
        return true
      end

      case config[:samesite][mode]
      when Hash
        conditionally_flag?(config[:samesite][mode])
      when TrueClass
        true
      else
        false
      end
    end

    def parse(cookie)
      return unless cookie

      cookie.split(/[;,]\s?/).each do |pairs|
        name, values = pairs.split("=", 2)
        name = CGI.unescape(name)

        attribute = name.downcase.to_sym
        if @attributes.has_key?(attribute)
          @attributes[attribute] = values || true
        end
      end
    end
  end
end


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project (OpenNebula.org), C12G Labs        */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

#include "Quotas.h"
#include "Nebula.h"

#include "ObjectXML.h"

int Quotas::set(Template *tmpl, string& error)
{
    vector<Attribute *> vquotas;

    if ( tmpl->get(datastore_quota.get_quota_name(), vquotas) > 0 )
    {
        if ( datastore_quota.set(&vquotas, error) != 0 )
        {
            return -1;
        }

        vquotas.clear();
    }

    if ( tmpl->get(network_quota.get_quota_name(), vquotas) > 0 )
    {
        if ( network_quota.set(&vquotas, error) != 0 )
        {
            return -1;
        }

        vquotas.clear();
    }

    if ( tmpl->get(image_quota.get_quota_name(), vquotas) > 0 )
    {
        if ( image_quota.set(&vquotas, error) != 0 )
        {
            return -1;
        }

        vquotas.clear();
    }

    if ( tmpl->get(vm_quota.get_quota_name(), vquotas) > 0 )
    {
        if ( vm_quota.set(&vquotas, error) != 0 )
        {
            return -1;
        }

        vquotas.clear();
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& Quotas::to_xml(string& xml) const
{
    ostringstream oss;

    string ds_quota_xml;
    string net_quota_xml;
    string vm_quota_xml;
    string image_quota_xml;

    oss << datastore_quota.to_xml(ds_quota_xml)
        << network_quota.to_xml(net_quota_xml)
        << vm_quota.to_xml(vm_quota_xml)
        << image_quota.to_xml(image_quota_xml);

    xml = oss.str();

    return xml;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int Quotas::from_xml(ObjectXML * object_xml)
{
    vector<xmlNodePtr> content;
    int                rc = 0;

    object_xml->get_nodes(ds_xpath, content);

    if (!content.empty())
    {
        rc += datastore_quota.from_xml_node(content[0]);
    }

    object_xml->free_nodes(content);
    content.clear();

    object_xml->get_nodes(net_xpath, content);

    if (!content.empty())
    {
        rc += network_quota.from_xml_node(content[0]);
    }

    object_xml->free_nodes(content);
    content.clear();

    object_xml->get_nodes(vm_xpath, content);

    if (!content.empty())
    {
        rc += vm_quota.from_xml_node(content[0]);
    }

    object_xml->free_nodes(content);
    content.clear();

    object_xml->get_nodes(img_xpath, content);

    if (!content.empty())
    {
        rc += image_quota.from_xml_node(content[0]);
    }

    object_xml->free_nodes(content);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void Quotas::quota_del(QuotaType type, Template *tmpl)
{
    switch (type)
    {
        case DATASTORE:
            datastore_quota.del(tmpl);
        break;

        case NETWORK:
            network_quota.del(tmpl);
        break;

        case IMAGE:
            image_quota.del(tmpl);
        break;

        case VM:
            vm_quota.del(tmpl);
        break;

        case VIRTUALMACHINE:
            network_quota.del(tmpl);
            vm_quota.del(tmpl);
            image_quota.del(tmpl);
        break;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

bool Quotas::quota_check(QuotaType  type,
                        Template    *tmpl,
                        Quotas      &default_quotas,
                        string      &error_str)
{
    switch (type)
    {
        case DATASTORE:
            return datastore_quota.check(tmpl, default_quotas, error_str);

        case NETWORK:
            return network_quota.check(tmpl, default_quotas, error_str);

        case IMAGE:
            return image_quota.check(tmpl, default_quotas, error_str);

        case VM:
            return vm_quota.check(tmpl, default_quotas, error_str);

        case VIRTUALMACHINE:
            if ( network_quota.check(tmpl, default_quotas, error_str) == false )
            {
                return false;
            }

            if ( vm_quota.check(tmpl, default_quotas, error_str) == false )
            {
                network_quota.del(tmpl);
                return false;
            }

            if ( image_quota.check(tmpl, default_quotas, error_str) == false )
            {
                network_quota.del(tmpl);
                vm_quota.del(tmpl);
                return false;
            }

            return true;
    }

    return false;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

bool Quotas::quota_update(QuotaType  type,
                          Template    *tmpl,
                          Quotas      &default_quotas,
                          string      &error_str)
{
    switch (type)
    {
        // This is an internal check, should never get in here.
        case DATASTORE:
        case NETWORK:
        case IMAGE:
        case VIRTUALMACHINE:
            error_str = "Cannot update quota. Not implemented";
            return false;

        case VM:
            return vm_quota.update(tmpl, default_quotas, error_str);
    }

    return false;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void Quotas::quota_del(QuotaType type, int uid, int gid, Template * tmpl)
{
    Nebula&     nd    = Nebula::instance();
    UserPool *  upool = nd.get_upool();
    GroupPool * gpool = nd.get_gpool();

    User *  user;
    Group * group;

    if ( uid != UserPool::ONEADMIN_ID )
    {
        user = upool->get(uid, true);

        if ( user != 0 )
        {
            user->quota.quota_del(type, tmpl);

            upool->update_quotas(user);

            user->unlock();
        }
    }

    if ( gid != GroupPool::ONEADMIN_ID )
    {
        group = gpool->get(gid, true);

        if ( group != 0 )
        {
            group->quota.quota_del(type, tmpl);

            gpool->update_quotas(group);

            group->unlock();
        }
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;

/**
 * The name of the metric and its n-dimensional position. Basically a pair of a
 * Point and a metric name. Written to be robust against null input as the API
 * gives very little guidance, converting null to empty string/point.  Immutable.
 *
 * @author Steinar Knutsen
 */
public class Identifier {

    private final String name;
    private final Point location;
    private final int hashCode;

    public Identifier(String name, Point location) {
        this.name = (name == null ? "" : name);
        this.location = (location == null ? Point.emptyPoint() : location);
        this.hashCode = this.location.hashCode() * 31 + this.name.hashCode();
    }

    @Override
    public int hashCode() {
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;

        Identifier other = (Identifier) obj;
        return location.equals(other.location) && name.equals(other.name);
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Identifier [name=").append(name).append(", location=").append(location).append("]");
        return builder.toString();
    }

    public String getName() {
        return name;
    }

    public Point getLocation() {
        return location;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CheckBox_Sample">
        <attr name="size" format="dimension" />
        <attr name="color_border" format="color" />
        <attr name="color_background" format="color" />
    </declare-styleable>
</resources>


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class GrupoAlimentar extends Model
{
    protected $table = 'grupoAlimentar';
    protected $primaryKey = 'idGAlimentar';
    public $timestamps = false;
}


text:
package com.dancingqueen.walladog.aws.downloader.query;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;

/**
 * A class which implements a content provider that gives access to
 * the download queue. Note that we only support querying. Updates,
 * deletes, inserts must all happen by firing intents at the download
 * service.
 */
public class DownloadQueueProvider extends ContentProvider {
    /** The authority for download content provider. */
    private static String authority = null;

    /**
     * Gets the authority for the download queue content provider.
     * @param context a context
     * @return the authority for the download queue content provider.
     */
    public static synchronized String getAuthority(final Context context) {
        if (authority == null) {
            authority = "com.amazonaws.mobile.downloader-" + context.getPackageName();
        }
        return authority;
    }

    /** The base path for download content provider's content Uri. */
    public static final String BASE_PATH = "Downloads";

    public static final String OPEN_TRANSACTION_PATH = "Downloads/StartTransaction";
    public static final String COMPLETE_TRANSACTION_PATH = "Downloads/CompleteTransaction";

    /** The download content Uri. */
    private static Uri downloadContentUri = null;
    private static Uri downloadOpenTransactionUri = null;
    private static Uri downloadCompleteTransactionUri = null;

    /**
     * Gets the uri for the download queue content provider.
     * @param context a context
     * @return the uri for the download queue content provider.
     */
    public static synchronized Uri getDownloadContentUri(final Context context) {
        if (downloadContentUri == null) {
            downloadContentUri = Uri.parse("content://" + getAuthority(context) + "/" + BASE_PATH);
        }
        return downloadContentUri;
    }

    public static synchronized Uri getDownloadOpenTransactionUri(final Context context) {
        if (downloadOpenTransactionUri == null) {
            downloadOpenTransactionUri = Uri.parse("content://" + getAuthority(context) + "/" + OPEN_TRANSACTION_PATH);
        }
        return downloadOpenTransactionUri;
    }

    public static synchronized Uri getDownloadCompleteTransactionUri(final Context context) {
        if (downloadCompleteTransactionUri == null) {
            downloadCompleteTransactionUri = Uri.parse("content://" + getAuthority(context) + "/" + COMPLETE_TRANSACTION_PATH);
        }
        return downloadCompleteTransactionUri;
    }

    /** Our MIME type for single rows. */
    public static final String ROW_MIME_TYPE =
        "vnd.android.cursor.item/vnd.com.amazonaws.mobile.downloader." + BASE_PATH;

    /** Our MIME type for sets of rows. */
    public static final String TABLE_MIME_TYPE =
        "vnd.android.cursor.dir/vnd.com.amazonaws.mobile.downloader." + BASE_PATH;

    /** The table name. */
    public static final String TABLE_NAME = "download_queue";

    /** The column containing download id. */
    public static final String COLUMN_DOWNLOAD_ID = "_id";

    /** The column containing the download file location. */
    public static final String COLUMN_DOWNLOAD_FILE_LOCATION = "fileLocation";

    /** The column containing the download description. */
    public static final String COLUMN_DOWNLOAD_DESCRIPTION = "description";

    /** The column containing the download Uri. */
    public static final String COLUMN_DOWNLOAD_URL = "url";

    /** The column containing the user interaction flags. */
    public static final String COLUMN_DOWNLOAD_USER_FLAGS = "userFlags";

    /** The column containing the MIME type. */
    public static final String COLUMN_DOWNLOAD_MIME_TYPE = "mimeType";

    /** The column containing the serialized intent passed in. */
    public static final String COLUMN_DOWNLOAD_INTENT_URI = "intentURI";

    /** The column containing the eTag. */
    public static final String COLUMN_DOWNLOAD_ETAG = "eTag";

    /** The column containing the status enum. */
    public static final String COLUMN_DOWNLOAD_STATUS = "status";

    /** The column containing the size of the thing being downloaded. */
    public static final String COLUMN_DOWNLOAD_TOTAL_SIZE = "size";

    /** The column containing the amount downloaded so far. */
    public static final String COLUMN_DOWNLOAD_CURRENT_SIZE = "bytesDownloaded";

    /** The column containing the pause/fail reason. */
    public static final String COLUMN_DOWNLOAD_STOP_REASON = "stoppedBecause";

    /** The column containing the timestamp of when the status was last modified (in milliseconds). */
    public static final String COLUMN_DOWNLOAD_CREATE_TIMESTAMP = "createTimestamp";

    /** The column containing the download title. */
    public static final String COLUMN_DOWNLOAD_TITLE = "title";

    /** An instance of our helper class used to access the DB. */
    private DatabaseHelper helper;

    /**
     * Called when a the content provider is created by the Android system.
     *
     * @return true if initialization successful
     */
    @Override
    public boolean onCreate() {
        helper = new DatabaseHelper(getContext());
        return true;
    }

    /**
     * Called to make a query to the content provider.
     *
     * @param uri
     *            the URI to query
     * @param projection
     *            the columns desired in the output
     * @param selection
     *            the "where" clause to use
     * @param selectionArgs
     *            variables to insert into the ? in the "where" clause
     * @param sortOrder
     *            the "order by" clause
     * @return the cursor with the results in it
     */
    @Override
    public Cursor query(final Uri uri, final String[] projection,
                        final String selection, final String[] selectionArgs, final String sortOrder) {
        if (uri.equals(downloadContentUri)) {
            final SQLiteDatabase db = helper.getReadableDatabase();
            return db.query(TABLE_NAME, projection, selection, selectionArgs,
                null, null, sortOrder, null);
        }
        final SQLiteDatabase db = helper.getWritableDatabase();

        if (uri.equals(downloadOpenTransactionUri)) {
            db.beginTransaction();
        } else if (uri.equals(downloadCompleteTransactionUri)) {
            db.setTransactionSuccessful();
            db.endTransaction();
        }
        return null;
    }

    /**
     * Called to insert an item.
     *
     * @param uri
     *            the URI to insert to
     * @param values
     *            the values to insert.
     * @return the URI for the new row
     */
    @Override
    public Uri insert(final Uri uri, final ContentValues values) {
        final SQLiteDatabase db = helper.getWritableDatabase();
        final long id = db.insert(TABLE_NAME, null, values);
        return ContentUris.withAppendedId(uri, id);
    }

    /**
     * Called to update an item.
     *
     * @param uri
     *            the URI to update
     * @param values
     *            the values to change
     * @param selection
     *            the "where" clause
     * @param selectionArgs
     *            the variables to be inserted into the ? of the "where" clause
     * @return the count of rows changed
     */
    @Override
    public int update(final Uri uri, final ContentValues values,
                      final String selection, final String[] selectionArgs) {
        final SQLiteDatabase db = helper.getWritableDatabase();
        return db.update(TABLE_NAME, values, selection, selectionArgs);
    }

    /**
     * Delete an item.
     *
     * @param uri
     *            the URI to update
     * @param selection
     *            the "where" clause
     * @param selectionArgs
     *            the variables to be inserted into the ? of the "where" clause
     * @return the count of rows deleted.
     */
    @Override
    public int delete(final Uri uri, final String selection, final String[] selectionArgs) {
        final SQLiteDatabase db = helper.getWritableDatabase();
        return db.delete(TABLE_NAME, selection, selectionArgs);
    }

    /**
     * Get the mime type of this content.
     *
     * @param uri
     *            the URI to query
     * @return the mime type
     */
    @Override
    public String getType(final Uri uri) {
        final String result;
        final String query = uri.getQuery();
        if (query.startsWith("id=")) {
            result = ROW_MIME_TYPE;
        } else {
            result = TABLE_MIME_TYPE;
        }
        return result;
    }

    /**
     * A class to help us manage our SQLite database.
     */
    /* package */static final class DatabaseHelper extends SQLiteOpenHelper {

        /** Log Tag. */
        private static final String LOG_TAG = DatabaseHelper.class.getSimpleName();

        /** Current database version. */
        private static final int VERSION = 1;

        /** Database name. */
        private static final String NAME = "downloadQueue";

        /** SQL to create table. */
        public static final String CREATE_TABLE = "CREATE TABLE "
            + DownloadQueueProvider.TABLE_NAME
            + "("
            + DownloadQueueProvider.COLUMN_DOWNLOAD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_URL + " TEXT, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_FILE_LOCATION + " TEXT, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_DESCRIPTION + " TEXT, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_USER_FLAGS + " INTEGER, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_MIME_TYPE + " TEXT, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_INTENT_URI + " TEXT, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_ETAG + " TEXT, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_STATUS + " TEXT, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_TOTAL_SIZE + " INTEGER, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_CURRENT_SIZE + " INTEGER, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_STOP_REASON + " TEXT, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_CREATE_TIMESTAMP + " INTEGER, "
            + DownloadQueueProvider.COLUMN_DOWNLOAD_TITLE + " TEXT "
            + ")";

        /**
         * Create a new instance.
         *
         * @param context
         *            the Context to be used.
         */
        /* package */DatabaseHelper(final Context context) {
            super(context, NAME, null, VERSION);
        }

        /**
         * Create a database schema.
         *
         * @param db
         *            the database in which to create the schema.
         */
        @Override
        public void onCreate(final SQLiteDatabase db) {
            try {
                db.execSQL(CREATE_TABLE);
            } catch (SQLiteException e) {
                Log.e(LOG_TAG, "Error trying to create table", e);
            }
        }

        /**
         * Upgrade a database schema.
         *
         * @param db
         *            the database to upgrade.
         * @param oldVersion
         *            the current version
         * @param newVersion
         *            the version to upgrade to.
         */
        @Override
        public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
            Log.i(LOG_TAG, "upgrading db from v" + oldVersion + " to v" + newVersion);

            // No versions yet except version 1.
        }
    }
}