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

namespace WebservicesIntegrationTests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Newtonsoft.Json.Linq;

    using NUnit.Framework;

    [TestFixture]
    public class ParameterGroupTestFixture : WebClientTestFixtureBaseWithDatabaseRestore
    {
        [Test]
        [Category("GET")]
        public void VerifyThatExpectedParameterGroupIsReturnedFromWebApi()
        {
            // define the URI on which to perform a GET request
            var parameterGroupUri = new Uri($"{this.Settings.Hostname}/EngineeringModel/9ec982e4-ef72-4953-aa85-b158a95d8d56/iteration/e163c5ad-f32b-4387-b805-f4b34600bc2c/element/f73860b2-12f0-43e4-b8b2-c81862c0a159/parameterGroup");

            // get a response from the data-source as a JArray (JSON Array)
            var jArray = this.WebClient.GetDto(parameterGroupUri);

            // check if there is the only one ParameterGroup object
            Assert.AreEqual(1, jArray.Count);

            // get a specific ParameterGroup from the result by it's unique id
            var parameterGroup = jArray.Single(x => (string)x[PropertyNames.Iid] == "b739b3c6-9cc0-4e64-9cc4-ef7463edf559");

            ParameterGroupTestFixture.VerifyProperties(parameterGroup);
        }

        [Test]
        [Category("GET")]
        public void VerifyThatExpectedParameterGroupWithContainerIsReturnedFromWebApi()
        {
            // define the URI on which to perform a GET request
            var parameterGroupUri = new Uri($"{this.Settings.Hostname}/EngineeringModel/9ec982e4-ef72-4953-aa85-b158a95d8d56/iteration/e163c5ad-f32b-4387-b805-f4b34600bc2c/element/f73860b2-12f0-43e4-b8b2-c81862c0a159/parameterGroup?includeAllContainers=true");

            // get a response from the data-source as a JArray (JSON Array)
            var jArray = this.WebClient.GetDto(parameterGroupUri);

            // check if there are 4 objects
            Assert.AreEqual(4, jArray.Count);

            // get a specific Iteration from the result by it's unique id
            var iteration = jArray.Single(x => (string)x[PropertyNames.Iid] == "e163c5ad-f32b-4387-b805-f4b34600bc2c");
            IterationTestFixture.VerifyProperties(iteration);

            // get a specific ElementDefinition from the result by it's unique id
            ElementDefinitionTestFixture.VerifyProperties(jArray);

            // get a specific ParameterGroup from the result by it's unique id
            var parameterGroup = jArray.Single(x => (string)x[PropertyNames.Iid] == "b739b3c6-9cc0-4e64-9cc4-ef7463edf559");
            ParameterGroupTestFixture.VerifyProperties(parameterGroup);
        }

        [Test]
        [Category("POST")]
        public void VerifyThatParameterGroupCanBeDeletedAndContainedParametersReturnedFromWebApi()
        {
            var iterationUri = new Uri($"{this.Settings.Hostname}/EngineeringModel/9ec982e4-ef72-4953-aa85-b158a95d8d56/iteration/e163c5ad-f32b-4387-b805-f4b34600bc2c");
            var postBodyPath = this.GetPath("Tests/EngineeringModel/ParameterGroup/PostDeleteParameterGroup.json");

            var postBody = this.GetJsonFromFile(postBodyPath);
            var jArray = this.WebClient.PostDto(iterationUri, postBody);

            // check if there are appropriate amount of objects
            Assert.AreEqual(3, jArray.Count);

            var engineeeringModel = jArray.Single(x => (string)x[PropertyNames.Iid] == "9ec982e4-ef72-4953-aa85-b158a95d8d56");
            Assert.AreEqual(2, (int)engineeeringModel[PropertyNames.RevisionNumber]);

            // get a specific ElementDefinition from the result by it's unique id
            var elementDefinition = jArray.Single(x => (string)x[PropertyNames.Iid] == "f73860b2-12f0-43e4-b8b2-c81862c0a159");
            Assert.AreEqual(2, (int)elementDefinition[PropertyNames.RevisionNumber]);
            var expectedParameterGroups = new string[] { };
            var parameterGroupsArray = (JArray)elementDefinition[PropertyNames.ParameterGroup];
            IList<string> parameterGroups = parameterGroupsArray.Select(x => (string)x).ToList();
            CollectionAssert.AreEquivalent(expectedParameterGroups, parameterGroups);

            // get a specific Parameter from the result by it's unique id
            var parameter = jArray.Single(x => (string)x[PropertyNames.Iid] == "6c5aff74-f983-4aa8-a9d6-293b3429307c");
            Assert.AreEqual(2, (int)parameter[PropertyNames.RevisionNumber]);
            Assert.IsNull((string)parameter[PropertyNames.Group]);
        }

        /// <summary>
        /// Verifies all properties of the ParameterGroup <see cref="JToken"/>
        /// </summary>
        /// <param name="parameterGroup">
        /// The <see cref="JToken"/> that contains the properties of
        /// the ParameterGroup object
        /// </param>
        public static void VerifyProperties(JToken parameterGroup)
        {
            // verify the amount of returned properties
            Assert.AreEqual(5, parameterGroup.Children().Count());

            // assert that the properties are what is expected
            Assert.AreEqual("b739b3c6-9cc0-4e64-9cc4-ef7463edf559", (string)parameterGroup[PropertyNames.Iid]);
            Assert.AreEqual(1, (int)parameterGroup[PropertyNames.RevisionNumber]);
            Assert.AreEqual("ParameterGroup", (string)parameterGroup[PropertyNames.ClassKind]);

            Assert.AreEqual("Test ParameterGroup", (string)parameterGroup[PropertyNames.Name]);
            Assert.IsNull((string)parameterGroup[PropertyNames.ContainingGroup]);
        }
    }
}


text:
<title>M32C-Opts - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="M32C_002dDependent.html#M32C_002dDependent" title="M32C-Dependent">
<link rel="next" href="M32C_002dModifiers.html#M32C_002dModifiers" title="M32C-Modifiers">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: M32C-Modifiers,
Up: M32C-Dependent

9.19.1 M32C Options

The Renesas M32C version of as has these
machine-dependent options:

-m32c
Assemble M32C instructions.

-m16c
Assemble M16C instructions (default).

-relax
Enable support for link-time relaxations.

-h-tick-hex
Support H'00 style hex constants in addition to 0x00 style.

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"
#include "core/dom/DocumentLifecycle.h"

#include "platform/RuntimeEnabledFeatures.h"
#include "wtf/Assertions.h"

namespace blink {

static DocumentLifecycle::DeprecatedTransition* s_deprecatedTransitionStack = 0;

DocumentLifecycle::Scope::Scope(DocumentLifecycle& lifecycle, State finalState)
    : m_lifecycle(lifecycle)
    , m_finalState(finalState)
{
}

DocumentLifecycle::Scope::~Scope()
{
    m_lifecycle.advanceTo(m_finalState);
}

DocumentLifecycle::DeprecatedTransition::DeprecatedTransition(State from, State to)
    : m_previous(s_deprecatedTransitionStack)
    , m_from(from)
    , m_to(to)
{
    s_deprecatedTransitionStack = this;
}

DocumentLifecycle::DeprecatedTransition::~DeprecatedTransition()
{
    s_deprecatedTransitionStack = m_previous;
}

DocumentLifecycle::DocumentLifecycle()
    : m_state(Uninitialized)
    , m_detachCount(0)
{
}

DocumentLifecycle::~DocumentLifecycle()
{
}

#if ENABLE(ASSERT)

bool DocumentLifecycle::canAdvanceTo(State nextState) const
{
    // We can stop from anywhere.
    if (nextState == Stopping)
        return true;

    switch (m_state) {
    case Uninitialized:
        return nextState == Inactive;
    case Inactive:
        if (nextState == StyleClean)
            return true;
        if (nextState == Disposed)
            return true;
        break;
    case VisualUpdatePending:
        if (nextState == InPreLayout)
            return true;
        if (nextState == InStyleRecalc)
            return true;
        if (nextState == InPerformLayout)
            return true;
        break;
    case InStyleRecalc:
        return nextState == StyleClean;
    case StyleClean:
        // We can synchronously recalc style.
        if (nextState == InStyleRecalc)
            return true;
        // We can notify layout objects that subtrees changed.
        if (nextState == InLayoutSubtreeChange)
            return true;
        // We can synchronously perform layout.
        if (nextState == InPreLayout)
            return true;
        if (nextState == InPerformLayout)
            return true;
        // We can redundant arrive in the style clean state.
        if (nextState == StyleClean)
            return true;
        if (nextState == LayoutClean)
            return true;
        if (nextState == InCompositingUpdate)
            return true;
        break;
    case InLayoutSubtreeChange:
        return nextState == LayoutSubtreeChangeClean;
    case LayoutSubtreeChangeClean:
        // We can synchronously recalc style.
        if (nextState == InStyleRecalc)
            return true;
        // We can synchronously perform layout.
        if (nextState == InPreLayout)
            return true;
        if (nextState == InPerformLayout)
            return true;
        // Can move back to style clean.
        if (nextState == StyleClean)
            return true;
        if (nextState == LayoutClean)
            return true;
        if (nextState == InCompositingUpdate)
            return true;
        break;
    case InPreLayout:
        if (nextState == InStyleRecalc)
            return true;
        if (nextState == StyleClean)
            return true;
        if (nextState == InPreLayout)
            return true;
        break;
    case InPerformLayout:
        return nextState == AfterPerformLayout;
    case AfterPerformLayout:
        // We can synchronously recompute layout in AfterPerformLayout.
        // FIXME: Ideally, we would unnest this recursion into a loop.
        if (nextState == InPreLayout)
            return true;
        if (nextState == LayoutClean)
            return true;
        break;
    case LayoutClean:
        // We can synchronously recalc style.
        if (nextState == InStyleRecalc)
            return true;
        // We can synchronously perform layout.
        if (nextState == InPreLayout)
            return true;
        if (nextState == InPerformLayout)
            return true;
        // We can redundant arrive in the layout clean state. This situation
        // can happen when we call layout recursively and we unwind the stack.
        if (nextState == LayoutClean)
            return true;
        if (nextState == StyleClean)
            return true;
        if (nextState == InCompositingUpdate)
            return true;
        break;
    case InCompositingUpdate:
        return nextState == CompositingClean;
    case CompositingClean:
        if (nextState == InStyleRecalc)
            return true;
        if (nextState == InPreLayout)
            return true;
        if (nextState == InCompositingUpdate)
            return true;
        if (nextState == InPaintInvalidation)
            return true;
        break;
    case InPaintInvalidation:
        return nextState == PaintInvalidationClean;
    case PaintInvalidationClean:
        if (nextState == InStyleRecalc)
            return true;
        if (nextState == InPreLayout)
            return true;
        if (nextState == InCompositingUpdate)
            return true;
        if (nextState == InPaintForSlimmingPaintV2 && RuntimeEnabledFeatures::slimmingPaintV2Enabled())
            return true;
        break;
    case InPaintForSlimmingPaintV2:
        if (nextState == PaintForSlimmingPaintV2Clean && RuntimeEnabledFeatures::slimmingPaintV2Enabled())
            return true;
        break;
    case PaintForSlimmingPaintV2Clean:
        if (nextState == InCompositingForSlimmingPaintV2 && RuntimeEnabledFeatures::slimmingPaintV2Enabled())
            return true;
        break;
    case InCompositingForSlimmingPaintV2:
        if (nextState == CompositingForSlimmingPaintV2Clean && RuntimeEnabledFeatures::slimmingPaintV2Enabled())
            return true;
        break;
    case CompositingForSlimmingPaintV2Clean:
        if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled())
            return false;
        if (nextState == InStyleRecalc)
            return true;
        if (nextState == InPreLayout)
            return true;
        if (nextState == InCompositingUpdate)
            return true;
        if (nextState == CompositingForSlimmingPaintV2Clean)
            return true;
        break;
    case Stopping:
        return nextState == Stopped;
    case Stopped:
        return nextState == Disposed;
    case Disposed:
        // FIXME: We can dispose a document multiple times. This seems wrong.
        // See https://code.google.com/p/chromium/issues/detail?id=301668.
        return nextState == Disposed;
    }
    return false;
}

bool DocumentLifecycle::canRewindTo(State nextState) const
{
    // This transition is bogus, but we've whitelisted it anyway.
    if (s_deprecatedTransitionStack && m_state == s_deprecatedTransitionStack->from() && nextState == s_deprecatedTransitionStack->to())
        return true;
    return m_state == StyleClean
        || m_state == LayoutSubtreeChangeClean
        || m_state == AfterPerformLayout
        || m_state == LayoutClean
        || m_state == CompositingClean
        || m_state == PaintInvalidationClean
        || (m_state == PaintForSlimmingPaintV2Clean && RuntimeEnabledFeatures::slimmingPaintV2Enabled())
        || (m_state == CompositingForSlimmingPaintV2Clean && RuntimeEnabledFeatures::slimmingPaintV2Enabled());
}

#endif

void DocumentLifecycle::advanceTo(State nextState)
{
    ASSERT(canAdvanceTo(nextState));
    m_state = nextState;
}

void DocumentLifecycle::rewindTo(State state)
{
    m_state = state;
}

void DocumentLifecycle::ensureStateAtMost(State state)
{
    ASSERT(state == VisualUpdatePending || state == StyleClean || state == LayoutClean);
    if (m_state <= state)
        return;
    ASSERT(canRewindTo(state));
    m_state = state;
}

}


text:
package org.waveprotocol.wave.client.common.safehtml;

//NOTE: In the near future, the files in this package will be open sourced as
//part of a different project. Do not rely on them staying here.

/**
 * A string wrapped as an object of type {@link SafeHtml}.
 *
 * <p>This class is package-private and intended for internal use by the
 * {@link org.waveprotocol.wave.client.common.safehtml} package.
 */
class SafeHtmlString implements SafeHtml {
  private String html;

  /**
   * Constructs a {@link SafeHtmlString} from a string.  Callers are responsible for ensuring that
   * the string passed as the argument to this constructor satisfies the constraints of the contract
   * imposed by the {@link SafeHtml} interface.
   *
   * @param html the string to be wrapped as a {@link SafeHtml}
   */
  SafeHtmlString(String html) {
    this.html = html;
  }

  /**
   * No-arg constructor for compatibility with GWT serialization.
   */
  SafeHtmlString() {
  }

  /** {@inheritDoc} */
  @Override
  public String asString() {
    return html;
  }
}


text:
<?php

namespace jambroo\aws\view\helper;

use Yii;

use Aws\Common\Aws;
use Aws\S3\S3Client;
use Aws\S3\BucketStyleListener;
use Guzzle\Common\Event;

use jambroo\aws\view\exception\InvalidDomainNameException;

/**
 * View helper that can render a link to a S3 object. It can also create signed URLs
 *
 * @author James Brooking <jambroo@gmail.com>
 * @since 1.0
 */
class S3Link extends AbstractLinkHelper
{
    /**
     * @var S3Client
     */
    protected $client;

    /**
     * @var string
     */
    protected $defaultBucket = '';

    /**
     * @param S3Client $client
     */
    public function __construct(S3Client $client)
    {
        $this->client = $client;
    }

    /**
     * Set the default bucket to use if none is provided
     *
     * @param string $defaultBucket
     *
     * @return self
     */
    public function setDefaultBucket($defaultBucket)
    {
        $this->defaultBucket = (string) $defaultBucket;

        return $this;
    }

    /**
     * Get the default bucket to use if none is provided
     *
     * @return string
     */
    public function getDefaultBucket()
    {
        return $this->defaultBucket;
    }

    /**
     * Create a link to a S3 object from a bucket. If expiration is not empty, then it is used to create
     * a signed URL
     *
     * @param  string     $object The object name (full path)
     * @param  string     $bucket The bucket name
     * @param  string|int $expiration The Unix timestamp to expire at or a string that can be evaluated by strtotime
     * @throws InvalidDomainNameException
     * @return string
     */
    public function __invoke($object, $bucket = '', $expiration = '')
    {
        $bucket = trim($bucket ?: $this->getDefaultBucket(), '/');
        if (empty($bucket)) {
            throw new InvalidDomainNameException('An empty bucket name was given');
        }

        // Create a command representing the get request
        // Using a command will make sure the configured regional endpoint is used
        $command = $this->client->getCommand('GetObject', array(
            'Bucket' => $bucket,
            'Key'    => $object,
        ));

        // Instead of executing the command, retrieve the request and make sure the scheme is set to what was specified
        $request = $command->prepare()->setScheme($this->getScheme())->setPort(null);

        // Ensure that the correct bucket URL style (virtual or path) is used based on the bucket name
        // This addresses a bug in versions of the SDK less than or equal to 2.3.4
        // @codeCoverageIgnoreStart
        if (version_compare(Aws::VERSION, '2.4.0', '<') && strpos($request->getHost(), $bucket) === false) {
            $bucketStyleListener = new BucketStyleListener();
            $bucketStyleListener->onCommandBeforeSend(new Event(array('command' => $command)));
        }
        // @codeCoverageIgnoreEnd

        if ($expiration) {
            return $this->client->createPresignedUrl($request, $expiration);
        } else {
            return $request->getUrl();
        }
    }
}


text:
<?php

namespace ZfrEbWorkerTest\Message;

use ZfrEbWorker\Message\DelayedMessage;

class DelayedMessageTest extends \PHPUnit_Framework_TestCase
{
    public function testMessage()
    {
        $message = new DelayedMessage('test', ['foo' => 'bar'], 15);

        $this->assertEquals('test', $message->getName());
        $this->assertEquals(['foo' => 'bar'], $message->getPayload());
        $this->assertEquals(15, $message->getDelay());
    }
}


text:
package org.wso2.carbon.apimgt.gateway.utils;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder;
import org.wso2.carbon.localentry.LocalEntryAdminException;
import org.wso2.carbon.localentry.service.LocalEntryAdmin;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import java.util.Arrays;

/**
 * This LocalEntryServiceProxy class for operating the synapse localEntries
 */
public class LocalEntryServiceProxy {

    private LocalEntryAdmin localEntryAdmin;

    private String tenantDomain;

    public LocalEntryServiceProxy(String tenantDomain) {

        this.tenantDomain = tenantDomain;
        localEntryAdmin = ServiceReferenceHolder.getInstance().getLocalEntryAdmin();
    }

    /**
     * Add Local entry
     *
     * @param content Swagger Content
     * @return Status of the add operation
     * @throws AxisFault
     */
    public Boolean addLocalEntry(String content) throws AxisFault {

        Boolean value;
        try {
            if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                value = localEntryAdmin.addEntry(content);
            } else {
                value = localEntryAdmin.addEntryForTenant(content, tenantDomain);
            }
        } catch (org.wso2.carbon.localentry.LocalEntryAdminException e) {
            throw new AxisFault("Error occurred while adding the local entry", e);
        }
        return value;
    }

    /**
     * Get Local entry for given API
     *
     * @param key API Id to be retrived
     * @return LocalEntry for the given API
     * @throws AxisFault
     */
    public Object getEntry(String key) throws AxisFault {

        Object localEntryObject;
        try {
            if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                localEntryObject = localEntryAdmin.getEntry(key);
            } else {
                localEntryObject = localEntryAdmin.getEntryForTenant(key, tenantDomain);
            }
        } catch (LocalEntryAdminException e) {
            throw new AxisFault("Error occurred while create the admin client", e);
        }
        return localEntryObject;
    }

    /**
     * Delete the local entry
     *
     * @param key APT Id to be deleted
     * @return Stataus of the delete operation
     * @throws AxisFault
     */
    public boolean deleteEntry(String key) throws AxisFault {

        try {
            if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                return localEntryAdmin.deleteEntry(key);
            } else {
                return localEntryAdmin.deleteEntryForTenant(key, tenantDomain);
            }
        } catch (LocalEntryAdminException e) {
            throw new AxisFault("Error occurred while deleting the local entry", e);
        }
    }

    /**
     * Check local Entry Existence
     *
     * @param key
     * @return
     * @throws AxisFault
     */
    public boolean isEntryExists(String key) throws AxisFault {

        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            try {
                return localEntryAdmin.isEntryExist(key);
            } catch (LocalEntryAdminException e) {
                return false;
            }
        } else {
            try {
                return localEntryAdmin.isEntryExistForTenant(key, tenantDomain);
            } catch (LocalEntryAdminException e) {
                return false;
            }
        }
    }
}


text:
package com.google.android.exoplayer2.upstream.cache;

import android.util.Log;
import android.util.SparseArray;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.upstream.cache.Cache.CacheException;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.AtomicFile;
import com.google.android.exoplayer2.util.ReusableBufferedOutputStream;
import com.google.android.exoplayer2.util.Util;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * This class maintains the index of cached content.
 */
/*package*/ class CachedContentIndex {

  public static final String FILE_NAME = "cached_content_index.exi";

  private static final int VERSION = 1;

  private static final int FLAG_ENCRYPTED_INDEX = 1;

  private static final String TAG = "CachedContentIndex";

  private final HashMap<String, CachedContent> keyToContent;
  private final SparseArray<String> idToKey;
  private final AtomicFile atomicFile;
  private final Cipher cipher;
  private final SecretKeySpec secretKeySpec;
  private final boolean encrypt;
  private boolean changed;
  private ReusableBufferedOutputStream bufferedOutputStream;

  /**
   * Creates a CachedContentIndex which works on the index file in the given cacheDir.
   *
   * @param cacheDir Directory where the index file is kept.
   */
  public CachedContentIndex(File cacheDir) {
    this(cacheDir, null);
  }

  /**
   * Creates a CachedContentIndex which works on the index file in the given cacheDir.
   *
   * @param cacheDir Directory where the index file is kept.
   * @param secretKey 16 byte AES key for reading and writing the cache index.
   */
  public CachedContentIndex(File cacheDir, byte[] secretKey) {
    this(cacheDir, secretKey, secretKey != null);
  }

  /**
   * Creates a CachedContentIndex which works on the index file in the given cacheDir.
   *
   * @param cacheDir Directory where the index file is kept.
   * @param secretKey 16 byte AES key for reading, and optionally writing, the cache index.
   * @param encrypt When false, a plaintext index will be written.
   */
  public CachedContentIndex(File cacheDir, byte[] secretKey, boolean encrypt) {
    this.encrypt = encrypt;
    if (secretKey != null) {
      Assertions.checkArgument(secretKey.length == 16);
      try {
        cipher = getCipher();
        secretKeySpec = new SecretKeySpec(secretKey, "AES");
      } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new IllegalStateException(e); // Should never happen.
      }
    } else {
      cipher = null;
      secretKeySpec = null;
    }
    keyToContent = new HashMap<>();
    idToKey = new SparseArray<>();
    atomicFile = new AtomicFile(new File(cacheDir, FILE_NAME));
  }

  /** Loads the index file. */
  public void load() {
    Assertions.checkState(!changed);
    if (!readFile()) {
      atomicFile.delete();
      keyToContent.clear();
      idToKey.clear();
    }
  }

  /** Stores the index data to index file if there is a change. */
  public void store() throws CacheException {
    if (!changed) {
      return;
    }
    writeFile();
    changed = false;
  }

  /**
   * Adds the given key to the index if it isn't there already.
   *
   * @param key The cache key that uniquely identifies the original stream.
   * @return A new or existing CachedContent instance with the given key.
   */
  public CachedContent add(String key) {
    CachedContent cachedContent = keyToContent.get(key);
    if (cachedContent == null) {
      cachedContent = addNew(key, C.LENGTH_UNSET);
    }
    return cachedContent;
  }

  /** Returns a CachedContent instance with the given key or null if there isn't one. */
  public CachedContent get(String key) {
    return keyToContent.get(key);
  }

  /**
   * Returns a Collection of all CachedContent instances in the index. The collection is backed by
   * the {@code keyToContent} map, so changes to the map are reflected in the collection, and
   * vice-versa. If the map is modified while an iteration over the collection is in progress
   * (except through the iterator's own remove operation), the results of the iteration are
   * undefined.
   */
  public Collection<CachedContent> getAll() {
    return keyToContent.values();
  }

  /** Returns an existing or new id assigned to the given key. */
  public int assignIdForKey(String key) {
    return add(key).id;
  }

  /** Returns the key which has the given id assigned. */
  public String getKeyForId(int id) {
    return idToKey.get(id);
  }

  /**
   * Removes {@link CachedContent} with the given key from index. It shouldn't contain any spans.
   *
   * @throws IllegalStateException If {@link CachedContent} isn't empty.
   */
  public void removeEmpty(String key) {
    CachedContent cachedContent = keyToContent.remove(key);
    if (cachedContent != null) {
      Assertions.checkState(cachedContent.isEmpty());
      idToKey.remove(cachedContent.id);
      changed = true;
    }
  }

  /** Removes empty {@link CachedContent} instances from index. */
  public void removeEmpty() {
    LinkedList<String> cachedContentToBeRemoved = new LinkedList<>();
    for (CachedContent cachedContent : keyToContent.values()) {
      if (cachedContent.isEmpty()) {
        cachedContentToBeRemoved.add(cachedContent.key);
      }
    }
    for (String key : cachedContentToBeRemoved) {
      removeEmpty(key);
    }
  }

  /**
   * Returns a set of all content keys. The set is backed by the {@code keyToContent} map, so
   * changes to the map are reflected in the set, and vice-versa. If the map is modified while an
   * iteration over the set is in progress (except through the iterator's own remove operation), the
   * results of the iteration are undefined.
   */
  public Set<String> getKeys() {
    return keyToContent.keySet();
  }

  /**
   * Sets the content length for the given key. A new {@link CachedContent} is added if there isn't
   * one already with the given key.
   */
  public void setContentLength(String key, long length) {
    CachedContent cachedContent = get(key);
    if (cachedContent != null) {
      if (cachedContent.getLength() != length) {
        cachedContent.setLength(length);
        changed = true;
      }
    } else {
      addNew(key, length);
    }
  }

  /**
   * Returns the content length for the given key if one set, or {@link
   * com.google.android.exoplayer2.C#LENGTH_UNSET} otherwise.
   */
  public long getContentLength(String key) {
    CachedContent cachedContent = get(key);
    return cachedContent == null ? C.LENGTH_UNSET : cachedContent.getLength();
  }

  private boolean readFile() {
    DataInputStream input = null;
    try {
      InputStream inputStream = new BufferedInputStream(atomicFile.openRead());
      input = new DataInputStream(inputStream);
      int version = input.readInt();
      if (version != VERSION) {
        // Currently there is no other version
        return false;
      }

      int flags = input.readInt();
      if ((flags & FLAG_ENCRYPTED_INDEX) != 0) {
        if (cipher == null) {
          return false;
        }
        byte[] initializationVector = new byte[16];
        input.readFully(initializationVector);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initializationVector);
        try {
          cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
          throw new IllegalStateException(e);
        }
        input = new DataInputStream(new CipherInputStream(inputStream, cipher));
      } else {
        if (cipher != null) {
          changed = true; // Force index to be rewritten encrypted after read.
        }
      }

      int count = input.readInt();
      int hashCode = 0;
      for (int i = 0; i < count; i++) {
        CachedContent cachedContent = new CachedContent(input);
        add(cachedContent);
        hashCode += cachedContent.headerHashCode();
      }
      if (input.readInt() != hashCode) {
        return false;
      }
    } catch (FileNotFoundException e) {
      return false;
    } catch (IOException e) {
      Log.e(TAG, "Error reading cache content index file.", e);
      return false;
    } finally {
      if (input != null) {
        Util.closeQuietly(input);
      }
    }
    return true;
  }

  private void writeFile() throws CacheException {
    DataOutputStream output = null;
    try {
      OutputStream outputStream = atomicFile.startWrite();
      if (bufferedOutputStream == null) {
        bufferedOutputStream = new ReusableBufferedOutputStream(outputStream);
      } else {
        bufferedOutputStream.reset(outputStream);
      }
      output = new DataOutputStream(bufferedOutputStream);
      output.writeInt(VERSION);

      boolean writeEncrypted = encrypt && cipher != null;
      int flags = writeEncrypted ? FLAG_ENCRYPTED_INDEX : 0;
      output.writeInt(flags);

      if (writeEncrypted) {
        byte[] initializationVector = new byte[16];
        new Random().nextBytes(initializationVector);
        output.write(initializationVector);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initializationVector);
        try {
          cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
          throw new IllegalStateException(e); // Should never happen.
        }
        output.flush();
        output = new DataOutputStream(new CipherOutputStream(bufferedOutputStream, cipher));
      }

      output.writeInt(keyToContent.size());
      int hashCode = 0;
      for (CachedContent cachedContent : keyToContent.values()) {
        cachedContent.writeToStream(output);
        hashCode += cachedContent.headerHashCode();
      }
      output.writeInt(hashCode);
      atomicFile.endWrite(output);
      // Avoid calling close twice. Duplicate CipherOutputStream.close calls did
      // not used to be no-ops: https://android-review.googlesource.com/#/c/272799/
      output = null;
    } catch (IOException e) {
      throw new CacheException(e);
    } finally {
      Util.closeQuietly(output);
    }
  }

  private void add(CachedContent cachedContent) {
    keyToContent.put(cachedContent.key, cachedContent);
    idToKey.put(cachedContent.id, cachedContent.key);
  }

  /** Adds the given CachedContent to the index. */
  /*package*/ void addNew(CachedContent cachedContent) {
    add(cachedContent);
    changed = true;
  }

  private CachedContent addNew(String key, long length) {
    int id = getNewId(idToKey);
    CachedContent cachedContent = new CachedContent(id, key, length);
    addNew(cachedContent);
    return cachedContent;
  }

  private static Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
    // Workaround for https://issuetracker.google.com/issues/36976726
    if (Util.SDK_INT == 18) {
      try {
        return Cipher.getInstance("AES/CBC/PKCS5PADDING", "BC");
      } catch (Throwable ignored) {
        // ignored
      }
    }
    return Cipher.getInstance("AES/CBC/PKCS5PADDING");
  }

  /**
   * Returns an id which isn't used in the given array. If the maximum id in the array is smaller
   * than {@link java.lang.Integer#MAX_VALUE} it just returns the next bigger integer. Otherwise it
   * returns the smallest unused non-negative integer.
   */
  //@VisibleForTesting
  public static int getNewId(SparseArray<String> idToKey) {
    int size = idToKey.size();
    int id = size == 0 ? 0 : (idToKey.keyAt(size - 1) + 1);
    if (id < 0) { // In case if we pass max int value.
      // TODO optimization: defragmentation or binary search?
      for (id = 0; id < size; id++) {
        if (id != idToKey.keyAt(id)) {
          break;
        }
      }
    }
    return id;
  }

}


text:
help:
	@echo "REQUIREMENTS"
	@echo "  * nginx"
	@echo "  * django"
	@echo "  * supervisor"
	@echo "  * virtual environment"
	@echo ""
	@echo "USAGE"
	@echo "Start:"
	@echo "  - startproject - alternative django-admin.py startproject,"
	@echo "    but creates a project by the django-project-template structure."
	@echo "    ** Create a virtual environment and install Django."
	@echo ""
	@echo "Deploying the project:"
	@echo "  - make deploy - deploy project."
	@echo "    ** Create a configuration file: world/etc/local_settings.sh"
	@echo ""
	@echo "Main commands:"
	@echo "ONLY ON THE DEPLOYED PROJECT"
	@echo "  - make start - to start server."
	@echo "  - make stop - to stop server."
	@echo "  - make restart - to restart server."
	@echo "  - make status - show server status."
	@echo "  - make kill - forced to kill the server processes."
	@echo ""

# Start project.
startproject:
	django-admin.py startproject basic
	mkdir -p ./src/basic
	/bin/cp -rf ./basic/* ./src/
	rm -Rf ./basic

# Main commands:
all: start
runserver: start
start:
	sh ./world/bin/supervisorctl.sh --start

stop:
	sh ./world/bin/supervisorctl.sh --stop
	sh ./world/bin/killserver.sh

status:
	sh ./world/bin/supervisorctl.sh --status

forcekill: kill
kill:
	sh ./world/bin/killserver.sh

restart: stop start

forcestart:
	sh ./world/etc/init.d/runserver.sh

cleardebris:
	sh ./world/bin/cleardebris.sh

# Deploying the project:
deploy:
	sh ./world/bin/createconfigs.sh

lesscompiler:
	sh ./world/bin/lesscompiler.sh lib/ library/ import/ imports/ fonts/


text:
import React, {PropTypes} from 'react'
import LoginManager from './LoginManager'
import * as DataUtils from '../client_data'
import {getCookieByName} from '../utils'
import {checkIdentity} from '../../../electron/ipc_render'
import {SUPPORT_PLATFORM_MAP} from '../../helpers/const'

const platform = SUPPORT_PLATFORM_MAP.zhihu
const PLATFORM_NAME = platform.name
const PLATFORM_LABEL = platform.label

function transformCookie(cookie) {
  let token = getCookieByName(cookie, platform.csrfTokenName.replace('X-', ''))
  if (!token) {
    throw new Error('内部错误:无法获取zhihu的CSRF Token')
  }

  return {
    cookie,
    token
  }
}

function onLoggedIn({cookie, token}, serverJson) {
  let username = serverJson.email || serverJson.name || serverJson.slug
  if (!username) {
    console.error('服务端json返回有误', serverJson)
    return null
  }

  let account = {
    cookie, token, username
  }

  DataUtils.updateAccount(PLATFORM_NAME, account)

  // 没有开通专栏
  let hasColumns = serverJson.columns && serverJson.columns.length > 0
  if (!hasColumns) {
    App.alert('温馨提醒', '当前帐号还没有开通专栏,作品将无法同步请知悉')
  }

  return account
}

export default function createLoginPage(props) {
  return (
    <LoginManager
      {...props}
      platformName={PLATFORM_NAME}
      platformLabel={PLATFORM_LABEL}
      loginUrl={platform.loginUrl}
      logoutUrl={platform.logoutUrl}
      loggedInUrl={platform.loggedInUrl}
      domain={platform.domain}
      whoAmI={checkIdentity}
      onLoggedIn={onLoggedIn}
      transformCookie={transformCookie}
    />
  )
}

createLoginPage.propTypes = {
  states: PropTypes.object.isRequired,
  actions: PropTypes.object.isRequired
}


text:
import FindBy from 'ember-tabular/helpers/find-by';

export default FindBy;


text:
old: This functionality is made obsolete for me by the [sepia](https://github.com/linkedin/sepia) package.

# fxt

...tools for the creation and management of test fixture data.

For example, for use with this app:

`tests/some_app.js`
```
// ...

exports.some_app = {

  get_org: function () {
    var response = Q.defer()
    http.get('http://example.com', function (response_event) {
      //must grab some data to have it loaded into memory
      content = response_event.read()
      response_event.on('end', function () { response.resolve(response_event) })
    }).end()
    return response.promise
  },

  get_org_twice: function () {
    return Q.all([this.get_org(), this.get_org()])
    .then(function (responses) {
      return responses[0].statusCode + responses[1].statusCode
    })
  },

  other_feature: function () {
    //has an unknown integration
    http.get('http://example.com')
  }

}

```

## generate test fixtures as a side effect of integration
(using nock)

`tests/fxtSpec.js`
```
describe('fxt', function () {

  //define the fixture
  some_app.get_org_twice = fxt.feature(some_app.get_org_twice)

  // feature test
  it('creates and replays a fixture to test a feature', function (done) {
    some_app.get_org_twice()
    .then(function (summary) {
      expect(summary).toBe(400)
      done()
    })
  })
```

### archiving test fixtures
```
cp /tmp/fxt/default my_saved_fixture # and sanitize if desired
```


text:
<?php

// EstaticasBundle:Default:servicios.html.twig
return array (
);


text:
"""
Copyright (c) 2016 Gabriel Esteban

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

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

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

from django.conf.urls import url
from django.contrib.auth.decorators import login_required

from main.views import HomeView, RankingProblemsView, RankingUsersView

urlpatterns = [
    url(r'^$', login_required(HomeView.as_view()), name='home'),
    url(r'^ranking/problems$', login_required(RankingProblemsView.as_view()), name='ranking_problems'),
    url(r'^ranking/users', login_required(RankingUsersView.as_view()), name='ranking_users')
]


text:
<?php

namespace App\Http\Middleware;

use Closure;

class Ip
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->ip() == '127.0.0.1') { // TODO: put ip front prod
            return $next($request);
        }
        return response('Unauthorized.', 401);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Mystic.Common.DTO;

namespace Mystic.Common.Parsers
{
    public abstract class DTOParser
    {
        protected sealed class DTOParserCache
        {
            private static readonly Lazy<DTOParserCache> _lazy = new Lazy<DTOParserCache>(() => new DTOParserCache());

            public Dictionary<Type, object> Ordinals = new Dictionary<Type, object>();

            private DTOParserCache()
            {

            }

            public static DTOParserCache Instance { get { return _lazy.Value; } }
        }

        // TODO: Verify performance.
        protected virtual T Populate<T>(IDataReader reader)
        {
            object generic;
            var type = typeof(T);
            if (DTOParserCache.Instance.Ordinals.ContainsKey(type))
            {
                generic = DTOParserCache.Instance.Ordinals[type];
            }
            else
            {
                generic = Activator.CreateInstance<T>();
                foreach (var property in type.GetProperties())
                {
                    int ordinal = reader.GetOrdinal(property.Name);
                    property.SetValue(generic, ordinal, null);
                }
                DTOParserCache.Instance.Ordinals.Add(type, generic);
            }
            return (T)generic;
        }

        public abstract DTOBase PopulateDTO(IDataReader reader);
    }
}


text:
package ru.abelov.collection.iterator;

import java.util.Iterator;

/**
 * Interface IteratorConverter.
 * Realizes how iterator converted should look like.
 */

public interface IteratorConverter {

    /**
     * Converts iterator of integer iterators to iterator of integers.
     * @param it    iterator of integer iterators.
     * @return      iterator of integers.
     */

    Iterator<Integer> convert(Iterator<Iterator<Integer>> it);

}


text:
package com.emc.storageos.model.vpool;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;

import com.emc.storageos.model.RestLinkRep;
import com.emc.storageos.model.StringHashMapEntry;

/**
 * Extends the name related resource to add new fields
 * specifying if the a change to the virtual pool is allowed and
 * the reason if not allowed.
 */
public class VirtualPoolChangeRep extends NamedRelatedVirtualPoolRep {

    private Boolean allowed;
    private String notAllowedReason;
    private List<StringHashMapEntry> allowedChangeOperations;

    public VirtualPoolChangeRep() {
    }

    public VirtualPoolChangeRep(URI id, RestLinkRep selfLink, String name, String virtualPoolType,
            String notAllowedReason, List<VirtualPoolChangeOperationEnum> allowedChangeOperationEnums) {
        super(id, selfLink, name, virtualPoolType);
        this.allowed = allowedChangeOperationEnums != null && !allowedChangeOperationEnums.isEmpty();
        this.notAllowedReason = notAllowedReason;

        if (allowedChangeOperationEnums != null) {
            for (VirtualPoolChangeOperationEnum allowedChangeOperationEnum : allowedChangeOperationEnums) {
                getAllowedChangeOperations().add(
                        new StringHashMapEntry(allowedChangeOperationEnum.name(), allowedChangeOperationEnum.toString()));
            }
        }
    }

    /**
     * Specifies whether or not a virtual pool change is allowed.
     *
     */
    @XmlElement(name = "allowed")
    public Boolean getAllowed() {
        return allowed;
    }

    public void setAllowed(Boolean allowed) {
        this.allowed = allowed;
    }

    /**
     * When not allowed, the reason the virtual pool change is not allowed.
     *
     */
    @XmlElement(name = "not_allowed_reason")
    public String getNotAllowedReason() {
        return notAllowedReason;
    }

    public void setNotAllowedReason(String notAllowedReason) {
        this.notAllowedReason = notAllowedReason;
    }

    /**
     * Get list of allowed change operations
     *
     * @return List of allowed change operations
     */
    @XmlElement(name = "allowed_change_operation")
    public List<StringHashMapEntry> getAllowedChangeOperations() {
        if (allowedChangeOperations == null) {
            allowedChangeOperations = new ArrayList<StringHashMapEntry>();
        }
        return allowedChangeOperations;
    }

    public void setAllowedChangeOperations(List<StringHashMapEntry> allowedOperations) {
        this.allowedChangeOperations = allowedOperations;
    }
}


text:
package com.guddy.android_modular_sample.first;

import android.support.annotation.NonNull;
import android.support.design.widget.TextInputEditText;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bluelinelabs.conductor.Controller;
import com.guddy.android_modular_sample.common.FlowContext;

import au.com.ds.ef.EventEnum;
import au.com.ds.ef.StateEnum;
import au.com.ds.ef.err.LogicViolationError;

public class FirstController extends Controller {
    //region Constants
    private static final String ARG_KEY_LOGIN = "LOGIN";
    //endregion

    //region Fields
    @NonNull
    private final FlowContext mFlowContext;
    //endregion

    //region Bound views
    private TextInputEditText mEditTextLogin;
    //endregion

    //region Constructor
    public FirstController() {
        this(new FlowContext());
    }

    public FirstController(@NonNull final FlowContext poFlowContext) {
        super();
        mFlowContext = poFlowContext;
    }
    //endregion

    //region Controller
    @NonNull
    @Override
    protected View onCreateView(@NonNull final LayoutInflater poInflater, @NonNull final ViewGroup poContainer) {
        final View loView = poInflater.inflate(R.layout.first_controller, poContainer, false);
        mEditTextLogin = (TextInputEditText) loView.findViewById(R.id.FirstController_EditText_Login);
        loView.findViewById(R.id.FirstController_Button_Start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View poView) {
                onClickButtonStart();
            }
        });
        return loView;
    }
    //endregion

    //region User interaction
    private void onClickButtonStart() {
        final String lsLogin = mEditTextLogin.getText().toString();
        if (TextUtils.isEmpty(lsLogin)) {
            mEditTextLogin.setError(getApplicationContext().getString(R.string.login_error));
        } else {
            try {
                mFlowContext.args().putString(ARG_KEY_LOGIN, lsLogin);
                mFlowContext.trigger(Events.loginProvided);
            } catch (final LogicViolationError poLogicViolationError) {
                // does nothing
            }
        }
    }
    //endregion

    //region FSM
    public enum States implements StateEnum {
        WAITING_LOGIN
    }

    public enum Events implements EventEnum {
        loginProvided
    }

    public static String getLogin(@NonNull final FlowContext poFlowContext) {
        return poFlowContext.args().getString(ARG_KEY_LOGIN);
    }
    //endregion
}


text:
[![Code Climate](https://codeclimate.com/github/beorc/scopie_rails/badges/gpa.svg)](https://codeclimate.com/github/beorc/scopie_rails)
[![Build Status](https://travis-ci.org/beorc/scopie_rails.svg?branch=master)](https://travis-ci.org/beorc/scopie_rails)
[![Coverage Status](https://codecov.io/gh/beorc/scopie_rails/branch/master/graph/badge.svg)](https://codecov.io/gh/beorc/scopie_rails)
[![Dependency Status](https://gemnasium.com/beorc/scopie_rails.svg)](https://gemnasium.com/beorc/scopie_rails)
[![Gem Version](https://badge.fury.io/rb/scopie_rails.svg)](https://badge.fury.io/rb/scopie_rails)

A [has_scope](http://github.com/plataformatec/has_scope) alternative: [scopie][s] for Rails.

ScopieRails allows you to map incoming controller parameters to named scopes in your resources through OO design.

Motivation:

* Dedicated class for scopes mapping, so that the logic is isolated and your controller is skinny.
* Ability to override default mapping behavior by definition of a method having the same name as a scope in the scopie class.
* Ability to use the object oriented approach to DRY your custom scopes mapping logic and reuse the scopie class.

Imagine the following model called graduations:

```ruby
class Graduation < ActiveRecord::Base

  scope :featured, -> { where(featured: true) }
  scope :by_degree, -> (degree) { where(degree: degree) }
  scope :by_period, -> (started_at, ended_at) { where('started_at = ? AND ended_at = ?', started_at, ended_at) }

  scope :created_at_greater_than, ->(date) { where('created_at >= ?', date.beginning_of_day) }
  scope :created_at_less_than, ->(date) { where('created_at <= ?', date.end_of_day) }
  scope :updated_at_greater_than, ->(date) { where('updated_at >= ?', date.beginning_of_day) }
  scope :updated_at_less_than, ->(date) { where('updated_at <= ?', date.end_of_day) }

end
```

You can use those named scopes as filters by declaring them on your scopie:

```ruby
class GraduationsScopie < ScopieRails::Base

  has_scope :featured, type: :boolean
  has_scope :by_degree, :by_period

  has_scope :created_at_greater_than, in: :created_at, as: :start_at
  has_scope :created_at_less_than, in: :created_at, as: :end_at

  has_scope :updated_at_greater_than, in: :updated_at, as: :start_at, type: :date
  has_scope :updated_at_less_than, in: :updated_at, as: :end_at, type: :date

  has_scope :page, default: 1
  has_scope :per, default: 30

  def by_period(scope, value, _hash)
    started_at = value[:started_at]
    ended_at = value[:ended_at]

    started_at && ended_at && scope.by_period(started_at, ended_at)
  end

  def created_at_greater_than(scope, value, _hash)
    scope.created_at_greater_than(parse_date(value))
  end

  def created_at_less_than(scope, value, _hash)
    scope.created_at_less_than(parse_date(value))
  end

  def updated_at_greater_than(scope, value, _hash)
    scope.updated_at_greater_than(value)
  end

  def updated_at_less_than(scope, value, _hash)
    scope.updated_at_less_than(value)
  end

  private

  def parse_date(value)
    Date.parse(value)
  end

end
```

Now, if you want to apply them to an specific resource, you just need to call `apply_scopes`:

```ruby
class GraduationsController < ApplicationController
  include ScopieRails::Controller

  def index
    @graduations = apply_scopes(Graduation).all
  end
end
```

Then for each request:

```
/graduations
#=> acts like a normal request

/graduations?featured=true
#=> calls the named scope and bring featured graduations

/graduations?by_period[started_at]=20100701&by_period[ended_at]=20101013
#=> brings graduations in the given period

/graduations?created_at[start_at]=2016-06-01&created_at[end_at]=2016-06-02
#=> brings graduations created in the given period

/graduations?featured=true&by_degree=phd
#=> brings featured graduations with phd degree
```

## Installation

Add `scopie_rails` to your Gemfile or install it from Rubygems.

```ruby
gem 'scopie_rails'
```

## Mutation testing

    mutant --include lib --require scopie_rails --use rspec ScopieRails*

## Options

Scopie supports several options:

* `:type` - Coerces the type of the parameter sent. Available options: boolean, integer, float, date.

* `:only` - In which actions the scope is applied.

* `:except` - In which actions the scope is not applied.

* `:as` - The key in the params hash expected to find the scope. Defaults to the scope name.

* `:in` - The key in the params hash expected to contain a hash holding scope name as a value.

* `:allow_blank` - Blank values are not sent to scopes by default. Set to true to overwrite.

* `:ignore_blank` - Set to true to not apply the scope if blank value is given.

* `:default` - Default value for the scope. Whenever supplied the scope is always called.

## Rails

ScopieRails provides Rails integration for [Scopie][s].

Among other things it adds a `controller` method to scopies.

## Thanks

Scopie was inspired by [has_scope](http://github.com/plataformatec/has_scope) and [pundit](http://github.com/elabs/pundit).

Thanks to both.

[s]: https://github.com/beorc/scopie


text:
import os
from wheelerdata.load.base import Wheelerdata

class Butterfly(Wheelerdata):
    """Butterfly data"""

    def __init__(self):
        super(Butterfly, self).__init__()

        self.scodes = [4, 5, 7, 17, 18, 19, 21, 22, 23, 25, 26, 30]
        # self.scodes = [4, 5, 7, 17, 18, 19, 20, 21, 22, 23, 25, 26, 30]
        # S20's data was corrupted in roinii and I don't have
        # access to the orignal nii to recreate it.

        self.name = "butterfly"

        self.datapath = "/data/data2/meta_accumulate/" + self.name
        self.roipath = os.path.join(self.datapath, "roinii")
        self.metapath = os.path.join(self.datapath, "fidl")
        self.TR = 2.0

class SimAccumButterfly(Butterfly):
    """Simulated accumulator Butterfly data"""

    def __init__(self):
        super(SimAccumButterfly, self).__init__()

        self.datapath = "/data/data2/meta_accumulate/" + self.name
        self.roipath = os.path.join(self.datapath, "simnii")
        self.metapath = os.path.join(self.datapath, "fidl")


text:
//
//  gcd.h
//  INKELiving
//
//  Created by swift on 10/01/2017.
//  Copyright © 2017 swift. All rights reserved.
//

#ifndef gcd_h
#define gcd_h

/*************************GCD相关****************************/

#pragma mark - 循环引用相关

//GCD - 一次性执行

#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);

//GCD - 在Main线程上运行

#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);

//GCD - 开启异步线程

#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlock);

//GCD - 延迟执行

#define KDISPATCH_AFTER(delayTime,afterBlock)   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(),afterBlock );

#endif /* gcd_h */


text:
"""Boot-strap development by fetching package set from service.

This script fetches a protobuf encoded FileSet from get_file_set
method of a service.
"""

__author__ = 'rafek@google.com (Rafe Kaplan)'

import optparse
import os
import sys
import urllib2

from protorpc import protobuf
from protorpc import protojson
from protorpc import registry
from protorpc import transport

def parse_options(argv):
  """Parse options.

  Args:
    argv: List of original unparsed options.

  Returns:
    Options object as parsed by optparse.
  """
  program = os.path.split(__file__)[-1]
  parser = optparse.OptionParser(usage='%s [options]' % program)

  parser.add_option('-o', '--output',
                    dest='output',
                    help='Write descriptor to FILE.',
                    metavar='FILE',
                    default='music_service.descriptor')

  parser.add_option('-r', '--registry_path',
                    dest='registry_path',
                    help='Path to registry service.',
                    metavar='REGISTRY_PATH',
                    default='/protorpc')

  parser.add_option('-s', '--server',
                    dest='server',
                    help='Tunes DB server.',
                    metavar='SERVER',
                    default='tunes-db.appspot.com')

  options, args = parser.parse_args(argv)

  if args:
    parser.print_help()
    sys.exit(1)

  return options

def main(argv):
  options = parse_options(argv[1:])

  registry_url =  'http://%s%s' % (options.server,
                                   options.registry_path)

  http_transport = transport.HttpTransport(registry_url, protocol=protojson)
  remote_registry = registry.RegistryService.Stub(http_transport)

  # Get complete list of services.
  services = remote_registry.services()

  # Get file set for all services on server.
  get_file_set = registry.GetFileSetRequest()
  get_file_set.names = [service.name for service in services.services]
  file_set = remote_registry.get_file_set(get_file_set).file_set

  # Save file sets to disk.
  output = open(options.output, 'wb')
  try:
    output.write(protobuf.encode_message(file_set))
  finally:
    output.close()

if __name__ == '__main__':
  main(sys.argv)


text:
require 'digest/md5'
require 'gruff'

module GruffServer
  module Helper
    def self.included(base)
      base.helpers do
        def hashed_basename
          return @hashed_basename if @hashed_basename

          key = %Q(#{Time.now.to_i}-#{(rand() * 100000000).to_i})
          @hashed_basename = Digest::MD5.hexdigest(key).to_s
        end

        def saved_pathname(basename, ext=extension)
           File.join(settings.graphs_folder, "#{basename}.#{ext}")
        end

        def extension
          return settings.extension if settings.respond_to?(:extension)
          'png'
        end

        def gruff(params, options={})
          g = Gruff::Line.new

          # Parse parameters
          data = params.delete('data')
          labels = params.delete('labels')

          # set parameters
          params.each_pair do |method, value|
            setter = method.to_s + '='
            g.send(setter, value) if g.respond_to?(setter)
          end

          # set data
          data.each_pair do |name, values|
            g.data(name, values)
          end

          # set labels
          g.labels = labels.inject({}) { |_labels, (key, value)|
            _labels[key.to_i] = value
            _labels
          } if labels

          yield(g)
        end
      end
    end
  end
end


text:
namespace rviz_plugins
{
class NumButton : public QPushButton
{
  Q_OBJECT
public:
  NumButton(const QString &text, QWidget *parent = 0, int n = 0);

public Q_SLOTS:
  void emitNum();

Q_SIGNALS:
  void numClicked(int num);

private:
  int num;
};
}

#endif  // NUM_BUTTON_H


text:
package dotty.tools.dotc
package transform

import ast.tpd
import core.Constants.Constant
import core.Contexts.Context
import core.StdNames.nme
import core.Symbols.{defn,TermSymbol}
import core.TypeErasure
import TreeTransforms.{MiniPhaseTransform, TransformerInfo, TreeTransform}

/** Rewrite `classOf` calls as follow:
 *
 *  For every primitive class C whose boxed class is called B:
 *    classOf[C]    -> B.TYPE
 *  For every non-primitive class D:
 *    classOf[D]    -> Literal(Constant(erasure(D)))
 */
class ClassOf extends MiniPhaseTransform {
  import tpd._

  override def phaseName: String = "classOf"

  private var classOfMethod: TermSymbol = _

  override def prepareForUnit(tree: tpd.Tree)(implicit ctx: Context): TreeTransform = {
    classOfMethod = defn.ScalaPredefModule.requiredMethod(nme.classOf)
    this
  }

  override def transformTypeApply(tree: TypeApply)(implicit ctx: Context, info: TransformerInfo): Tree =
    if (tree.symbol eq classOfMethod) {
      val targ = tree.args.head.tpe
      tree.clsOf(targ, Literal(Constant(TypeErasure.erasure(targ))))
    }
    else tree
}


text:
'use strict';

module.exports = function (vm) {
  return {
    submit: function submit(e) {
      if (e) e.preventDefault();

      setTimeout(function () {
        var data = vm.formData();

        if (vm.opts.resetFormAfterSubmit) {
          vm.reinitForm();
        }

        vm.dispatch('sent', data);
        vm.getStatusBar().success(vm.opts.texts.sent);
      }, 50);

      return true;
    }
  };
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>traffic3.simulator Class Hierarchy</title>
<meta name="date" content="2013-12-16">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package traffic3.simulator

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

rescuecore2.components.AbstractComponent<T> (implements rescuecore2.components.Component)

rescuecore2.components.AbstractSimulator<T> (implements rescuecore2.components.Simulator)

rescuecore2.standard.components.StandardSimulator

traffic3.simulator.TrafficSimulator (implements rescuecore2.GUIComponent)

java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)

java.awt.Container

javax.swing.JComponent (implements java.io.Serializable)

javax.swing.JPanel (implements javax.accessibility.Accessible)

traffic3.simulator.TrafficSimulatorGUI

traffic3.simulator.PathElement

traffic3.simulator.TrafficConstants

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
(function( window, $, cue, undefined ) {
	'use strict';

	$.extend( MediaElementPlayer.prototype, {
		buildcuenexttrack: function( player, controls, layers, media ) {
			$( '
' +
					'<button type="button" aria-controls="' + player.id + '" title="' + cue.l10n.nextTrack + '"></button>' +
					'
' )
				.appendTo( controls )
				.on( 'click.cue', function() {
					var state,
						track = player.cueGetCurrentTrack() || {};

					state = $.extend({}, {
						currentTime: media.currentTime,
						duration: media.duration,
						src: media.src
					});

					$( player.node ).trigger( 'skipNext.cue', [ state, track ] );
					player.cuePlayNextTrack();
				});
		},

		// @todo Go to next playable track.
		cuePlayNextTrack: function() {
			var player = this,
				index = player.cueCurrentTrack + 1 >= player.options.cuePlaylistTracks.length ? 0 : player.cueCurrentTrack + 1;

			$( player.node ).trigger( 'nextTrack.cue', player );
			player.cueSetCurrentTrack( index );
		}
	});

})( this, jQuery, window.cue );


text:
package org.apache.wicket.security.pages.secure;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.security.checks.InverseSecurityCheck;
import org.apache.wicket.security.components.SecureComponentHelper;
import org.apache.wicket.security.components.markup.html.links.SecurePageLink;
import org.apache.wicket.security.pages.SecureTestPage;

/**
 * @author marrink
 *
 */
public class HomePage extends SecureTestPage
{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 *
	 */
	public HomePage()
	{
		add(new Label("welcome", "Welcome Only logged in users can see this page"));
		SecurePageLink<Void> securePageLink = new SecurePageLink<Void>("link", PageA.class);
		add(securePageLink);
		add(SecureComponentHelper.setSecurityCheck(new Label("sorry",
				"you are not allowed to go to Page A"), new InverseSecurityCheck(securePageLink
				.getSecurityCheck())));
	}

}


text:
package binape.http;

import java.net.MalformedURLException;

import binape.utils.LexerBase;
import binape.utils.StringUtils;

class URLError extends MalformedURLException {
	public URLError(String message) {
		super(message);
	}
}

public class HttpURL {

	static enum State {
		BEGIN,
		DOUBLE_SLASH,
		SLASH,
		LITERAL,
		HOST,
		PORT,
		USER,
		PASSWORD,
		PATH,
		HASH,
		QUERY
	}

	private String protocol;
	private String host;
	private int port = 80;
	private String path = "";
	private String hash = "";
	private String query = "";
	private boolean invalid = false;
	private String original;

	public HttpURL(String url) {
		if (StringUtils.isEmpty(url))
			throw new IllegalArgumentException("url can not be null");

		this.original = url;
		HttpURLLexer lexer = new HttpURLLexer(url);
		try {
			advanced(lexer, lexer.next(), State.BEGIN);
		} catch (URLError e) {
			invalid = true;
		}
	}

	public boolean valid() {
		return !invalid;
	}

	private void error(Tok tok, State state) throws URLError {
		throw new URLError("Syntax error: " + state + "," + tok.text + ", " + this.original);
	}

	private void error(Tok tok, State state, Throwable e) throws URLError {
		throw new URLError("Syntax error: " + state + "," + tok.text + ", " + this.original);
	}

	private void advanced(HttpURLLexer lexer, Tok tok, State state) throws URLError {
		if (tok.type != Tok.EOF) {
			if (state == State.BEGIN) {
				if (tok.type == Tok.DOUBLE_SLASH) {
					this.protocol = "http";
					advanced(lexer, lexer.next(), State.HOST);
				} else if (tok.type == Tok.STRING_LITERAL) {
					if ("http".equals(tok.text)
						|| "https".equals(tok.text)) {
						this.protocol = tok.text;
						Tok next = lexer.next();
						if (next.type == Tok.COLON)
							advanced(lexer, lexer.next(), State.DOUBLE_SLASH);
						else
							error(tok, state);
					} else
						error(tok, state);
				} else {
					error(tok, state);
				}
			} else if (state == State.DOUBLE_SLASH) {
				if (tok.type != Tok.DOUBLE_SLASH) {
					error(tok, state);
				} else {
					advanced(lexer, lexer.next(), State.HOST);
				}
			} else if (state == State.HOST) { // 解释主机名

				if (tok.type != Tok.STRING_LITERAL)
					error(tok, state);

				this.setHost(tok.text);

				Tok next = lexer.next();
				if (next.type == Tok.COLON) {
					advanced(lexer, lexer.next(), State.PORT);
				} else if (next.type == Tok.SINGLE_SLASH
						|| next.type == Tok.DOUBLE_SLASH) {
					this.setPort(this.isSecureURL() ? 443 : 80);
					advanced(lexer, next, State.PATH);
				} else if (next.type == Tok.EOF) {
					this.setPath("/");
					this.setPort(this.isSecureURL() ? 443 : 80);
				} else {
					error(tok, state);
				}
			} else if (state == State.PATH) {
				if (tok.type != Tok.HASH && tok.type != Tok.QUEST) {
					setPath(getPath() + tok.text);
					advanced(lexer, lexer.next(), State.PATH);
				} else {
					if (tok.type == Tok.HASH) {
						hash += tok.text;
						advanced(lexer, lexer.next(), State.HASH);
					} else if (tok.type == Tok.QUEST) {
						advanced(lexer, lexer.next(), State.QUERY);
					}
				}
			} else if (state == State.PORT) { // 解释主机端口
				if (tok.type != Tok.STRING_LITERAL)
					error(tok, state);
				else {
					try {
						this.setPort(Integer.parseInt(tok.text));
						if (getPort() > 65535 || getPort() < 0)
							throw new NumberFormatException("Port out of range: 0 ~ 65535 => got" + tok.text);
					} catch (NumberFormatException e) {
						error(tok, state, e);
					}
					advanced(lexer, lexer.next(), State.PATH);
				}
			} else if (state == State.HASH) {
				hash += tok.text;
				advanced(lexer, lexer.next(), State.HASH);
			} else if (state == State.QUERY) {
				if (tok.type == Tok.HASH) {
					advanced(lexer, lexer.next(), State.HASH);
				} else {
					query += tok.text;
					advanced(lexer, lexer.next(), State.QUERY);
				}
			}
		}
	}

	public String getPrefix() {
		return this.getProtocol() + "://" + host + portSuffix();
	}

	private String portSuffix() {
		return isDefaultPort() ?  "" : (":" + port);
	}

	public boolean isSecureURL() {
		return "https".equalsIgnoreCase(this.protocol);
	}

	public boolean isDefaultPort() {
		return getPort() == 0 || (isSecureURL() ? (getPort() == 443) : (getPort() == 80));
	}

	public String getHash() {
		return this.hash;
	}

	public String getProtocol() {
		return protocol;
	}

	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public String getUri() {
		return makeUri(this.getPath(), this.getQuery());
	}

	private String makeUri(String path, String query) {
		if (StringUtils.isEmpty(query))
			return path;
		else {
			return path + "?" + query;
		}
	}

	public String getOriginal() {
		return this.original;
	}

	public String toURL() {
		StringBuffer buf = new StringBuffer();
		buf.append(protocol + "://");
		buf.append(host);
		if (!isDefaultPort()) {
			buf.append(":" + getPort());
		}
		buf.append(this.getUri());
		return buf.toString();
	}

	public String toString() {
		return String.format("{#HttpURL proto=%s host=%s port=%d path=%s hash=%s query=%s}",
							 protocol, host, port, path, query, hash);
	}

}

class Tok {
	int type = 0;
	String text = null;
	public Tok(String text, int type) {
		this.text = text;
		this.type = type;
	}

	public static final int EOF = 0;
	public static final int DOUBLE_SLASH = 1;
	public static final int STRING_LITERAL = 2;
	public static final int COLON = 3;
	public static final int AT = 4;
	public static final int QUEST = 5;
	public static final int HASH = 6;
	public static final int SEMICOLON = 7;
	public static final int SINGLE_SLASH = 8;

	public String toString() {
		return String.format("<#Tok text='%s' type='%d'>", text, type);
	}
}

class HttpURLLexer extends LexerBase {

	public HttpURLLexer(String url) {
		super(url.getBytes());
	}

	public Tok next() {
		while (true) {
			switch (current()) {
				case '/':
					if ('/' == forward()) {
						forward();
						return new Tok("//", Tok.DOUBLE_SLASH);
					}
					else
						return new Tok("/", Tok.SINGLE_SLASH);
				case ':':
					forward();
					return new Tok(":", Tok.COLON);
				case ';':
					forward();
					return new Tok(";", Tok.SEMICOLON);
				case '?':
					forward();
					return new Tok("?", Tok.QUEST);
				case '#':
					forward();
					return new Tok("#", Tok.HASH);
				case 0:
					return new Tok("<EOF>", Tok.EOF);
				default:
					return new Tok(readStringLiteral(current()), Tok.STRING_LITERAL);
			}
		}
	}

	private String readStringLiteral(int c) {
		if (!isStringLiteral(c)) {
			return "";
		} else {
			return (char)c + readStringLiteral(forward());
		}
	}

	private boolean isStringLiteral(int c) {
		return c != '#'
			   && c != '?'
			   && c != ';'
			   && c != ':'
			   && c != '/'
			   && c != 0;
	}

}


text:
<?php

namespace Sofa\Eloquence\Contracts;

use Closure;

interface Mappable
{
    public static function hook($method, Closure $hook);
    public function getAttribute($key);
    public function setAttribute($key, $value);
    public function hasMapping($key);
    public function getMappingForAttribute($key);
    public function getMaps();
}


text:
import tempfile
import ROOT
from IPython.core.magic import (Magics, magics_class, cell_magic)

@magics_class
class RootMagics(Magics):
    """Magics related to Root.
    %%rootprint  - Capture Root stdout output and show in result cell
    """

    def __init__(self, shell):
        super(RootMagics, self).__init__(shell)

    @cell_magic
    def rootprint(self, line, cell):
        """Capture Root stdout output and print in ipython notebook."""

        with tempfile.NamedTemporaryFile() as tmpFile:

            ROOT.gSystem.RedirectOutput(tmpFile.name, "w")
            # ns = {}
            # exec cell in self.shell.user_ns, ns
            exec cell in self.shell.user_ns
            ROOT.gROOT.ProcessLine("gSystem->RedirectOutput(0);")
            print tmpFile.read()

# Register
ip = get_ipython()
ip.register_magics(RootMagics)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Storage location provided for troubleshoot. */
@Fluent
public final class TroubleshootingProperties {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(TroubleshootingProperties.class);

    /*
     * The ID for the storage account to save the troubleshoot result.
     */
    @JsonProperty(value = "storageId", required = true)
    private String storageId;

    /*
     * The path to the blob to save the troubleshoot result in.
     */
    @JsonProperty(value = "storagePath", required = true)
    private String storagePath;

    /**
     * Get the storageId property: The ID for the storage account to save the troubleshoot result.
     *
     * @return the storageId value.
     */
    public String storageId() {
        return this.storageId;
    }

    /**
     * Set the storageId property: The ID for the storage account to save the troubleshoot result.
     *
     * @param storageId the storageId value to set.
     * @return the TroubleshootingProperties object itself.
     */
    public TroubleshootingProperties withStorageId(String storageId) {
        this.storageId = storageId;
        return this;
    }

    /**
     * Get the storagePath property: The path to the blob to save the troubleshoot result in.
     *
     * @return the storagePath value.
     */
    public String storagePath() {
        return this.storagePath;
    }

    /**
     * Set the storagePath property: The path to the blob to save the troubleshoot result in.
     *
     * @param storagePath the storagePath value to set.
     * @return the TroubleshootingProperties object itself.
     */
    public TroubleshootingProperties withStoragePath(String storagePath) {
        this.storagePath = storagePath;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (storageId() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property storageId in model TroubleshootingProperties"));
        }
        if (storagePath() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property storagePath in model TroubleshootingProperties"));
        }
    }
}


text:
@value grey from '../../styles/palette.css';

/* define sizes for header elements */
@value header-height: 80px;
@value header-item-width: 48px;
@value header-item-height: 48px;

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: header-height;
    background: grey;
}

.header-icon {
    width: header-item-width;
    height: header-item-height;
}


text:
<?php

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

class AddMaskToWork extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('works', function ($table) {
            $table->integer('mask_id')->unsigned()->after('logo');
            $table->integer('order')->after('description')->unsigned()->default(0);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('works', function ($table) {
            $table->dropColumn('mask_id');
            $table->dropColumn('order');
        });
    }
}


text:
// ------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
//
//	   Copyright (c) 2017 Citrix ShareFile. All rights reserved.
// </auto-generated>
// ------------------------------------------------------------------------------

package com.citrix.sharefile.api.models;

import java.io.InputStream;
import java.util.ArrayList;
import java.net.URI;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;

import com.google.gson.annotations.SerializedName;
import com.citrix.sharefile.api.*;
import com.citrix.sharefile.api.enumerations.*;
import com.citrix.sharefile.api.models.*;

public class SFQuery extends SFODataObject {

	@SerializedName("ItemTypes")
	private ArrayList<String> ItemTypes;
	@SerializedName("ParentID")
	private ArrayList<String> ParentID;
	@SerializedName("CreatorID")
	private ArrayList<String> CreatorID;
	@SerializedName("SearchQuery")
	private String SearchQuery;
	@SerializedName("CreateStartDate")
	private String CreateStartDate;
	@SerializedName("CreateEndDate")
	private String CreateEndDate;
	@SerializedName("ItemNameOnly")
	private Boolean ItemNameOnly;

		/**
		* Types of items to search for (ex "File", "Folder", etc.)
		*/
	public ArrayList<String> getItemTypes() {
		return this.ItemTypes;
	}

		/**
		* Types of items to search for (ex "File", "Folder", etc.)
		*/
	public void setItemTypes(ArrayList<String> itemtypes) {
		this.ItemTypes = itemtypes;
	}
		/**
		* Parent id constraints on search results
		*/
	public ArrayList<String> getParentID() {
		return this.ParentID;
	}

		/**
		* Parent id constraints on search results
		*/
	public void setParentID(ArrayList<String> parentid) {
		this.ParentID = parentid;
	}
		/**
		* Creator id constraints on search results
		*/
	public ArrayList<String> getCreatorID() {
		return this.CreatorID;
	}

		/**
		* Creator id constraints on search results
		*/
	public void setCreatorID(ArrayList<String> creatorid) {
		this.CreatorID = creatorid;
	}
		/**
		* Search term to search for
		*/
	public String getSearchQuery() {
		return this.SearchQuery;
	}

		/**
		* Search term to search for
		*/
	public void setSearchQuery(String searchquery) {
		this.SearchQuery = searchquery;
	}
		/**
		* Item creation date range constraint start date in UTC
		*/
	public String getCreateStartDate() {
		return this.CreateStartDate;
	}

		/**
		* Item creation date range constraint start date in UTC
		*/
	public void setCreateStartDate(String createstartdate) {
		this.CreateStartDate = createstartdate;
	}
		/**
		* Item creation date range constraint end date in UTC
		*/
	public String getCreateEndDate() {
		return this.CreateEndDate;
	}

		/**
		* Item creation date range constraint end date in UTC
		*/
	public void setCreateEndDate(String createenddate) {
		this.CreateEndDate = createenddate;
	}
		/**
		* Whether item content should be included in the search or not.
		*/
	public Boolean getItemNameOnly() {
		return this.ItemNameOnly;
	}

		/**
		* Whether item content should be included in the search or not.
		*/
	public void setItemNameOnly(Boolean itemnameonly) {
		this.ItemNameOnly = itemnameonly;
	}

}


text:
<!DOCTYPE html>

            <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Blog budućeg softver inženjera">
        <meta name="author" content="Zoran Stupar">

        <title>Blog budućeg softver inženjera</title>

        <link href="theme/css/bootstrap.min.css" rel="stylesheet">

        <link href="theme/css/clean-blog.min.css" rel="stylesheet">

            <link href="theme/css/code_blocks/darkly.css" rel="stylesheet">

        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
        <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

			<meta property="og:locale" content="en">
		<meta property="og:site_name" content="Blog budućeg softver inženjera">

	<meta property="og:type" content="article">
	<meta property="article:author" content="">
	<meta property="og:url" content="/pun-sabirac.html">
	<meta property="og:title" content="Pun sabirač">
	<meta property="og:description" content="">
	<meta property="og:image" content="/theme/images/posts/pun-sabirac.jpg">
	<meta property="article:published_time" content="2017-03-10 22:59:00+01:00">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Blog budućeg softver inženjera

                    Website

Pun sabirač

                        Posted by
                                Zoran Stupar
                             on 10/03/2017

  < 1 min read

Pun sabirač (Full Adder) je složeno logičko kolo koje služi za sabiranje tri binerne cifre istovremeno. Ovo kolo se još naziva i kolo za potpuno sabiranje. Prema pravilima sabiranja, pun sabirač treba da zadovoljava sledeću tabelu stanja:

A1
A2
A3
C
S

0
0
0
0
0

0
0
1
0
1

0
1
0
0
1

0
1
1
1
0

1
0
0
0
1

1
0
1
1
0

1
1
0
1
0

1
1
1
1
1

Zbir rezultata operacije ekskluzivne disjunkcije je:

\(S = A_1 \bigoplus A_2 \bigoplus A_3\)

Prenos zadovoljava logičku operaciju datu sledećim izrazom:
\(C = A_1 * A_2 + A_1 * A_3 + A_2 * A_3\)

Prema tome, pun sabirač mora imati tri ulaza i dva izlaza. S obzirom na izraze za S i C, za realizaciju punog sabirača potrebno je jedno troulazno ekskluzivno ILI kolo (za operaciju sabiranja) i tri I kola i jedno ILI kolo (za operaciju prenosa).

Šema punog sabirača napravljena u programu KiCad

Zoran Stupar ©


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.05.02 at 01:40:56 PM CEST
//

package org.easybatch.xml;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Exclusion", propOrder = {

})
public class Exclusion {

    protected String artifactId;
    protected String groupId;

    /**
     * Gets the value of the artifactId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getArtifactId() {
        return artifactId;
    }

    /**
     * Sets the value of the artifactId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setArtifactId(String value) {
        this.artifactId = value;
    }

    /**
     * Gets the value of the groupId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getGroupId() {
        return groupId;
    }

    /**
     * Sets the value of the groupId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setGroupId(String value) {
        this.groupId = value;
    }

}


text:
"""
CLE is an extensible binary loader. Its main goal is to take an executable program and any libraries it depends on and
produce an address space where that program is loaded and ready to run.

The primary interface to CLE is the Loader class.
"""

import logging
logging.getLogger("cle").addHandler(logging.NullHandler())

# pylint: disable=wildcard-import
from . import utils
from .loader import *
from .memory import *
from .errors import *
from .backends import *
from .backends.tls import *
from .backends.externs import *
from .patched_stream import *
from .gdb import *


text:
<!DOCTYPE xml>
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
   <xwss:UsernameToken name="myUser" password="myPassword"
      digestPassword="true" useNonce="true" />
</xwss:SecurityConfiguration>


text:
package tools.devnull.boteco.message.formatter;

import org.junit.Before;
import org.junit.Test;
import tools.devnull.boteco.ContentFormatter;
import tools.devnull.boteco.message.FormatExpressionParser;
import tools.devnull.kodo.Spec;

import java.util.function.Function;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static tools.devnull.kodo.Expectation.to;

public class FormatExpressionParserTest {

  private FormatExpressionParser parser;
  private ContentFormatter formatter;

  @Before
  public void initialize() {
    formatter = mock(ContentFormatter.class);
    parser = new DefaultFormatExpressionParser();

    when(formatter.normalize(any())).thenAnswer(invocation -> invocation.getArguments()[0]);
    when(formatter.accent("value")).thenReturn("accent: value");
    when(formatter.alternativeAccent("value")).thenReturn("alternative_accent: value");
    when(formatter.error("value")).thenReturn("error: value");
    when(formatter.link("title", "url")).thenReturn("link: title - url");
    when(formatter.negative("value")).thenReturn("negative: value");
    when(formatter.positive("value")).thenReturn("positive: value");
    when(formatter.tag("value")).thenReturn("tag: value");
    when(formatter.value("value")).thenReturn("value: value");
  }

  @Test
  public void testExpressionBuild() {
    Spec.given(parser)
        .expect(expression("[a]value[/a]"), to().be("accent: value"))
        .expect(expression("lorem ipsum [a]value[/a] dolor [/a]"),
            to().be("lorem ipsum accent: value dolor [/a]"))

        .expect(expression("[aa]value[/aa]"), to().be("alternative_accent: value"))

        .expect(expression("[v]value[/v]"), to().be("value: value"))
        .expect(expression("[p]value[/p]"), to().be("positive: value"))
        .expect(expression("[n]value[/n]"), to().be("negative: value"))
        .expect(expression("[t]value[/t]"), to().be("tag: value"))
        .expect(expression("[e]value[/e]"), to().be("error: value"))
        .expect(expression("[l]title|url[/l]"), to().be("link: title - url"))

        .expect(expression("[t]value[/a]"), to().be("[t]value[/a]"));

    verify(formatter, times(2)).accent("value");
    verify(formatter, times(1)).alternativeAccent("value");
    verify(formatter, times(1)).value("value");
    verify(formatter, times(1)).positive("value");
    verify(formatter, times(1)).negative("value");
    verify(formatter, times(1)).tag("value");
    verify(formatter, times(1)).error("value");
    verify(formatter, times(1)).link("title", "url");
    verify(formatter, times(10)).normalize(any());
  }

  private Function<FormatExpressionParser, String> expression(String expression) {
    return f -> f.parse(formatter, expression);
  }

}


text:
namespace Poco {

SemaphoreImpl::SemaphoreImpl(int n, int max): _n(n), _max(max)
{
	poco_assert (n >= 0 && max > 0 && n <= max);

#if defined(POCO_VXWORKS)
	// This workaround is for VxWorks 5.x where
	// pthread_mutex_init() won't properly initialize the mutex
	// resulting in a subsequent freeze in pthread_mutex_destroy()
	// if the mutex has never been used.
	std::memset(&_mutex, 0, sizeof(_mutex));
#endif
	if (pthread_mutex_init(&_mutex, NULL))
		throw SystemException("cannot create semaphore (mutex)");
	if (pthread_cond_init(&_cond, NULL))
		throw SystemException("cannot create semaphore (condition)");
}

SemaphoreImpl::~SemaphoreImpl()
{
	pthread_cond_destroy(&_cond);
	pthread_mutex_destroy(&_mutex);
}

void SemaphoreImpl::waitImpl()
{
	if (pthread_mutex_lock(&_mutex))
		throw SystemException("wait for semaphore failed (lock)");
	while (_n < 1)
	{
		if (pthread_cond_wait(&_cond, &_mutex))
		{
			pthread_mutex_unlock(&_mutex);
			throw SystemException("wait for semaphore failed");
		}
	}
	--_n;
	pthread_mutex_unlock(&_mutex);
}

bool SemaphoreImpl::waitImpl(long milliseconds)
{
	int rc = 0;
	struct timespec abstime;

#if defined(__VMS)
	struct timespec delta;
	delta.tv_sec  = milliseconds / 1000;
	delta.tv_nsec = (milliseconds % 1000)*1000000;
	pthread_get_expiration_np(&delta, &abstime);
#elif defined(POCO_VXWORKS)
	clock_gettime(CLOCK_REALTIME, &abstime);
	abstime.tv_sec  += milliseconds / 1000;
	abstime.tv_nsec += (milliseconds % 1000)*1000000;
	if (abstime.tv_nsec >= 1000000000)
	{
		abstime.tv_nsec -= 1000000000;
		abstime.tv_sec++;
	}
#else
	struct timeval tv;
	gettimeofday(&tv, NULL);
	abstime.tv_sec  = tv.tv_sec + milliseconds / 1000;
	abstime.tv_nsec = tv.tv_usec*1000 + (milliseconds % 1000)*1000000;
	if (abstime.tv_nsec >= 1000000000)
	{
		abstime.tv_nsec -= 1000000000;
		abstime.tv_sec++;
	}
#endif

	if (pthread_mutex_lock(&_mutex) != 0)
		throw SystemException("wait for semaphore failed (lock)");
	while (_n < 1)
	{
		if ((rc = pthread_cond_timedwait(&_cond, &_mutex, &abstime)))
		{
			if (rc == ETIMEDOUT) break;
			pthread_mutex_unlock(&_mutex);
			throw SystemException("cannot wait for semaphore");
		}
	}
	if (rc == 0) --_n;
	pthread_mutex_unlock(&_mutex);
	return rc == 0;
}

} // namespace Poco


text:
/*
 * Angular 2 decorators and services
 */
import { Component, ViewEncapsulation } from '@angular/core';

import { AppState } from './app.service';

/*
 * App Component
 * Top Level Component
 */
@Component({
    selector: 'app',
    encapsulation: ViewEncapsulation.None,
    styles: [
        require('./app.component.css'),
        require('@angular/material/core/theming/prebuilt/indigo-pink.css')
    ],
    template: require('./app.component.html')
})
export class AppComponent {

}


text:
package com.diozero.internal.provider.builtin.gpio;

import com.diozero.api.RuntimeIOException;

// struct gpiod_line
public class GpioLine implements AutoCloseable {
	public static enum Direction {
		INPUT, OUTPUT;
	}

	// Line informational flags
	// https://elixir.bootlin.com/linux/v4.9.127/source/include/uapi/linux/gpio.h#L29
	private static final int GPIOLINE_FLAG_KERNEL = 1 << 0;
	private static final int GPIOLINE_FLAG_IS_OUT = 1 << 1;
	private static final int GPIOLINE_FLAG_ACTIVE_LOW = 1 << 2;
	private static final int GPIOLINE_FLAG_OPEN_DRAIN = 1 << 3;
	private static final int GPIOLINE_FLAG_OPEN_SOURCE = 1 << 4;

	private final int offset;
	private final boolean reserved;
	private final Direction direction;
	private final boolean activeLow;
	private final boolean openDrain;
	private final boolean openSource;
	private final String name;
	private final String consumer;
	private int fd;

	public GpioLine(int offset, int flags, String name, String consumer) {
		this.offset = offset;
		this.reserved = ((flags & GPIOLINE_FLAG_KERNEL) == 0) ? false : true;
		this.direction = ((flags & GPIOLINE_FLAG_IS_OUT) == 0) ? Direction.INPUT : Direction.OUTPUT;
		this.activeLow = ((flags & GPIOLINE_FLAG_ACTIVE_LOW) == 0) ? false : true;
		this.openDrain = ((flags & GPIOLINE_FLAG_OPEN_DRAIN) == 0) ? false : true;
		this.openSource = ((flags & GPIOLINE_FLAG_OPEN_SOURCE) == 0) ? false : true;
		this.name = name;
		this.consumer = consumer;
	}

	public int getOffset() {
		return offset;
	}

	public boolean isReserved() {
		return reserved;
	}

	public Direction getDirection() {
		return direction;
	}

	public boolean isActiveLow() {
		return activeLow;
	}

	public boolean isOpenDrain() {
		return openDrain;
	}

	public boolean isOpenSource() {
		return openSource;
	}

	public String getName() {
		return name;
	}

	public String getConsumer() {
		return consumer;
	}

	public int getFd() {
		return fd;
	}

	void setFd(int fd) {
		this.fd = fd;
	}

	public int getValue() {
		int rc = NativeGpioDevice.getValue(fd);
		if (rc < 0) {
			throw new RuntimeIOException("Error in getValue() for line " + offset + ": " + rc);
		}
		return rc;
	}

	public void setValue(int value) {
		int rc = NativeGpioDevice.setValue(fd, value);
		if (rc < 0) {
			throw new RuntimeIOException("Error in setValue(" + value + ") for line " + offset + ": " + rc);
		}
	}

	@Override
	public void close() {
		NativeGpioDevice.close(fd);
	}
}


text:
#import <DevToolsInterface/PBXPreferencesPaneModule.h>

@class NSArray, NSArrayController, NSButton, NSMenuItem, NSPanel, NSPopUpButton, NSSecureTextField, NSString, NSTabView, NSTableView, NSTextField, NSTextView, NSView, SCMRepositorySettingsEditor;

@interface XCRepositoriesPrefsModule : PBXPreferencesPaneModule
{
    NSButton *_addRepositoryButton;
    NSButton *_removeRepositoryButton;
    NSButton *_cancelButton;
    NSView *_contentView;
    NSTabView *_infoTabView;
    NSTextView *_infoTextView;
    NSTextField *_newRepositoryNameTextField;
    NSPanel *_newRepositoryPanel;
    NSButton *_okButton;
    NSTableView *_repositoriesTable;
    NSTableView *_keyTable;
    NSPopUpButton *_scmSystemPopup;
    NSArrayController *_repositoryController;
    SCMRepositorySettingsEditor *_repositorySettingsEditor;
    NSView *_settingsView;
    NSArray *_sortDescriptors;
    NSSecureTextField *_sshPasswordTextField;
    NSPopUpButton *compareToolPopUpButton;
    NSMenuItem *compareDisplayLeftOrRightPopUpButtonLeftMenuItem;
    NSMenuItem *compareDisplayLeftOrRightPopUpButtonRightMenuItem;
    NSMenuItem *compareToolPopUpButtonXcodeMenuItem;
    NSMenuItem *compareToolPopUpButtonFileMergeMenuItem;
    NSMenuItem *compareToolPopUpButtonP4MergeMenuItem;
    NSMenuItem *compareToolPopUpButtonBBEditMenuItem;
    NSMenuItem *compareToolPopUpButtonOtherMenuItem;
    NSPopUpButton *compareDisplayLeftOrRightPopUpButton;
    NSButton *saveFilesCheckbox;
    NSButton *configureSCMAutomaticallyCheckBox;
    NSPopUpButton *diffOutputFormatPopUpButton;
    NSMenuItem *diffOutputFormatPopUpButtonSideBySideItem;
    NSMenuItem *diffOutputFormatPopUpButtonContextualItem;
    NSMenuItem *diffOutputFormatPopUpButtonUnifiedItem;
    NSMenuItem *diffOutputFormatPopUpButtonDefaultItem;
    NSTextField *diffLinesOfContextTextField;
    NSTextField *diffLinesOfContextLabel;
    NSButton *diffIgnoresWhitespaceCheckbox;
    NSButton *diffIgnoresBlankLinesCheckbox;
    NSString *_compareLeftOrRight;
    NSString *_compareToolSelection;
    NSString *_compareToolLocation;
    NSString *_diffOutputFormat;
}

+ (void)initialize;
- (void)setDiffOutputFormat:(id)arg1;
- (id)diffOutputFormat;
- (void)setCompareToolLocation:(id)arg1;
- (id)compareToolLocation;
- (void)setCompareToolSelection:(id)arg1;
- (id)compareToolSelection;
- (void)setCompareLeftOrRight:(id)arg1;
- (id)compareLeftOrRight;
- (void)compareDisplayLeftOrRightPopUpButtonDidSelectRight:(id)arg1;
- (void)compareDisplayLeftOrRightPopUpButtonDidSelectLeft:(id)arg1;
- (void)compareToolPopUpDidSelectOther:(id)arg1;
- (void)_scmCompareToolOtherSheetDidEnd:(id)arg1 returnCode:(long long)arg2 contextInfo:(void *)arg3;
- (void)configureAutomaticallyDidChange:(id)arg1;
- (void)diffLinesOfContextTextFieldDidChange:(id)arg1;
- (void)diffIgnoresBlankLinesCheckboxDidChange:(id)arg1;
- (void)diffIgnoresWhitespaceCheckboxDidChange:(id)arg1;
- (void)diffOutputFormatPopUpButtonDidSelectDefault:(id)arg1;
- (void)diffOutputFormatPopUpButtonDidSelectUnified:(id)arg1;
- (void)diffOutputFormatPopUpButtonDidSelectContextual:(id)arg1;
- (void)diffOutputFormatPopUpButtonDidSelectSideBySide:(id)arg1;
- (void)compareToolPopUpDidSelectBBEdit:(id)arg1;
- (void)compareToolPopUpDidSelectP4Merge:(id)arg1;
- (void)compareToolPopUpDidSelectFileMerge:(id)arg1;
- (void)compareToolPopUpDidSelectXcode:(id)arg1;
- (void)compareToolPopUpButtonDidChange:(id)arg1;
- (void)compareDisplayLeftOrRightPopUpButtonDidChange:(id)arg1;
- (void)saveFilesCheckboxDidChange:(id)arg1;
- (id)agent;
- (id)repositorySortDescriptors;
- (void)setRepositorySortDescriptors:(id)arg1;
- (void)removeRepositoryAction:(id)arg1;
- (void)_addRepositorySheetDidEnd:(id)arg1 returnCode:(long long)arg2 contextInfo:(void *)arg3;
- (void)dismissSheet:(id)arg1;
- (void)addRepositoryAction:(id)arg1;
- (void)selectRepository:(id)arg1;
- (void)showRepositoriesTab;
- (void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void *)arg4;
- (void)viewDidLoad;
- (void)updateEditorView;
- (void)dealloc;
- (void)initializeFromDefaults;
- (void)saveChanges;
- (void)applyChanges;
- (id)scmManager;
- (struct CGSize)minModuleSize;

@end


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

namespace gov.va.medora.mdo
{
    public class MicrobiologyReport : LabReport
    {
        string sample;
        string text;

        public MicrobiologyReport() { }

        public string Sample
        {
            get { return sample; }
            set { sample = value; }
        }

        public string Text
        {
            get { return text; }
            set { text = value; }
        }

    }
}


text:
//
//  TKBundleController.h
//  TumblKitNG
//
//  Created by uasi on 09/03/29.
//  Copyright 2011 isdead.info. All rights reserved.
//

#import <Cocoa/Cocoa.h>

extern NSBundle *TKBundle; /* Shared bundle instance */

@class TKEditPanelController;
@interface TKBundleController : NSObject {
    IBOutlet TKEditPanelController *editPanelController;
}

@property(readonly) TKEditPanelController *editPanelController;

+ (NSBundle *)bundle;
+ (id)sharedBundleController;
+ (void)swizzleInstanceMethod:(SEL)aMethod
                   withMethod:(SEL)otherMethod
                      ofClass:(Class)theClass;

@end