text:
require 'spec_helper'

describe Puppet::Type.type(:dsc_xadorganizationalunit) do

  let :dsc_xadorganizationalunit do
    Puppet::Type.type(:dsc_xadorganizationalunit).new(
      :name     => 'foo',
      :dsc_name => 'foo',
      :dsc_path => 'foo',
    )
  end

  it 'should allow all properties to be specified' do
    expect { Puppet::Type.type(:dsc_xadorganizationalunit).new(
      :name     => 'foo',
      :dsc_name => 'foo',
      :dsc_path => 'foo',
      :dsc_ensure => 'Present',
      :dsc_credential => {"user"=>"user", "password"=>"password"},
      :dsc_protectedfromaccidentaldeletion => true,
      :dsc_description => 'foo',
    )}.to_not raise_error
  end

  it "should stringify normally" do
    expect(dsc_xadorganizationalunit.to_s).to eq("Dsc_xadorganizationalunit[foo]")
  end

  it 'should default to ensure => present' do
    expect(dsc_xadorganizationalunit[:ensure]).to eq :present
  end

  it 'should require that dsc_name is specified' do
    #dsc_xadorganizationalunit[:dsc_name]
    expect { Puppet::Type.type(:dsc_xadorganizationalunit).new(
      :name     => 'foo',
      :dsc_path => 'foo',
    )}.to raise_error(Puppet::Error, /dsc_name is a required attribute/)
  end

  it 'should not accept array for dsc_name' do
    expect{dsc_xadorganizationalunit[:dsc_name] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_name' do
    expect{dsc_xadorganizationalunit[:dsc_name] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_name' do
    expect{dsc_xadorganizationalunit[:dsc_name] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_name' do
    expect{dsc_xadorganizationalunit[:dsc_name] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should require that dsc_path is specified' do
    #dsc_xadorganizationalunit[:dsc_path]
    expect { Puppet::Type.type(:dsc_xadorganizationalunit).new(
      :name     => 'foo',
      :dsc_name => 'foo',
    )}.to raise_error(Puppet::Error, /dsc_path is a required attribute/)
  end

  it 'should not accept array for dsc_path' do
    expect{dsc_xadorganizationalunit[:dsc_path] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_path' do
    expect{dsc_xadorganizationalunit[:dsc_path] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_path' do
    expect{dsc_xadorganizationalunit[:dsc_path] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_path' do
    expect{dsc_xadorganizationalunit[:dsc_path] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept dsc_ensure predefined value Present' do
    dsc_xadorganizationalunit[:dsc_ensure] = 'Present'
    expect(dsc_xadorganizationalunit[:dsc_ensure]).to eq('Present')
  end

  it 'should accept dsc_ensure predefined value present' do
    dsc_xadorganizationalunit[:dsc_ensure] = 'present'
    expect(dsc_xadorganizationalunit[:dsc_ensure]).to eq('present')
  end

  it 'should accept dsc_ensure predefined value present and update ensure with this value (ensure end value should be a symbol)' do
    dsc_xadorganizationalunit[:dsc_ensure] = 'present'
    expect(dsc_xadorganizationalunit[:ensure]).to eq(dsc_xadorganizationalunit[:dsc_ensure].downcase.to_sym)
  end

  it 'should accept dsc_ensure predefined value Absent' do
    dsc_xadorganizationalunit[:dsc_ensure] = 'Absent'
    expect(dsc_xadorganizationalunit[:dsc_ensure]).to eq('Absent')
  end

  it 'should accept dsc_ensure predefined value absent' do
    dsc_xadorganizationalunit[:dsc_ensure] = 'absent'
    expect(dsc_xadorganizationalunit[:dsc_ensure]).to eq('absent')
  end

  it 'should accept dsc_ensure predefined value absent and update ensure with this value (ensure end value should be a symbol)' do
    dsc_xadorganizationalunit[:dsc_ensure] = 'absent'
    expect(dsc_xadorganizationalunit[:ensure]).to eq(dsc_xadorganizationalunit[:dsc_ensure].downcase.to_sym)
  end

  it 'should not accept values not equal to predefined values' do
    expect{dsc_xadorganizationalunit[:dsc_ensure] = 'invalid value'}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_ensure' do
    expect{dsc_xadorganizationalunit[:dsc_ensure] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_ensure' do
    expect{dsc_xadorganizationalunit[:dsc_ensure] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_ensure' do
    expect{dsc_xadorganizationalunit[:dsc_ensure] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_ensure' do
    expect{dsc_xadorganizationalunit[:dsc_ensure] = 16}.to raise_error(Puppet::ResourceError)
  end

  it "should not accept empty password for dsc_credential" do
    expect{dsc_xadorganizationalunit[:dsc_credential] = {"user"=>"user", "password"=>""}}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_credential' do
    expect{dsc_xadorganizationalunit[:dsc_credential] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_credential' do
    expect{dsc_xadorganizationalunit[:dsc_credential] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_credential' do
    expect{dsc_xadorganizationalunit[:dsc_credential] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_credential' do
    expect{dsc_xadorganizationalunit[:dsc_credential] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_protectedfromaccidentaldeletion' do
    expect{dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept boolean for dsc_protectedfromaccidentaldeletion' do
    dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = true
    expect(dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion]).to eq(true)
  end

  it "should accept boolean-like value 'true' and munge this value to boolean for dsc_protectedfromaccidentaldeletion" do
    dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = 'true'
    expect(dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion]).to eq(true)
  end

  it "should accept boolean-like value 'false' and munge this value to boolean for dsc_protectedfromaccidentaldeletion" do
    dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = 'false'
    expect(dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion]).to eq(false)
  end

  it "should accept boolean-like value 'True' and munge this value to boolean for dsc_protectedfromaccidentaldeletion" do
    dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = 'True'
    expect(dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion]).to eq(true)
  end

  it "should accept boolean-like value 'False' and munge this value to boolean for dsc_protectedfromaccidentaldeletion" do
    dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = 'False'
    expect(dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion]).to eq(false)
  end

  it "should accept boolean-like value :true and munge this value to boolean for dsc_protectedfromaccidentaldeletion" do
    dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = :true
    expect(dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion]).to eq(true)
  end

  it "should accept boolean-like value :false and munge this value to boolean for dsc_protectedfromaccidentaldeletion" do
    dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = :false
    expect(dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion]).to eq(false)
  end

  it 'should not accept int for dsc_protectedfromaccidentaldeletion' do
    expect{dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_protectedfromaccidentaldeletion' do
    expect{dsc_xadorganizationalunit[:dsc_protectedfromaccidentaldeletion] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_description' do
    expect{dsc_xadorganizationalunit[:dsc_description] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_description' do
    expect{dsc_xadorganizationalunit[:dsc_description] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_description' do
    expect{dsc_xadorganizationalunit[:dsc_description] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_description' do
    expect{dsc_xadorganizationalunit[:dsc_description] = 16}.to raise_error(Puppet::ResourceError)
  end

  # Configuration PROVIDER TESTS

  describe "powershell provider tests" do

    it "should successfully instanciate the provider" do
      described_class.provider(:powershell).new(dsc_xadorganizationalunit)
    end

    before(:each) do
      @provider = described_class.provider(:powershell).new(dsc_xadorganizationalunit)
    end

    describe "when dscmeta_module_name existing/is defined " do

      it "should compute powershell dsc test script with Invoke-DscResource" do
        expect(@provider.ps_script_content('test')).to match(/Invoke-DscResource/)
      end

      it "should compute powershell dsc test script with method Test" do
        expect(@provider.ps_script_content('test')).to match(/Method\s+=\s*'test'/)
      end

      it "should compute powershell dsc set script with Invoke-DscResource" do
        expect(@provider.ps_script_content('set')).to match(/Invoke-DscResource/)
      end

      it "should compute powershell dsc test script with method Set" do
        expect(@provider.ps_script_content('set')).to match(/Method\s+=\s*'set'/)
      end

    end

    describe "when dsc_ensure is 'present'" do

      before(:each) do
        dsc_xadorganizationalunit.original_parameters[:dsc_ensure] = 'present'
        dsc_xadorganizationalunit[:dsc_ensure] = 'present'
        @provider = described_class.provider(:powershell).new(dsc_xadorganizationalunit)
      end

      it "should update :ensure to :present" do
        expect(dsc_xadorganizationalunit[:ensure]).to eq(:present)
      end

      it "should compute powershell dsc test script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/)
      end

      it "should compute powershell dsc set script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('set')).to match(/ensure = 'present'/)
      end

    end

    describe "when dsc_ensure is 'absent'" do

      before(:each) do
        dsc_xadorganizationalunit.original_parameters[:dsc_ensure] = 'absent'
        dsc_xadorganizationalunit[:dsc_ensure] = 'absent'
        @provider = described_class.provider(:powershell).new(dsc_xadorganizationalunit)
      end

      it "should update :ensure to :absent" do
        expect(dsc_xadorganizationalunit[:ensure]).to eq(:absent)
      end

      it "should compute powershell dsc test script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/)
      end

      it "should compute powershell dsc set script in which ensure value is 'absent'" do
        expect(@provider.ps_script_content('set')).to match(/ensure = 'absent'/)
      end

    end

    describe "when dsc_resource has credentials" do

      it "should convert credential hash to a pscredential object" do
        expect(@provider.ps_script_content('test')).to match(/| new-pscredential'/)
      end

    end

  end
end


text:
class LaraSerializationHelper

  def initialize
    @entries = {}
  end

  def export(item)
    results = item.export
    results[:type] = item.class.name
    results[:ref_id] = key(item)
    if item.respond_to?(:interactive) && item.interactive
      results[:interactive_ref_id] = key(item.interactive)
    end
    if item.respond_to?(:embeddable) && item.embeddable
      results[:embeddable_ref_id] = key(item.embeddable)
    end
    if item.respond_to?(:linked_interactive) && item.linked_interactive
      # Why is linked interactive fully serialized while other linked items use reference only?
      # Not sure. It might be related to the fact, that linked interactives can be linked across multiple pages
      # or even activities. However, it doesn't seem it would work if we export and import activity with this
      # interactive missing. I guess it could be double checked and fixed in the future.
      results[:linked_interactive] = self.export(item.linked_interactive)
    end

    # This is done here and not in the models as we don't want to export the linked embeddables as they are already exported
    # we only want to save the key so that the references to the embeddables can be restored during import.
    # The embeddedable references are saved instead of the page_item references as new page_items are created when the
    # embeddables are imported into the page.
    if item.respond_to?(:primary_linked_items)
      results[:linked_interactives] = item.primary_linked_items.map {|pli| {
        ref_id: key(pli.secondary.embeddable),
        label: pli.label
      }}
    end
    results
  end

  def import(item_hash)
    existing_item = lookup_item(item_hash[:ref_id])
    return existing_item if existing_item

    item = item_hash[:type].constantize.import(item_hash.except(:type, :ref_id, :interactive_ref_id, :embeddable_ref_id, :linked_interactive, :linked_interactives))
    item.save!(validate: false)
    unless item_hash[:ref_id]
      # This is only for backward compatibility when not all the embeddables were defining ref_id in export hash.
      item_hash[:ref_id] = key(item)
    end
    cache_item(item_hash[:ref_id], item)
    item
  end

  def set_references(item_hash)
    item = lookup_item(item_hash[:ref_id])
    if item_hash[:interactive_ref_id] && item.respond_to?(:interactive=)
      item.interactive = lookup_item(item_hash[:interactive_ref_id])
    end
    if item_hash[:embeddable_ref_id] && item.respond_to?(:embeddable=)
      item.embeddable = lookup_item(item_hash[:embeddable_ref_id])
    end
    if item_hash[:linked_interactive] && item.respond_to?(:linked_interactive)
      item.linked_interactive = import(item_hash[:linked_interactive])
    end
    if item_hash[:linked_interactives]
      item_hash[:linked_interactives].each do |lpi_hash|
        secondary = lookup_item(lpi_hash[:ref_id])
        if secondary
          lpi = LinkedPageItem.new(primary_id: item.page_item.id, secondary_id: secondary.page_item.id, label: lpi_hash[:label])
          lpi.save!(validate: false)
        end
      end
    end
    item.save!(validate: false)
    item
  end

  def key(item)
    "#{item.id}-#{item.class.name}"
  end

  private

  def cache_item(ref_id, item)
    @entries[ref_id] = item
  end

  def lookup_item(key_sting)
    @entries[key_sting]
  end
end

redpajama_set_name: RedPajamaGithub


text:
import {QueryParameter} from './query-parameter.model';
import {DisplayableField} from './displayable-field.model';

export interface ReportRequest {
  queryParameters: QueryParameter[];
  displayableFields: DisplayableField[];
}


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

namespace PHPUnit\Framework;

use function array_keys;
use function get_class;
use function spl_object_hash;
use PHPUnit\Util\Filter;
use Throwable;

/**
 * Wraps Exceptions thrown by code under test.
 *
 * Re-instantiates Exceptions thrown by user-space code to retain their original
 * class names, properties, and stack traces (but without arguments).
 *
 * Unlike PHPUnit\Framework_\Exception, the complete stack of previous Exceptions
 * is processed.
 *
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ExceptionWrapper extends Exception
{
    /**
     * @var string
     */
    protected $className;

    /**
     * @var null|ExceptionWrapper
     */
    protected $previous;

    public function __construct(Throwable $t)
    {
        // PDOException::getCode() is a string.
        // @see https://php.net/manual/en/class.pdoexception.php#95812
        parent::__construct($t->getMessage(), (int) $t->getCode());
        $this->setOriginalException($t);
    }

    public function __toString(): string
    {
        $string = TestFailure::exceptionToString($this);

        if ($trace = Filter::getFilteredStacktrace($this)) {
            $string .= "\n" . $trace;
        }

        if ($this->previous) {
            $string .= "\nCaused by\n" . $this->previous;
        }

        return $string;
    }

    public function getClassName(): string
    {
        return $this->className;
    }

    public function getPreviousWrapped(): ?self
    {
        return $this->previous;
    }

    public function setClassName(string $className): void
    {
        $this->className = $className;
    }

    public function setOriginalException(Throwable $t): void
    {
        $this->originalException($t);

        $this->className = get_class($t);
        $this->file      = $t->getFile();
        $this->line      = $t->getLine();

        $this->serializableTrace = $t->getTrace();

        foreach (array_keys($this->serializableTrace) as $key) {
            unset($this->serializableTrace[$key]['args']);
        }

        if ($t->getPrevious()) {
            $this->previous = new self($t->getPrevious());
        }
    }

    public function getOriginalException(): ?Throwable
    {
        return $this->originalException();
    }

    /**
     * Method to contain static originalException to exclude it from stacktrace to prevent the stacktrace contents,
     * which can be quite big, from being garbage-collected, thus blocking memory until shutdown.
     *
     * Approach works both for var_dump() and var_export() and print_r().
     */
    private function originalException(Throwable $exceptionToStore = null): ?Throwable
    {
        static $originalExceptions;

        $instanceId = spl_object_hash($this);

        if ($exceptionToStore) {
            $originalExceptions[$instanceId] = $exceptionToStore;
        }

        return $originalExceptions[$instanceId] ?? null;
    }
}


text:
package org.spongepowered.common.data.provider.entity;

import com.google.common.collect.ImmutableList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.projectile.FireworkRocketEntity;
import net.minecraft.world.item.ItemStack;
import org.spongepowered.api.data.Keys;
import org.spongepowered.common.accessor.world.entity.EntityAccessor;
import org.spongepowered.common.accessor.world.entity.projectile.FireworkRocketEntityAccessor;
import org.spongepowered.common.data.provider.DataProviderRegistrator;
import org.spongepowered.common.util.Constants;
import org.spongepowered.common.util.FireworkUtil;
import org.spongepowered.common.util.SpongeTicks;

public final class FireworkRocketData {

    private FireworkRocketData() {
    }

    // @formatter:off
    public static void register(final DataProviderRegistrator registrator) {
        registrator
                .asMutable(FireworkRocketEntity.class)
                    .create(Keys.FIREWORK_EFFECTS)
                        .get(h -> FireworkUtil.getFireworkEffects(h).orElse(null))
                        .set(FireworkUtil::setFireworkEffects)
                        .resetOnDelete(ImmutableList.of())
                    .create(Keys.FIREWORK_FLIGHT_MODIFIER)
                        .get(h -> {
                            final ItemStack item = FireworkUtil.getItem(h);
                            final CompoundTag fireworks = item.getOrCreateTagElement(Constants.Item.Fireworks.FIREWORKS);
                            if (fireworks.contains(Constants.Item.Fireworks.FLIGHT)) {
                                return new SpongeTicks(fireworks.getByte(Constants.Item.Fireworks.FLIGHT));
                            }
                            return null;
                        })
                        .setAnd((h, v) -> {
                            final int ticks = (int) v.ticks();
                            if (ticks < 0 || ticks > Byte.MAX_VALUE) {
                                return false;
                            }
                            final ItemStack item = FireworkUtil.getItem(h);
                            final CompoundTag fireworks = item.getOrCreateTagElement(Constants.Item.Fireworks.FIREWORKS);
                            fireworks.putByte(Constants.Item.Fireworks.FLIGHT, (byte) ticks);
                            ((FireworkRocketEntityAccessor) h).accessor$lifetime(10 * ticks + ((EntityAccessor) h).accessor$random().nextInt(6) + ((EntityAccessor) h).accessor$random().nextInt(7));
                            return true;
                        });
    }
    // @formatter:on
}


text:
package ca

import (
	"github.com/prometheus/client_golang/prometheus"
)

const (
	errorlabel = "error"
)

var (
	csrCounts = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "citadel",
		Subsystem: "server",
		Name:      "csr_count",
		Help:      "The number of CSRs recerived by Citadel server.",
	}, []string{})

	authnErrorCounts = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "citadel",
		Subsystem: "server",
		Name:      "authentication_failure_count",
		Help:      "The number of authentication failures.",
	}, []string{})

	csrParsingErrorCounts = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "citadel",
		Subsystem: "server",
		Name:      "csr_parsing_err_count",
		Help:      "The number of erorrs occurred when parsing the CSR.",
	}, []string{})

	idExtractionErrorCounts = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "citadel",
		Subsystem: "server",
		Name:      "id_extraction_err_count",
		Help:      "The number of errors occurred when extracting the ID from CSR.",
	}, []string{})

	certSignErrorCounts = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "citadel",
		Subsystem: "server",
		Name:      "csr_sign_err_count",
		Help:      "The number of erorrs occurred when signing the CSR.",
	}, []string{errorlabel})

	successCounts = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "citadel",
		Subsystem: "server",
		Name:      "success_cert_issuance_count",
		Help:      "The number of certificates issuances that have succeeded.",
	}, []string{})
)

func init() {
	prometheus.MustRegister(csrCounts)
	prometheus.MustRegister(authnErrorCounts)
	prometheus.MustRegister(csrParsingErrorCounts)
	prometheus.MustRegister(idExtractionErrorCounts)
	prometheus.MustRegister(certSignErrorCounts)
	prometheus.MustRegister(successCounts)
}

// monitoringMetrics are counters for certificate signing related operations.
type monitoringMetrics struct {
	CSR               prometheus.Counter
	AuthnError        prometheus.Counter
	Success           prometheus.Counter
	CSRError          prometheus.Counter
	IDExtractionError prometheus.Counter
	certSignErrors    *prometheus.CounterVec
}

// newMonitoringMetrics creates a new monitoringMetrics.
func newMonitoringMetrics() monitoringMetrics {
	return monitoringMetrics{
		CSR:               csrCounts.With(prometheus.Labels{}),
		AuthnError:        authnErrorCounts.With(prometheus.Labels{}),
		Success:           successCounts.With(prometheus.Labels{}),
		CSRError:          csrParsingErrorCounts.With(prometheus.Labels{}),
		IDExtractionError: idExtractionErrorCounts.With(prometheus.Labels{}),
		certSignErrors:    certSignErrorCounts,
	}
}

func (m *monitoringMetrics) GetCertSignError(err string) prometheus.Counter {
	return m.certSignErrors.With(prometheus.Labels{errorlabel: err})
}


text:
<?php

namespace Thumbtack\Crankshaft;

/**
 * Internal: Used to implement repeat().
 */
class BoundedRepeatValueGenerator extends RepeatValueGenerator implements \Countable {
    private $position;
    private $count;

    public function __construct($value, $count) {
        parent::__construct($value);
        $this->count = $count;
    }

    public function count() {
        return $this->count;
    }

    protected function setup() {
        parent::setup();

        $this->position = 0;
    }

    protected function advance() {
        if ($this->position < $this->count) {
            $this->position++;
            return parent::advance();
        } else {
            throw new GeneratorExhausted();
        }
    }
}


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Controllers;
using Microsoft.Its.Domain.Serialization;

namespace Microsoft.Its.Domain.Api.Serialization
{
    [DebuggerStepThrough]
    internal class ServesJsonByDefaultAttribute : Attribute, IControllerConfiguration
    {
        public void Initialize(HttpControllerSettings settings, HttpControllerDescriptor descriptor)
        {
            foreach (var formatter in settings.Formatters.OfType<JsonMediaTypeFormatter>())
            {
                formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
                formatter.SerializerSettings = Serializer.Settings;
            }
        }
    }
}


text:
import { Box } from "@artsy/palette"
import { MockRelayRenderer } from "v2/DevTools"
import React from "react"
import { storiesOf } from "storybook/storiesOf"

import { Section } from "v2/Utils/Section"
import { RequestConditionReportFragmentContainer } from "../RequestConditionReport"

// TODO: Extract network creation/masking from MockRelayRenderer
//
// Context
//
// When multiple stories re-use the same GraphQL query, only the first to render
// receives properly un-masked data. The others pull from a global react-relay
// query cache without the same un-masking logic defined.
//
// This means that it's not safe to have multiple query renderers on the same
// storybook page.
//
// We should investigate re-using the same network across instances of
// MockRelayRenderer. One way might be extract the network creation and allow it
// to be passed in as a MockRelayRenderer prop.
//
// #dev-help thread: https://artsy.slack.com/archives/CP9P4KR35/p1579881138013100
import {
  FailureQuery,
  SuccessQuery,
  UnauthenticatedQuery,
} from "./RequestConditionReportQueries"

const MockRequestConditionReport = ({ query, me, conditionReportRequest }) => {
  return (
    <MockRelayRenderer
      Component={RequestConditionReportFragmentContainer}
      mockData={{
        me,
        artwork: { saleArtwork: { internalID: "sale-artwork-id" } },
      }}
      mockMutationResults={{
        requestConditionReport: { conditionReportRequest },
      }}
      variables={{ artworkID: "artwork-id" }}
      query={query}
    />
  )
}

storiesOf("Apps/Artwork/Components/ArtistDetails", module).add(
  "RequestConditionReport",
  () => {
    return (
      <>

          <Box width="100%">
            <MockRequestConditionReport
              me={{ internalID: "id", email: "user@example.com" }}
              conditionReportRequest={{ internalID: "id" }}
              query={SuccessQuery}
            />
          </Box>

          <Box width="100%">
            <MockRequestConditionReport
              me={{ internalID: "id", email: "user@example.com" }}
              conditionReportRequest={null}
              query={FailureQuery}
            />
          </Box>

          <Box width="100%">
            <MockRequestConditionReport
              me={null}
              conditionReportRequest={null}
              query={UnauthenticatedQuery}
            />
          </Box>

      </>
    )
  }
)


text:
using System;
using System.Collections.Generic;
using TMAPIv4;

namespace TMAPISample
{
	class MainClass
	{
		/// <summary>
		/// Run a series of TaguchiMail API tests.
		/// </summary>
		public static void Main()
		{
			Dictionary<string, string>	connectionParams = new Dictionary<string, string>() {
				{"host", ""},
				{"organization_id", ""},
				{"username", ""},
				{"password", ""}
			};
			Console.WriteLine("Connecting to " + connectionParams["host"] + "...");

			Context ctx = new Context(connectionParams["host"], connectionParams["username"],
			                          connectionParams["password"], connectionParams["organization_id"]);

			// Look for an existing subscriber record, and make some changes
			Console.WriteLine("Running lookup test...");
			Subscriber s = Subscriber.Find(ctx, "id", "asc", 0, 1, new string[1] {"email-eq-" + connectionParams["username"]})[0];
			Console.WriteLine("Found subscriber ID " + s.RecordId + "; name " + s.FirstName + " " + s.LastName);

			string newLastName = s.LastName + "Lorem";
			Console.WriteLine("Changing subscriber ID " +s.RecordId + " last name from '" + s.LastName + "'");

			s.LastName = newLastName;
			s.Update();

			Console.WriteLine("Subscriber ID " + s.RecordId + " last name now '" + s.LastName + '"');

			Console.WriteLine("Toggling subscriber ID " +s.RecordId + " subscription list ID 123");
			if (s.IsSubscribedToList("123"))
			{
				Console.WriteLine("Unsubscribing...");
				s.UnsubscribeFromList("123");
			}
			else
			{
				Console.WriteLine("Subscribing...");
				s.SubscribeToList("123", "example");
			}

			s.Update();

			Console.WriteLine("Subscriber ID " + s.RecordId + " now subscribed to " + s.GetSubscribedLists().Length.ToString() + " lists");

			// Create some new subscriber records, and add to a list.
			Console.WriteLine("Running create test...");
			Random rand = new Random();
			for (int i = 0; i < 100; i++)
			{
				Subscriber s2 = new Subscriber(ctx);
				int idx = rand.Next(1000);
				s2.FirstName = "Subscriber" + idx.ToString();
				s2.LastName = "Test";
				s2.Email = "edmtest+" + idx.ToString() + "@mail.taguchimail.com";
				s2.SubscribeToList(idx % 2 == 0 ? "123" : "124", null);
				s2.CreateOrUpdate();
				Console.WriteLine("Created subscriber " + s2.Email + " with ID " + s2.RecordId);
			}

			// Retrieve subscribers from the lists
			SubscriberList[] allLists = SubscriberList.Find(ctx, "id", "asc", 0, 100, null);
			foreach (SubscriberList sl in allLists)
			{
				Console.WriteLine("Dumping list " + sl.Name + " (ID " + sl.RecordId + ")");
				Subscriber[] subscribers = sl.GetSubscribers(0, 1000);
				foreach (Subscriber sub in subscribers)
				{
					Console.WriteLine("    Subscriber " + sub.Email + " width ID " + sub.RecordId + " is " + (sub.IsSubscribedToList(sl) ? "subscribed" : "unsubscribed"));
				}
			}

			// Send an email to a subscriber
			string customContent = @"<purchase>
  <product href='http://example.com/1234'>
    <name>Example Product</name>
    <price>123.45</price>
    <sku>XYZ1234ABC</sku>
  </product>
  <transaction>
    <name>Ms Example User</name>
    <phone>03 9123 4567</phone>
    <date>Monday, 22 November 2010</date>
    <time>6:30 PM</time>
    <confirmation-number>ABC123</confirmation-number>
  </transaction>
</purchase>";
			Activity purchaseConfirmation = Activity.Get(ctx, "123", null);
			Console.WriteLine("Sending activity " + purchaseConfirmation.Name + " to " + s.Email);
			purchaseConfirmation.Trigger(s, customContent, false);
			Console.WriteLine("Sent");
		}
	}
}


text:
#include <dlib/python.h>
#include "testing_results.h"
#include <boost/shared_ptr.hpp>
#include <boost/python/args.hpp>
#include <dlib/svm.h>

using namespace dlib;
using namespace std;
using namespace boost::python;

typedef matrix<double,0,1> sample_type;
typedef std::vector<std::pair<unsigned long,double> > sparse_vect;

template <typename decision_function>
double predict (
    const decision_function& df,
    const typename decision_function::kernel_type::sample_type& samp
)
{
    typedef typename decision_function::kernel_type::sample_type T;
    if (df.basis_vectors.size() == 0)
    {
        return 0;
    }
    else if (is_matrix<T>::value && df.basis_vectors(0).size() != samp.size())
    {
        std::ostringstream sout;
        sout << "Input vector should have " << df.basis_vectors(0).size()
             << " dimensions, not " << samp.size() << ".";
        PyErr_SetString( PyExc_ValueError, sout.str().c_str() );
        boost::python::throw_error_already_set();
    }
    return df(samp);
}

template <typename kernel_type>
void add_df (
    const std::string name
)
{
    typedef decision_function<kernel_type> df_type;
    class_<df_type>(name.c_str())
        .def("__call__", &predict<df_type>)
        .def_pickle(serialize_pickle<df_type>());
}

template <typename df_type>
typename df_type::sample_type get_weights(
    const df_type& df
)
{
    if (df.basis_vectors.size() == 0)
    {
        PyErr_SetString( PyExc_ValueError, "Decision function is empty." );
        boost::python::throw_error_already_set();
    }
    df_type temp = simplify_linear_decision_function(df);
    return temp.basis_vectors(0);
}

template <typename df_type>
typename df_type::scalar_type get_bias(
    const df_type& df
)
{
    if (df.basis_vectors.size() == 0)
    {
        PyErr_SetString( PyExc_ValueError, "Decision function is empty." );
        boost::python::throw_error_already_set();
    }
    return df.b;
}

template <typename df_type>
void set_bias(
    df_type& df,
    double b
)
{
    if (df.basis_vectors.size() == 0)
    {
        PyErr_SetString( PyExc_ValueError, "Decision function is empty." );
        boost::python::throw_error_already_set();
    }
    df.b = b;
}

template <typename kernel_type>
void add_linear_df (
    const std::string name
)
{
    typedef decision_function<kernel_type> df_type;
    class_<df_type>(name.c_str())
        .def("__call__", predict<df_type>)
        .add_property("weights", &get_weights<df_type>)
        .add_property("bias", get_bias<df_type>, set_bias<df_type>)
        .def_pickle(serialize_pickle<df_type>());
}

// ----------------------------------------------------------------------------------------

std::string binary_test__str__(const binary_test& item)
{
    std::ostringstream sout;
    sout << "class1_accuracy: "<< item.class1_accuracy << "  class2_accuracy: "<< item.class2_accuracy;
    return sout.str();
}
std::string binary_test__repr__(const binary_test& item) { return "< " + binary_test__str__(item) + " >";}

std::string regression_test__str__(const regression_test& item)
{
    std::ostringstream sout;
    sout << "mean_squared_error: "<< item.mean_squared_error << "  R_squared: "<< item.R_squared;
    return sout.str();
}
std::string regression_test__repr__(const regression_test& item) { return "< " + regression_test__str__(item) + " >";}

std::string ranking_test__str__(const ranking_test& item)
{
    std::ostringstream sout;
    sout << "ranking_accuracy: "<< item.ranking_accuracy << "  mean_ap: "<< item.mean_ap;
    return sout.str();
}
std::string ranking_test__repr__(const ranking_test& item) { return "< " + ranking_test__str__(item) + " >";}

// ----------------------------------------------------------------------------------------

template <typename K>
binary_test  _test_binary_decision_function (
    const decision_function<K>& dec_funct,
    const std::vector<typename K::sample_type>& x_test,
    const std::vector<double>& y_test
) { return binary_test(test_binary_decision_function(dec_funct, x_test, y_test)); }

template <typename K>
regression_test _test_regression_function (
    const decision_function<K>& reg_funct,
    const std::vector<typename K::sample_type>& x_test,
    const std::vector<double>& y_test
) { return regression_test(test_regression_function(reg_funct, x_test, y_test)); }

template < typename K >
ranking_test _test_ranking_function1 (
    const decision_function<K>& funct,
    const std::vector<ranking_pair<typename K::sample_type> >& samples
) { return ranking_test(test_ranking_function(funct, samples)); }

template < typename K >
ranking_test _test_ranking_function2 (
    const decision_function<K>& funct,
    const ranking_pair<typename K::sample_type>& sample
) { return ranking_test(test_ranking_function(funct, sample)); }

void bind_decision_functions()
{
    using boost::python::arg;
    add_linear_df<linear_kernel<sample_type> >("_decision_function_linear");
    add_linear_df<sparse_linear_kernel<sparse_vect> >("_decision_function_sparse_linear");

    add_df<histogram_intersection_kernel<sample_type> >("_decision_function_histogram_intersection");
    add_df<sparse_histogram_intersection_kernel<sparse_vect> >("_decision_function_sparse_histogram_intersection");

    add_df<polynomial_kernel<sample_type> >("_decision_function_polynomial");
    add_df<sparse_polynomial_kernel<sparse_vect> >("_decision_function_sparse_polynomial");

    add_df<radial_basis_kernel<sample_type> >("_decision_function_radial_basis");
    add_df<sparse_radial_basis_kernel<sparse_vect> >("_decision_function_sparse_radial_basis");

    add_df<sigmoid_kernel<sample_type> >("_decision_function_sigmoid");
    add_df<sparse_sigmoid_kernel<sparse_vect> >("_decision_function_sparse_sigmoid");

    def("test_binary_decision_function", _test_binary_decision_function<linear_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("labels")));
    def("test_binary_decision_function", _test_binary_decision_function<sparse_linear_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("labels")));
    def("test_binary_decision_function", _test_binary_decision_function<radial_basis_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("labels")));
    def("test_binary_decision_function", _test_binary_decision_function<sparse_radial_basis_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("labels")));
    def("test_binary_decision_function", _test_binary_decision_function<polynomial_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("labels")));
    def("test_binary_decision_function", _test_binary_decision_function<sparse_polynomial_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("labels")));
    def("test_binary_decision_function", _test_binary_decision_function<histogram_intersection_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("labels")));
    def("test_binary_decision_function", _test_binary_decision_function<sparse_histogram_intersection_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("labels")));
    def("test_binary_decision_function", _test_binary_decision_function<sigmoid_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("labels")));
    def("test_binary_decision_function", _test_binary_decision_function<sparse_sigmoid_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("labels")));

    def("test_regression_function", _test_regression_function<linear_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("targets")));
    def("test_regression_function", _test_regression_function<sparse_linear_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("targets")));
    def("test_regression_function", _test_regression_function<radial_basis_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("targets")));
    def("test_regression_function", _test_regression_function<sparse_radial_basis_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("targets")));
    def("test_regression_function", _test_regression_function<histogram_intersection_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("targets")));
    def("test_regression_function", _test_regression_function<sparse_histogram_intersection_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("targets")));
    def("test_regression_function", _test_regression_function<sigmoid_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("targets")));
    def("test_regression_function", _test_regression_function<sparse_sigmoid_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("targets")));
    def("test_regression_function", _test_regression_function<polynomial_kernel<sample_type> >,
        (arg("function"), arg("samples"), arg("targets")));
    def("test_regression_function", _test_regression_function<sparse_polynomial_kernel<sparse_vect> >,
        (arg("function"), arg("samples"), arg("targets")));

    def("test_ranking_function", _test_ranking_function1<linear_kernel<sample_type> >,
        (arg("function"), arg("samples")));
    def("test_ranking_function", _test_ranking_function1<sparse_linear_kernel<sparse_vect> >,
        (arg("function"), arg("samples")));
    def("test_ranking_function", _test_ranking_function2<linear_kernel<sample_type> >,
        (arg("function"), arg("sample")));
    def("test_ranking_function", _test_ranking_function2<sparse_linear_kernel<sparse_vect> >,
        (arg("function"), arg("sample")));

    class_<binary_test>("_binary_test")
        .def("__str__", binary_test__str__)
        .def("__repr__", binary_test__repr__)
        .add_property("class1_accuracy", &binary_test::class1_accuracy,
            "A value between 0 and 1, measures accuracy on the +1 class.")
        .add_property("class2_accuracy", &binary_test::class2_accuracy,
            "A value between 0 and 1, measures accuracy on the -1 class.");

    class_<ranking_test>("_ranking_test")
        .def("__str__", ranking_test__str__)
        .def("__repr__", ranking_test__repr__)
        .add_property("ranking_accuracy", &ranking_test::ranking_accuracy,
            "A value between 0 and 1, measures the fraction of times a relevant sample was ordered before a non-relevant sample.")
        .add_property("mean_ap", &ranking_test::mean_ap,
            "A value between 0 and 1, measures the mean average precision of the ranking.");

    class_<regression_test>("_regression_test")
        .def("__str__", regression_test__str__)
        .def("__repr__", regression_test__repr__)
        .add_property("mean_squared_error", &regression_test::mean_squared_error,
            "The mean squared error of a regression function on a dataset.")
        .add_property("R_squared", &regression_test::R_squared,
            "A value between 0 and 1, measures the squared correlation between the output of a \n"
            "regression function and the target values.");
}


text:
@interface RadioDetailPlayInfoModel : BaseModel

@property (nonatomic, copy) NSString *imgUrl; // 图片地址
@property (nonatomic, copy) NSString *musicUrl; // 音频地址
@property (nonatomic, copy) NSString *sharepic; // 图片共享
@property (nonatomic, copy) NSString *sharetext; // 分享文字
@property (nonatomic, copy) NSString *shareurl; // 分享链接
@property (nonatomic, copy) NSString *ting_contentid;
@property (nonatomic, copy) NSString *tingid;
@property (nonatomic, copy) NSString *title; // 标题
@property (nonatomic, copy) NSString *webview_url; // web地址

@property (nonatomic, strong) RadioDetailAuthorInfoModel *authorInfo; // 作者信息
@property (nonatomic, strong) RadioDetailShareInfoModel *shareInfo; // 用户信息
@property (nonatomic, strong) RadioUserInfoModel *userInfo; // 分享信息

@end


text:
package com.hazelcast.cp.internal.session;

import com.hazelcast.cp.internal.RaftGroupId;
import com.hazelcast.cp.internal.RaftInvocationManager;
import com.hazelcast.cp.internal.RaftOp;
import com.hazelcast.cp.internal.RaftService;
import com.hazelcast.cp.internal.datastructures.spi.RaftManagedService;
import com.hazelcast.cp.internal.session.operation.CloseSessionOp;
import com.hazelcast.cp.internal.session.operation.CreateSessionOp;
import com.hazelcast.cp.internal.session.operation.GenerateThreadIdOp;
import com.hazelcast.cp.internal.session.operation.HeartbeatSessionOp;
import com.hazelcast.internal.services.GracefulShutdownAwareService;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.impl.InternalCompletableFuture;
import com.hazelcast.spi.impl.NodeEngine;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import static com.hazelcast.cp.session.CPSession.CPSessionOwnerType.SERVER;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Server-side implementation of Raft proxy session manager
 */
public class ProxySessionManagerService extends AbstractProxySessionManager implements GracefulShutdownAwareService,
                                                                                RaftManagedService {

    /**
     * Name of the service
     */
    public static final String SERVICE_NAME = "hz:raft:proxySessionManagerService";

    private static final long SHUTDOWN_TASK_PERIOD_IN_MILLIS = SECONDS.toMillis(1);

    private final NodeEngine nodeEngine;

    public ProxySessionManagerService(NodeEngine nodeEngine) {
        this.nodeEngine = nodeEngine;
    }

    @Override
    protected long generateThreadId(RaftGroupId groupId) {
        return getInvocationManager().<Long>invoke(groupId, new GenerateThreadIdOp()).joinInternal();
    }

    @Override
    protected SessionResponse requestNewSession(RaftGroupId groupId) {
        String instanceName = nodeEngine.getConfig().getInstanceName();
        RaftOp op = new CreateSessionOp(nodeEngine.getThisAddress(), instanceName, SERVER);
        InternalCompletableFuture<SessionResponse> future = getInvocationManager().invoke(groupId, op);
        return future.joinInternal();
    }

    @Override
    protected InternalCompletableFuture<Object> heartbeat(RaftGroupId groupId, long sessionId) {
        return getInvocationManager().invoke(groupId, new HeartbeatSessionOp(sessionId));
    }

    @Override
    protected InternalCompletableFuture<Object> closeSession(RaftGroupId groupId, Long sessionId) {
        return getInvocationManager().invoke(groupId, new CloseSessionOp(sessionId));
    }

    @Override
    protected ScheduledFuture<?> scheduleWithRepetition(Runnable task, long period, TimeUnit unit) {
        return nodeEngine.getExecutionService().scheduleWithRepetition(task, period, period, unit);
    }

    @Override
    public boolean onShutdown(long timeout, TimeUnit unit) {
        ILogger logger = nodeEngine.getLogger(getClass());

        Map<RaftGroupId, InternalCompletableFuture<Object>> futures = shutdown();
        long remainingTimeNanos = unit.toNanos(timeout);
        boolean successful = true;

        while (remainingTimeNanos > 0 && futures.size() > 0) {
            Iterator<Entry<RaftGroupId, InternalCompletableFuture<Object>>> it = futures.entrySet().iterator();
            while (it.hasNext()) {
                Entry<RaftGroupId, InternalCompletableFuture<Object>> entry = it.next();
                RaftGroupId groupId = entry.getKey();
                InternalCompletableFuture<Object> f = entry.getValue();
                if (f.isDone()) {
                    it.remove();
                    try {
                        f.get();
                        logger.fine("Session closed for " + groupId);
                    } catch (Exception e) {
                        logger.warning("Close session failed for " + groupId, e);
                        successful = false;
                    }
                }
            }

            try {
                Thread.sleep(SHUTDOWN_TASK_PERIOD_IN_MILLIS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }

            remainingTimeNanos -= MILLISECONDS.toNanos(SHUTDOWN_TASK_PERIOD_IN_MILLIS);
        }

        return successful && futures.isEmpty();
    }

    private RaftInvocationManager getInvocationManager() {
        RaftService raftService = nodeEngine.getService(RaftService.SERVICE_NAME);
        return raftService.getInvocationManager();
    }

    @Override
    public void init(NodeEngine nodeEngine, Properties properties) {
    }

    @Override
    public void reset() {
    }

    @Override
    public void shutdown(boolean terminate) {
    }

    @Override
    public void onCPSubsystemRestart() {
        resetInternalState();
    }
}


text:
        <title></title>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <link rel="stylesheet" href="./data/dynamic.css"/>

        <sharpdox-app>

        </sharpdox-app>


text:
package org.apache.hadoop.hdfs;

import junit.framework.TestCase;

import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.namenode.LeaseManager;
import org.apache.hadoop.io.IOUtils;
import org.apache.log4j.Level;

/**
 * This class tests blockRecovery can throw exception if deadline reaches.
 */
public class TestBlockRecovery extends junit.framework.TestCase {
  static final String DIR = "/" + TestBlockRecovery.class.getSimpleName() + "/";

  {
    // ((Log4JLogger)DataNode.LOG).getLogger().setLevel(Level.ALL);
    ((Log4JLogger) LeaseManager.LOG).getLogger().setLevel(Level.ALL);
    ((Log4JLogger) FSNamesystem.LOG).getLogger().setLevel(Level.ALL);
    ((Log4JLogger) DFSClient.LOG).getLogger().setLevel(Level.ALL);
  }

  static final long seed = 0xDEADBEEFL;
  static final int blockSize = 8192;
  static final int numBlocks = 2;
  static final int fileSize = numBlocks * blockSize + 1;
  boolean simulatedStorage = false;
  boolean federation = false;
  static final int numNameNodes = 3;

  /**
   * Create a file, write something, and try to do a block recovery with
   * deadline is current time
   */
  public void testBlockRecoveryTimeout() throws Exception {
    System.out.println("testConcurrentLeaseRecovery start");
    final int DATANODE_NUM = 3;

    Configuration conf = new Configuration();
    conf.setInt("heartbeat.recheck.interval", 1000);
    conf.setInt("dfs.heartbeat.interval", 1);

    // create cluster
    MiniDFSCluster cluster = new MiniDFSCluster(conf, DATANODE_NUM, true, null);
    DistributedFileSystem dfs = null;
    try {
      cluster.waitActive();
      dfs = (DistributedFileSystem) cluster.getFileSystem();

      // create a new file.
      final String f = "/testBlockRecoveryTimeout";
      final Path fpath = new Path(f);
      FSDataOutputStream out = TestFileCreation.createFile(dfs, fpath,
          DATANODE_NUM);
      out.write("something".getBytes());
      out.sync();

      LocatedBlocks locations = dfs.dfs.namenode.getBlockLocations(f, 0,
          Long.MAX_VALUE);
      assertEquals(1, locations.locatedBlockCount());
      LocatedBlock locatedblock = locations.getLocatedBlocks().get(0);
      int nsId = cluster.getNameNode().getNamespaceID();

      for (DatanodeInfo datanodeinfo : locatedblock.getLocations()) {
        DataNode datanode = cluster.getDataNode(datanodeinfo.ipcPort);
        try {
          datanode.recoverBlock(nsId, locatedblock.getBlock(), true,
              locatedblock.getLocations(), System.currentTimeMillis());
          TestCase.fail("recoverBlock didn't throw timeout exception");
        } catch (DataNode.BlockRecoveryTimeoutException e) {

        }
        break;
      }
    } finally {
      IOUtils.closeStream(dfs);
      cluster.shutdown();
    }
    System.out.println("testLeaseExpireHardLimit successful");
  }
}


text:
@interface CNTransportationTableViewController : UITableViewController

@end


text:
package javaclient3.structures.pointcloud3d;

import javaclient3.structures.*;

/**
 * 3D Pointcloud element structure
 * An element as stored in a 3D pointcloud, containing a 3D position
 * plus other corresponding information.
 * @author Radu Bogdan Rusu
 * @version
 *

 *
v3.0 - Player 3.0 supported
 *

 */
public class PlayerPointCloud3DElement implements PlayerConstants {

    PlayerPoint3d point;
    PlayerColor   color;

    /**
     * @return
     */
    public synchronized PlayerPoint3d getPoint () {
        return this.point;
    }

    /**
     * @param newPoint
     */
    public synchronized void setPoint (PlayerPoint3d newPoint) {
        this.point = newPoint;
    }

    /**
     * @return
     */
    public synchronized PlayerColor getColor () {
        return this.color;
    }

    /**
     * @param newColor
     */
    public synchronized void setColor (PlayerColor newColor) {
        this.color = newColor;
    }
}


text:
#import "CHMutableDictionary.h"

/**
 A dictionary that allows bidirectional lookup by keys and values with equal ease. This is possible because a bidirectional dictionary enforces the restriction that there is a 1-to-1 relation between keys and values, meaning that multiple keys cannot map to the same value. This is accomplished using a second internal dictionary which stores value-to-key mappings so values can be checked for uniqueness upon insertion. (Since values become the keys in this secondary dictionary, values must also be unique.) See \link #setObject:forKey: -setObject:forKey:\endlink below for details.

 The main purpose of this constraint is to make it trivial to do bidirectional lookups of one-to-one relationships. A trivial example might be to store husband-wife pairs and look up by either, rather than choosing only one.

 There are two simple ways (equivalent in performance) to look up a key by it's value:
 - Call \link #keyForObject: -keyForObject:\endlink on a bidirectional dictionary.
 - Acquire the inverse dictionary via \link #inverseDictionary -inverseDictionary\endlink, then call \link #setObject:forKey: -objectForKey:\endlink on that.

 @attention Since values are used as keys in the inverse dictionary, both keys and values must conform to the NSCopying protocol. (NSDictionary requires that keys conform to NSCopying, but not values.) If they don't, a crash will result when this collection attempts to copy them.

 @warning If a dictionary is passed to \link NSDictionary#initWithDictionary: -initWithDictionary:\endlink which maps the same value to multiple keys, the value will be mapped to whichever key mapped to that value is enumerated last. Depending on the specifics of the dictionary, this ordering may be arbitrary.

 Implementations of bidirectional dictionaries (aka "maps") in other languages include the following:

 - BiMap / BidiMap (Java)
 - Boost.Bimap / bimap (C++)
 - BiDirHashtable (C#)
 */
@interface CHBidirectionalDictionary : CHMutableDictionary {
	__strong CFMutableDictionaryRef objectsToKeys; // Used for reverse mapping.
	CHBidirectionalDictionary* inverse; // Pointer to inverse dictionary.
}

#pragma mark Querying Contents
/** @name Querying Contents */
// @{

/**
 Returns the key associated with a given value.

 @param anObject The value for which to return the corresponding key.
 @return The key associated with @a value, or @c nil if no such key exists.

 @see \link NSDictionary#allKeys -allKeys\endlink
 @see \link NSDictionary#objectForKey: -objectForKey:\endlink
 @see removeKeyForObject:
 */
- (id) keyForObject:(id)anObject;

/**
 Returns the inverse view of the receiver, which maps each value to its associated key. The receiver and its inverse are backed by the same data; any changes to one will appear in the other. A reference to the inverse (if one exists) is stored internally, and vice versa, so the two instances are linked. If one is released, it will cut its ties to and from the other.

 @return The inverse view of the receiver,

 @attention There is no guaranteed correspondence between the order in which keys are enumerated for a dictionary and its inverse.
 */
- (CHBidirectionalDictionary*) inverseDictionary;

// @}
#pragma mark Modifying Contents
/** @name Modifying Contents */
// @{

/**
 Adds the entries from another dictionary to the receiver. Keys and values are copied as described in #setObject:forKey: below. If a key or value already exists in the receiver, the existing key-value mapping is replaced.

 @param otherDictionary The dictionary from which to add entries. All its keys @b and values must conform to the NSCopying protocol.

 @attention If @a otherDictionary maps the same value to multiple keys, the value can only appear once in the receiver, and will be mapped to the key that is enumerated @b last, which may be arbitrary. However, if @a otherDictionary is also a CHBidirectionalDictionary, the results will always be deterministic.

 @see \link NSDictionary#initWithDictionary: -initWithDictionary:\endlink
 @see setObject:forKey:
 */
- (void) addEntriesFromDictionary:(NSDictionary*)otherDictionary;

/**
 Removes the key for a given value (and its inverse key-value mapping) from the receiver. Does nothing if the specified value doesn't exist.

 @param anObject The value to remove.

 @throw NSInvalidArgumentException if @a anObject is @c nil.

 @see keyForObject:
 @see removeObjectForKey:
 */
- (void) removeKeyForObject:(id)anObject;

/**
 Removes the value for a given key (and its inverse value-key mapping) from the receiver. Does nothing if the specified key doesn't exist.

 @param aKey The key to remove.

 @throw NSInvalidArgumentException if @a aKey is @c nil.

 @see \link NSDictionary#objectForKey: -objectForKey:\endlink
 @see removeKeyForObject:
 */
- (void) removeObjectForKey:(id)aKey;

/**
 Adds a given key-value pair to the receiver, replacing any existing pair with the given key or value.

 @param anObject The value for @a aKey. The object is copied, so it @b must conform to the NSCopying protocol or a crash will result.
 @param aKey The key for @a anObject. The key is copied, so it @b must conform to the NSCopying protocol or a crash will result.

 @throw NSInvalidArgumentException if @a aKey or @a anObject is @c nil. If you need to represent a nil value in the dictionary, use NSNull.

 @attention If @a aKey already exists in the receiver, the value previously associated with it is replaced by @a anObject, just as expected. However, if @a anObject already exists in the reciever with a different key, that mapping is removed to ensure that @a anObject only occurs once in the inverse dictionary. To check whether this will occur, call #keyForObject: first.

 @b Example:
 @code
 id dict = [[CHBidirectionalDictionary alloc] init];
 [dict setObject:@"B" forKey:@"A"]; // now contains A -> B
 [dict setObject:@"C" forKey:@"A"]; // now contains A -> C
 [dict setObject:@"C" forKey:@"B"]; // now contains B -> C
 // Values must be unique just like keys, so A -> C is removed
 [dict setObject:@"D" forKey:@"A"]; // now contains B -> C, A -> D
 @endcode

 @see keyForObject:
 @see \link NSDictionary#objectForKey: -objectForKey:\endlink
 */
- (void) setObject:(id)anObject forKey:(id)aKey;

// @}
@end


text:
class CreateCompetitions < ActiveRecord::Migration
  def change
    create_table :competitions do |t|
      t.string :title
      t.text :description
      t.date :start_on
      t.date :end_on
      t.integer :owner_id

      t.timestamps
    end

    add_index :competitions, :owner_id
  end
end


text:
exports.Client = require('./client');
exports.EzSecurityToken = require('./thrift/ezbakeBaseTypes_types').EzSecurityToken;

exports.Constant = require('./constant');
exports.RSAKeyCrypto = require('./crypto/rsaKeyCrypto');


text:
import datetime
import time
import re
import os
from werkzeug import secure_filename
from flask import (
    Blueprint, render_template, request,
    current_app, jsonify
)
from sqlalchemy.orm import load_only

from wexplorer.database import db
from wexplorer.explorer.models import (
    Company, CompanyContact, Contract, LastUpdated
)
from wexplorer.explorer.util import SimplePagination
from wexplorer.explorer.forms import SearchBox, NewItemBox, FileUpload
from wexplorer.data_update import update

blueprint = Blueprint('explorer', __name__, url_prefix='/explore',
                      static_folder="../static")

@blueprint.route('/', methods=['GET', 'POST'])
def search():
    '''
    The view for the basic search box.
    '''
    form = SearchBox(request.form)

    if request.args.get('q') is None:
        return render_template('explorer/explore.html', form=form)

    results = []
    search_for = request.args.get('q')
    page = int(request.args.get('page', 1))
    lower_bound = (page - 1) * 50
    upper_bound = lower_bound + 50

    companies = db.session.execute(
        '''
        SELECT a.company_id, b.contract_id, a.company, b.description
        FROM company a
        INNER JOIN contract b
        ON a.company_id = b.company_id
        WHERE a.company ilike :search_for_wc
        OR b.description ilike :search_for_wc
        OR b.controller_number::VARCHAR = :search_for
        OR b.contract_number ilike :search_for_wc
        ORDER BY a.company, b.description
        ''',
        {
            'search_for_wc': '%' + str(search_for)   + '%',
            'search_for': search_for,
        }
    ).fetchall()

    pagination = SimplePagination(page, 50, len(companies))

    for company in companies[lower_bound:upper_bound]:
        results.append({
            'company_id': company[0],
            'contract_id': company[1],
            'name': company[2],
            'description': company[3]
        })

    if len(results) == 0:
        results = None

    updated = LastUpdated.query.first()
    if updated:
        last_updated = datetime.datetime.strftime(LastUpdated.query.first().last_updated, '%b %d %Y at %I:%M %p')
    else:
        last_updated = None

    return render_template(
        'explorer/explore.html', form=form, names=results, pagination=pagination, last_updated=last_updated
    )

@blueprint.route('/companies/<company_id>', methods=['GET', 'POST'])
def companies(company_id, page=1):
    '''
    Simple profile page for companies
    '''
    iform = NewItemBox()
    page = int(request.args.get('page', 1))

    company = Company.query.filter(
        Company.company_id == company_id
    ).distinct().first()

    contacts = CompanyContact.query.distinct(
        CompanyContact.contact_name, CompanyContact.address_1,
        CompanyContact.address_2, CompanyContact.phone_number,
        CompanyContact.email,
    ).options(
        load_only(
            'contact_name', 'address_1', 'address_2', 'phone_number', 'email'
        )
    ).filter(CompanyContact.company_id == company_id).all()

    return render_template(
        'explorer/companies.html',
        company=company,
        contacts=contacts,
        form=SearchBox(),
        iform=iform
    )

@blueprint.route('/contracts/<contract_id>', methods=['GET'])
def contracts(contract_id):
    '''
    Simple profile page for individual contracts
    '''
    form = SearchBox(request.form)

    company = Company.query.join(Contract).filter(
        Contract.contract_id == contract_id
    ).first()

    contract = company.contracts[0]
    contract_href = None
    if contract.contract_number and contract.type_of_contract.lower() == 'county':
        # first try to convert it to an int
        try:
            _contract_number = int(float(contract.contract_number))
            contract.contract_number = _contract_number
        # if you can't, it has * or other characters, so just
        # strip down to the digits
        except ValueError:
            if '**' in contract.contract_number:
                _contract_number = int(re.sub(r'i?\D', '', contract.contract_number))
            elif '*' in contract.contract_number:
                _contract_number = None
            elif 'i' in contract.contract_number:
                _contract_number = contract.contract_number

        # take the result and stick it into the well-formed county urls
        contract_href = 'http://apps.county.allegheny.pa.us/BidsSearch/pdf/{number}.pdf'.format(
            number=_contract_number
        ) if _contract_number else None

    return render_template(
        'explorer/contracts.html',
        company=company,
        contract=contract,
        form=form,
        contract_href=contract_href
    )

@blueprint.route('/upload_new', methods=['GET', 'POST'])
def upload():
    form = FileUpload()
    if form.validate_on_submit():
        _file = request.files.get('upload')
        filename = secure_filename(_file.filename)
        filepath = os.path.join(current_app.config.get('UPLOAD_FOLDER'), filename)
        _file.save(filepath)
        return render_template('explorer/upload_success.html', filepath=filepath)
    else:
        return render_template('explorer/upload_new.html', form=form)

@blueprint.route('/_process_file', methods=['POST'])
def process_upload():
    filepath = request.form.get('filepath')
    result = update(filepath)
    if result.get('status') == 'success':
        db.session.add(LastUpdated(datetime.datetime.now()))
        db.session.commit()
        return jsonify(result), 200
    else:
        return jsonify(result), 403

@blueprint.route('/_status')
def check_status():
    response = {}
    response['status'] = 'ok'
    try:
        Contract.query.first()
    except:
        response['status'] = 'Database is unavailable'
    response['updated'] = int(time.time())
    response['dependencies'] = []
    return jsonify(response)


text:
/* vim:set ts=2 sw=2 sts=2 cin et: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <QIcon>
#include <QStyle>
#include <QApplication>

#include <stdlib.h>
#include <unistd.h>

#include "nsIMIMEService.h"

#include "nsIStringBundle.h"

#include "nsNetUtil.h"
#include "nsIURL.h"
#include "prlink.h"

#include "nsIconChannel.h"
#include "nsGtkQtIconsConverter.h"

NS_IMPL_ISUPPORTS2(nsIconChannel,
                   nsIRequest,
                   nsIChannel)

static nsresult
moz_qicon_to_channel(QImage *image, nsIURI *aURI,
                     nsIChannel **aChannel)
{
  NS_ENSURE_ARG_POINTER(image);

  int width = image->width();
  int height = image->height();

  NS_ENSURE_TRUE(height < 256 && width < 256 && height > 0 && width > 0,
                 NS_ERROR_UNEXPECTED);

  const int n_channels = 4;
  long int buf_size = 2 + n_channels * height * width;
  uint8_t * const buf = (uint8_t*)NS_Alloc(buf_size);
  NS_ENSURE_TRUE(buf, NS_ERROR_OUT_OF_MEMORY);
  uint8_t *out = buf;

  *(out++) = width;
  *(out++) = height;

  const uchar * const pixels = image->bits();
  int rowextra = image->bytesPerLine() - width * n_channels;

  // encode the RGB data and the A data
  const uchar * in = pixels;
  for (int y = 0; y < height; ++y, in += rowextra) {
    for (int x = 0; x < width; ++x) {
      uint8_t r = *(in++);
      uint8_t g = *(in++);
      uint8_t b = *(in++);
      uint8_t a = *(in++);
#define DO_PREMULTIPLY(c_) uint8_t(uint16_t(c_) * uint16_t(a) / uint16_t(255))
#ifdef IS_LITTLE_ENDIAN
      *(out++) = DO_PREMULTIPLY(b);
      *(out++) = DO_PREMULTIPLY(g);
      *(out++) = DO_PREMULTIPLY(r);
      *(out++) = a;
#else
      *(out++) = a;
      *(out++) = DO_PREMULTIPLY(r);
      *(out++) = DO_PREMULTIPLY(g);
      *(out++) = DO_PREMULTIPLY(b);
#endif
#undef DO_PREMULTIPLY
    }
  }

  NS_ASSERTION(out == buf + buf_size, "size miscalculation");

  nsresult rv;
  nsCOMPtr<nsIStringInputStream> stream =
    do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = stream->AdoptData((char*)buf, buf_size);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_NewInputStreamChannel(aChannel, aURI, stream,
                                  NS_LITERAL_CSTRING("image/icon"));
}

nsresult
nsIconChannel::Init(nsIURI* aURI)
{

  nsCOMPtr<nsIMozIconURI> iconURI = do_QueryInterface(aURI);
  NS_ASSERTION(iconURI, "URI is not an nsIMozIconURI");

  nsAutoCString stockIcon;
  iconURI->GetStockIcon(stockIcon);

  nsAutoCString iconSizeString;
  iconURI->GetIconSize(iconSizeString);

  uint32_t desiredImageSize;
  iconURI->GetImageSize(&desiredImageSize);

  nsAutoCString iconStateString;
  iconURI->GetIconState(iconStateString);
  bool disabled = iconStateString.EqualsLiteral("disabled");

  QStyle::StandardPixmap sp_icon = (QStyle::StandardPixmap)0;
  nsCOMPtr <nsIGtkQtIconsConverter> converter = do_GetService("@mozilla.org/gtkqticonsconverter;1");
  if (converter) {
    int32_t res = 0;
    stockIcon.Cut(0,4);
    converter->Convert(stockIcon.get(), &res);
    sp_icon = (QStyle::StandardPixmap)res;
    // printf("ConvertIcon: icon:'%s' -> res:%i\n", stockIcon.get(), res);
  }
  if (!sp_icon)
    return NS_ERROR_FAILURE;

  QStyle *style = qApp->style();
  NS_ENSURE_TRUE(style, NS_ERROR_NULL_POINTER);
  QPixmap pixmap = style->standardIcon(sp_icon).pixmap(desiredImageSize, desiredImageSize, disabled?QIcon::Disabled:QIcon::Normal);
  QImage image = pixmap.toImage();

  return moz_qicon_to_channel(&image, iconURI,
                              getter_AddRefs(mRealChannel));
}


text:
package cullencarns.main;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * Controls all aspects of the program
 *
 * @author Cullen Carns
 */
public class Main {

    //////////////// WINDOW VARIABLES -->
    /* Main window of the program  */
    private JFrame window;
    /* Title of the window, has no effect if window is undecorated or in full
     screen */
    private final String title = "2D";
    /* If true, the window is full screen */
    private boolean fullscreen = false;
    /* If true, F11 toggles fullscreen */
    private final boolean fullscreenToggleable = true;
    /* Whether or not the window has a border, min, max, and exit buttons, etc.
     Overriden if window is fullScreen */
    private final boolean decorated = true;
    /* Whether or not window is resizeable */
    private final boolean resizeable = true;

    /* Tells min and max values of window dimensions, if <0 (i.e. -1) it is
     ignored, also ignored if resizeable is false
     THIS IS PLATFORM DEPENDENT!! I have used a work around by updating the
     window, but this doesn't look as nice. Users will still get the idea when
     they cannot resize the window  */
    private final int minWinWidth = -1, minWinHeight = -1, maxWinWidth = -1,
            maxWinHeight = -1;

    /* Window coords, if <0 (i.e. -1) window is centered on screen */
    private int winX = -1, winY = -1;
    /* Overriden if canvas width and height are >0 */
    private int winWidth = 980, winHeight = 720;
    //////////////// <-- WINDOW VARIABLES

    //////////////// CANVAS AND PANEL VARIABLES -->
    private Canvas canvas;
    private BufferStrategy bs;
    private JPanel panel;
    /* Tells min and max values of canvas dimensions, if <0 (i.e. -1) it is
     ignored, also ignored if resizeable is false, overrides window size
     THIS IS PLATFORM DEPENDENT!! I have used a work around by updating the
     window, but this doesn't look as nice. Users will still get the idea when
     they cannot resize the window  */
    private final int minCanvasWidth = -1, minCanvasHeight = -1, maxCanvasWidth = -1,
            maxCanvasHeight = -1;
    /* Canvas size adjusts automatically to window, if canvas width and height
     are set >0 here, window adjusts to match canvas size (the window borders
     have a thickness and that is incorporated into window width and height,
     setting canvas size ensures draw area is a specific size) overriden by
     fullscreen */
    private int canvasWidth = 980, canvasHeight = 720;
    /* Number of buffers in buffer strategy */
    private int numBuffers = 2;
    //////////////// <-- CANVAS AND PANEL VARIABLES

    //////////////// GAME LOGIC VARIABLES -->
    private boolean isRunning = true;
    private double delta;
    private double lastUpdateTime;
    //////////////// <-- GAME LOGIC VARIABLES

    public static void main(String[] args) {
        /* Create a new Main and call the start function */
        new Main().start();
    }

    public void start() {
        initWindow();
        updateLoop();
    }

    private void updateLoop() {
        /* If last update time started at 0, the first delta would be huge */
        lastUpdateTime = System.nanoTime();
        while (isRunning) {
            updateWindow();

            /* Update time variables */
            double now = System.nanoTime();
            delta = (now - lastUpdateTime) / 1000000000;
            lastUpdateTime = now;

            update();

            /* Make sure no contents are lost during rendering */
            do {
                render();
            } while (bs.contentsLost());

            /* Make sure some time passes between updates */
            while (!(System.nanoTime() > now)) {
                for (int i = 0; i < 1000; i++) {
                }
            }
        }
    }

    private void update() {
        /* Update stuff */
    }

    private void render() {
        Graphics2D g = (Graphics2D) bs.getDrawGraphics();

        /* Draw background */
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0, 0, canvasWidth, canvasHeight);

        /* Draw more things */

        /* Show buffer strategy */
        g.dispose();
        bs.show();
    }

    private void initWindow() {
        int width = this.winWidth;
        int height = this.winHeight;
        window = new JFrame(title);

        /* Apply fullscreen and decorations to window */
        if (fullscreen) {
            try {
                Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
                width = (int) dim.getWidth();
                height = (int) dim.getHeight();
            } catch (Exception e) {
                System.out.println(e);
            }
            window.setUndecorated(true);
        } else {
            window.setUndecorated(!decorated);
        }

        /* If true, canvas size overrides window size */
        boolean canvasSizeOverride = !fullscreen && canvasWidth > 0 && canvasHeight > 0;
        canvas = new Canvas();
        panel = (JPanel) window.getContentPane();
        /* Set canvas size, make it too big if it doesn't override window that
         way it gets updated after setting the window size */
        if (canvasSizeOverride) {
            canvas.setBounds(0, 0, canvasWidth, canvasHeight);
        } else {
            canvas.setBounds(0, 0, winWidth, winHeight);
        }
        /* Set ignore repaint because we will be painting canvas manually */
        canvas.setIgnoreRepaint(true);
        panel.add(canvas);
        /* Size window appropriately */
        if (canvasSizeOverride) {
            window.pack();
        } else {
            window.setSize(winWidth, winHeight);
        }

        /* Apply position to window */
        if (winX >= 0 && winY >= 0) {
            window.setLocation(winX, winY);
        } else {
            window.setLocationRelativeTo(null);
        }
        /* Apply resize features to window */
        if (resizeable) {
            if (minWinWidth >= 0 && minWinHeight >= 0) {
                window.setMinimumSize(new Dimension(minWinWidth, minWinHeight));
            }
            if (maxWinWidth >= 0 && maxWinHeight >= 0) {
                window.setMaximumSize(new Dimension(maxWinWidth, maxWinHeight));
            }
        }
        window.setResizable(resizeable);

        /* Make program exit when window closes */
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /* Update canvas width and height */
        canvasWidth = canvas.getWidth();
        canvasHeight = canvas.getHeight();

        /* Open the window */
        window.setVisible(true);

        /* Create buffer strategy */
        canvas.createBufferStrategy(numBuffers);
        bs = canvas.getBufferStrategy();
    }

    private void updateWindow() {
        if (!fullscreen) {
            /* Ensure the window obeys the min and max values */
            winWidth = window.getWidth();
            winHeight = window.getHeight();
            canvasWidth = canvas.getWidth();
            canvasHeight = canvas.getHeight();
            winX = window.getX();
            winY = window.getY();
            boolean canvasMinOverride = minCanvasWidth >= 0 && minCanvasHeight >= 0;
            boolean canvasMaxOverride = maxCanvasWidth >= 0 && maxCanvasHeight >= 0;
            if (canvasMinOverride) {
                if (canvasWidth < minCanvasWidth) {
                    canvasWidth = minCanvasWidth;
                }
                if (canvasHeight < minCanvasHeight) {
                    canvasHeight = minCanvasHeight;
                }
                canvas.setSize(canvasWidth, canvasHeight);
                window.pack();
            } else {
                if (minWinWidth >= 0 && winWidth < minWinWidth) {
                    winWidth = minWinWidth;
                }
                if (minWinHeight >= 0 && winHeight < minWinHeight) {
                    winHeight = minWinHeight;
                }
                window.setSize(winWidth, winHeight);
            }
            if (canvasMaxOverride) {
                if (canvasWidth > maxCanvasWidth) {
                    canvasWidth = maxCanvasWidth;
                }
                if (canvasHeight > maxCanvasHeight) {
                    canvasHeight = maxCanvasHeight;
                }
                canvas.setSize(canvasWidth,canvasHeight);
                window.pack();
            } else {
                if (maxWinWidth >= 0 && winWidth > maxWinWidth) {
                    winWidth = maxWinWidth;
                }
                if (maxWinHeight >= 0 && winHeight > maxWinHeight) {
                    winHeight = maxWinHeight;
                }
                window.setSize(winWidth, winHeight);
            }
        }
    }
}


text:
var ramlFasker = require('../index'),
	_ = require("lodash");

var options = {
	path: 'raml'
};

ramlFasker.generate(options, function (requestsToMock) {
	//console.log(requestsToMock);

	console.log(requestsToMock.length);

	_.each(requestsToMock, function(reqToMock){
		console.log('-----------------');
		console.log('uri ----->' + reqToMock.uri);

		console.log('code ----->' + reqToMock.defaultCode);

		try{
			console.log(reqToMock.mock());
		} catch (exception){
			console.log(exception.stack);
		}

	});
});


text:
package com.facebook.buck.cxx;

import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.RuleKeyObjectSink;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SymlinkTree;
import com.facebook.buck.util.immutables.BuckStyleImmutable;

import org.immutables.value.Value;

import java.util.Optional;

@Value.Immutable
@BuckStyleImmutable
abstract class AbstractCxxSandboxInclude extends CxxHeaders {

  @Override
  @Value.Parameter
  public abstract CxxPreprocessables.IncludeType getIncludeType();

  @Override
  @Value.Parameter
  public abstract SourcePath getRoot();

  @Override
  public SourcePath getIncludeRoot() {
    return getRoot();
  }

  @Value.Parameter
  public abstract String getIncludeDir();

  @Override
  public Optional<SourcePath> getHeaderMap() {
    return Optional.empty();
  }

  @Override
  public void addToHeaderPathNormalizer(HeaderPathNormalizer.Builder builder) {
    builder.addHeaderDir(getRoot());
  }

  @Override
  public Iterable<BuildRule> getDeps(SourcePathResolver resolver) {
    return resolver.filterBuildRuleInputs(getRoot());
  }

  @Override
  public void appendToRuleKey(RuleKeyObjectSink sink) {
    sink.setReflectively("type", getIncludeType());
    sink.setReflectively("includeDir", getIncludeDir());
  }

  public static CxxSandboxInclude from(
      SymlinkTree symlinkTree,
      String includeDir,
      CxxPreprocessables.IncludeType includeType) {

    CxxSandboxInclude.Builder builder = CxxSandboxInclude.builder();
    builder.setIncludeType(includeType);
    builder.setRoot(
        new BuildTargetSourcePath(
            symlinkTree.getBuildTarget(),
            symlinkTree.getRoot().resolve(includeDir)));
    builder.setIncludeDir(includeDir);
    return builder.build();
  }
}


text:
"""
    SleekXMPP: The Sleek XMPP Library
    Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. Stout
    This file is part of SleekXMPP.

    See the file LICENSE for copying permission.
"""

from sleekxmpp.xmlstream import ElementBase, ET

class UserGaming(ElementBase):

    name = 'gaming'
    namespace = 'urn:xmpp:gaming:0'
    plugin_attrib = 'gaming'
    interfaces = set(['character_name', 'character_profile', 'name',
                        'level', 'server_address', 'server_name', 'uri'])
    sub_interfaces = interfaces


text:
SELECT
    hfp3pos.t_id AS tid,
    hfp3pos.hfp3pos_von,
    hfp3pos.pos,
    hfp3pos.ori,
    halignment.itfcode AS hali,
    hfp3pos.hali AS hali_txt,
    valignment.itfcode AS vali,
    hfp3pos.vali AS vali_txt,
    CAST(hfp3pos.t_datasetname AS INT) AS gem_bfs,
    0 AS los,
    aimport.importdate AS lieferdatum
FROM
    agi_dm01avso24.fixpunktekatgrie3_hfp3pos AS hfp3pos
    LEFT JOIN agi_dm01avso24.t_ili2db_basket AS basket
        ON hfp3pos.t_basket = basket.t_id
    LEFT JOIN agi_dm01avso24.halignment AS halignment
        ON hfp3pos.hali = halignment.ilicode
    LEFT JOIN agi_dm01avso24.valignment AS valignment
        ON hfp3pos.vali = valignment.ilicode
    LEFT JOIN
    (
        SELECT
            max(importdate) AS importdate,
            dataset
        FROM
            agi_dm01avso24.t_ili2db_import
        GROUP BY
            dataset
    ) AS  aimport
        ON basket.dataset = aimport.dataset
;


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Neodroid: droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Neodroid
    0.2.0

Machine Learning Environment Prototyping Tool

Public Member Functions |
Protected Member Functions |
Properties |
List of all members

droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor Class Reference

 More...

Inheritance diagram for droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor:

<map name="droid_8_runtime_8_prototyping_8_sensors_8_transform_8_euler_transform_sensor_inherit__map" id="droid_8_runtime_8_prototyping_8_sensors_8_transform_8_euler_transform_sensor_inherit__map">
<area shape="rect" id="node2" href="classdroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_sensor.html" title="Sensor" alt="" coords="127,155,189,181"/>
<area shape="rect" id="node3" href="classdroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_prototyping_game_object.html" title="PrototypingGameObject" alt="" coords="5,80,167,107"/>
<area shape="rect" id="node5" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_registerable.html" title="IRegisterable" alt="" coords="173,5,271,32"/>
<area shape="rect" id="node6" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_observer.html" title="IObserver" alt="" coords="191,80,269,107"/>
<area shape="rect" id="node7" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_euler_transform.html" title="IHasEulerTransform" alt="" coords="214,155,353,181"/>
</map>
[legend]

Collaboration diagram for droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor:

<map name="droid_8_runtime_8_prototyping_8_sensors_8_transform_8_euler_transform_sensor_coll__map" id="droid_8_runtime_8_prototyping_8_sensors_8_transform_8_euler_transform_sensor_coll__map">
<area shape="rect" id="node2" href="classdroid_1_1_runtime_1_1_prototyping_1_1_sensors_1_1_sensor.html" title="Sensor" alt="" coords="127,155,189,181"/>
<area shape="rect" id="node3" href="classdroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_prototyping_game_object.html" title="PrototypingGameObject" alt="" coords="5,80,167,107"/>
<area shape="rect" id="node5" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_registerable.html" title="IRegisterable" alt="" coords="173,5,271,32"/>
<area shape="rect" id="node6" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_observer.html" title="IObserver" alt="" coords="191,80,269,107"/>
<area shape="rect" id="node7" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_euler_transform.html" title="IHasEulerTransform" alt="" coords="214,155,353,181"/>
</map>
[legend]

Public Member Functions

override void 	UpdateObservation ()

 Public Member Functions inherited from droid.Runtime.Prototyping.Sensors.Sensor

void 	EnvironmentReset ()

override string 	ToString ()

 Public Member Functions inherited from droid.Runtime.Utilities.GameObjects.PrototypingGameObject

void 	RefreshStart ()

void 	RefreshAwake ()

Protected Member Functions

override void 	PreSetup ()

 Protected Member Functions inherited from droid.Runtime.Prototyping.Sensors.Sensor

sealed override void 	Setup ()

override void 	RegisterComponent ()

override void 	UnRegisterComponent ()

virtual void 	Update ()

 Protected Member Functions inherited from droid.Runtime.Utilities.GameObjects.PrototypingGameObject

void 	Start ()

void 	Awake ()

virtual void 	Clear ()

Properties

override string 	PrototypingTypeName [get]

Vector3 	Position [get, set]

Vector3 	Rotation [get, set]

Space3 	PositionSpace [get]

Space3 	DirectionSpace = new Space3() [get]

Space3 	RotationSpace = new Space3() [get]

Vector3 	Direction = new Space3() [get, set]

override IEnumerable< float > 	FloatEnumerable [get]

 Properties inherited from droid.Runtime.Prototyping.Sensors.Sensor

AbstractPrototypingEnvironment 	ParentEnvironment [get, set]

abstract IEnumerable< float > 	FloatEnumerable [get]

 Properties inherited from droid.Runtime.Utilities.GameObjects.PrototypingGameObject

virtual string 	PrototypingTypeName [get]

string 	Identifier [get]

 Properties inherited from droid.Runtime.Interfaces.IRegisterable

string 	Identifier [get]

 Properties inherited from droid.Runtime.Interfaces.IObserver

IEnumerable< float > 	FloatEnumerable [get]

 Properties inherited from droid.Runtime.Interfaces.IHasEulerTransform

Vector3 	Position [get]

Vector3 	Direction [get]

Vector3 	Rotation [get]

Space3 	PositionSpace [get]

Space3 	DirectionSpace [get]

Space3 	RotationSpace [get]

Additional Inherited Members

 Protected Attributes inherited from droid.Runtime.Utilities.GameObjects.PrototypingGameObject

string 	_Custom_Name = ""

Detailed Description

Definition at line 34 of file EulerTransformSensor.cs.

Member Function Documentation

◆ PreSetup()

          override void droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.PreSetup
          (
          	)

protectedvirtual

Reimplemented from droid.Runtime.Prototyping.Sensors.Sensor.

Definition at line 150 of file EulerTransformSensor.cs.

◆ UpdateObservation()

          override void droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.UpdateObservation
          (
          	)

virtual

Implements droid.Runtime.Prototyping.Sensors.Sensor.

Definition at line 130 of file EulerTransformSensor.cs.

Property Documentation

◆ Direction

          Vector3 droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.Direction = new Space3()

getset

Definition at line 100 of file EulerTransformSensor.cs.

◆ DirectionSpace

          Space3 droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.DirectionSpace = new Space3()

get

Definition at line 90 of file EulerTransformSensor.cs.

◆ FloatEnumerable

          override IEnumerable<float> droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.FloatEnumerable

get

Definition at line 112 of file EulerTransformSensor.cs.

◆ Position

          Vector3 droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.Position

getset

Definition at line 61 of file EulerTransformSensor.cs.

◆ PositionSpace

          Space3 droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.PositionSpace

get

Definition at line 85 of file EulerTransformSensor.cs.

◆ PrototypingTypeName

          override string droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.PrototypingTypeName

get

Definition at line 56 of file EulerTransformSensor.cs.

◆ Rotation

          Vector3 droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.Rotation

getset

Definition at line 73 of file EulerTransformSensor.cs.

◆ RotationSpace

          Space3 droid.Runtime.Prototyping.Sensors.Transform.EulerTransformSensor.RotationSpace = new Space3()

get

Definition at line 95 of file EulerTransformSensor.cs.

The documentation for this class was generated from the following file:

/home/heider/Projects/Neodroid/Unity/Examples/Assets/droid/Runtime/Prototyping/Sensors/Transform/EulerTransformSensor.cs

droid

Runtime

Prototyping

Sensors

Transform

EulerTransformSensor

Generated by

     1.8.13


text:
package org.codejargon.fluentjdbc.internal.query;

import java.sql.PreparedStatement;
import java.sql.SQLException;

@FunctionalInterface
public interface QueryRunnerPreparedStatement<T> {
    T run(PreparedStatement c) throws SQLException;
}


text:
package sqlite

import (
	"bytes"
	"database/sql"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"

	"camlistore.org/pkg/sorted"
)

const requiredSchemaVersion = 1

func SchemaVersion() int {
	return requiredSchemaVersion
}

func SQLCreateTables() []string {
	// sqlite ignores n in VARCHAR(n), but setting it as such for consistency with
	// other sqls.
	return []string{
		`CREATE TABLE rows (
 k VARCHAR(` + strconv.Itoa(sorted.MaxKeySize) + `) NOT NULL PRIMARY KEY,
 v VARCHAR(` + strconv.Itoa(sorted.MaxValueSize) + `))`,

		`CREATE TABLE meta (
 metakey VARCHAR(255) NOT NULL PRIMARY KEY,
 value VARCHAR(255) NOT NULL)`,
	}
}

// IsWALCapable checks if the installed sqlite3 library can
// use Write-Ahead Logging (i.e version >= 3.7.0)
func IsWALCapable() bool {
	// TODO(mpl): alternative to make it work on windows
	cmdPath, err := exec.LookPath("pkg-config")
	if err != nil {
		log.Printf("Could not find pkg-config to check sqlite3 lib version: %v", err)
		return false
	}
	var stderr bytes.Buffer
	cmd := exec.Command(cmdPath, "--modversion", "sqlite3")
	cmd.Stderr = &stderr
	if runtime.GOOS == "darwin" && os.Getenv("PKG_CONFIG_PATH") == "" {
		matches, err := filepath.Glob("/usr/local/Cellar/sqlite/*/lib/pkgconfig/sqlite3.pc")
		if err == nil && len(matches) > 0 {
			cmd.Env = append(os.Environ(), "PKG_CONFIG_PATH="+filepath.Dir(matches[0]))
		}
	}

	out, err := cmd.Output()
	if err != nil {
		log.Printf("Could not check sqlite3 version: %v\n", stderr.String())
		return false
	}
	version := strings.TrimRight(string(out), "\n")
	return version >= "3.7.0"
}

// EnableWAL returns the statement to enable Write-Ahead Logging,
// which improves SQLite concurrency.
// Requires SQLite >= 3.7.0
func EnableWAL() string {
	return "PRAGMA journal_mode = WAL"
}

// initDB creates a new sqlite database based on the file at path.
func initDB(path string) error {
	db, err := sql.Open("sqlite3", path)
	if err != nil {
		return err
	}
	defer db.Close()
	for _, tableSql := range SQLCreateTables() {
		if _, err := db.Exec(tableSql); err != nil {
			return err
		}
	}
	if IsWALCapable() {
		if _, err := db.Exec(EnableWAL()); err != nil {
			return err
		}
	} else {
		log.Print("WARNING: An SQLite DB without Write Ahead Logging will most likely fail. See http://camlistore.org/issues/114")
	}
	_, err = db.Exec(fmt.Sprintf(`REPLACE INTO meta VALUES ('version', '%d')`, SchemaVersion()))
	return err
}


text:
//
//  CDAResourcesCollectionViewController.h
//  ContentfulSDK
//
//  Created by Boris Bügling on 19/03/14.
//
//

#if __has_feature(modules)
@import UIKit;
#else
#import <UIKit/UIKit.h>
#endif

#import <ContentfulDeliveryAPI/CDAClient.h>

/**
 The `CDAResourcesCollectionViewController` makes it easy to display content from different kinds
 of Resources in an `UICollectionView`.
 */
@interface CDAResourcesCollectionViewController : UICollectionViewController

/** @name Initializing the CDAResourcesCollectionViewController Object */

/**
*  Initializes a new instance with the given cell mapping. The cell mapping is a dictionary, containing
*  keypaths to properties on each cell and mapping them to Field identifiers. This is used for
*  automatically filling new cells with data from the Resources.
*
*  Example:
*
*  `@{ @"textLabel.text": @"fields.name" }`
*
*  This will set the text of each cell's `textLabel` to the corresponding Entry's value of Field `name`.
*
*  @param layout      The layout to be used for the collection view.
*  @param cellMapping Mapping between cell properties and Resource content.
*
*  @return An initialized `CDAResourcesCollectionViewController` or `nil` if the object
*  couldn't be created.
*/
-(id __nullable)initWithCollectionViewLayout:(UICollectionViewLayout * __nonnull)layout
                      cellMapping:(NSDictionary* __nonnull)cellMapping;

/** @name Access Displayed Data */

/** The items which are currently displayed in this view controller's table view. */
@property (nonatomic, readonly) NSArray* __nullable items;

/** @name Configure Data to Fetch */

/**
 The client which is used to fetch Resources. Make sure to set it before displaying the view
 controller's view or an exception will be thrown unless `initWithCellMapping:items:` was used to
 initialize this view controller.

 The client is not retained.
 */
@property (nonatomic, weak) CDAClient* __nullable client;

/** Locale to use when querying Resources. */
@property (nonatomic, copy) NSString* __nullable locale;

/**
 The query parameters used for fetching Resources. By default, all Resources from the Space associated
 with the client will be fetched.
 */
@property (nonatomic) NSDictionary* __nullable query;

/** The type of Resources which ought to be fetched. */
@property (nonatomic) CDAResourceType resourceType;

/**
 Activate the built-in support for caching Resources offline.

 The cached data will only be used if the device is truly offline, use a `CDASyncedSpace` instead for
 general purpose caching.
 */
@property (nonatomic) BOOL offlineCaching;

/** @name Configure Appearance */

/**
 Configure whether or not to show a search bar.

 The query will be handled automatically, by utilizing the full-text search of Contentful.
 */
@property (nonatomic) BOOL showSearchBar;

/** @name Configuring behaviour in Subclasses */

/**
 The collection view's data source is configured to return cells of this class. If you wish to use your
 own `UICollectionViewCell` subclass, override this method in your subclass of
 `CDAResourcesCollectionViewController`.
 */
+(Class __nonnull)cellClass;

/**
 *  By default, errors related to requests made to the Contentful API will be displayed in a
 *  `UIAlertView`. You can override this method in your subclass if you want to implement different
 *  behaviour.
 *
 *  @param error The error which occured.
 */
-(void)showError:(NSError* __nonnull)error;

@end