text:
if [ `whoami` == "travis" ];
then
    BASEDIR=`pwd`
elif [ `facter virtual` == "virtualbox" ];
then
    BASEDIR=/vagrant
else
    echo The command should be executed within the guest OS!
    exit 1
fi

WHOAMI=`whoami`

echo "Dirinit WHOAMI: ${WHOAMI}"

sudo mkdir -p /app/symfony2app/app/cache
sudo mkdir -p /app/symfony2app/app/logs
sudo mkdir -p /app/symfony2app/app/cache/sessions
sudo mkdir -p /app/symfony2app/vendor

sudo chmod -R 0777 /app/symfony2app
sudo chown -R "${WHOAMI}:${WHOAMI}" /app/symfony2app


text:
function main()
{

    model.allowBrowserToCache = "false";

    // Get the node from the URL
    var pathSegments = url.match.split("/");
    var reference = [ url.templateArgs.store_type, url.templateArgs.store_id ].concat(url.templateArgs.id.split("/"));
    var node = search.findNode('node', reference);

    // 404 if the node to thumbnail is not found
    if (node == null)
    {
        status.setCode(status.STATUS_NOT_FOUND, "The thumbnail source node could not be found");
        return;
    }

    // 400 if the node is not a subtype of cm:content
    if (!node.isSubType("cm:content"))
    {
        status.setCode(status.STATUS_BAD_REQUEST, "The thumbnail source node is not a subtype of cm:content");
        return;
    }

    var thumbnailName = 'pdf';

    // Get the thumbnail
    var thumbnail = node.getThumbnail(thumbnailName);
    if (thumbnail == null || thumbnail.size == 0)
    {
        // Remove broken thumbnail
        if (thumbnail != null)
        {
            thumbnail.remove();
        }

        try {
            model.contentNode = node.createThumbnail(thumbnailName, false, true);
        }
        catch(e) {
            status.setCode(status.STATUS_NOT_FOUND, "Thumbnail could not be created");
            return;
        }

    }
    else
    {
        // Place the details of the thumbnail into the model, this will be used to stream the content to the client
        model.contentNode = thumbnail;
    }
}

main();

redpajama_set_name: RedPajamaGithub


text:
/**
 * Contains classes that keep state of Raft nodes
 */
package com.hazelcast.cp.internal.raft.impl.state;


text:
package gov.va.med.lom.javaBroker.rpc.user.models;

import gov.va.med.lom.javaBroker.rpc.BaseBean;

import java.io.Serializable;

public class TiuAlertInfo extends BaseBean implements Serializable {

  private int tiuda;
  private String guiTabIndicator;

  public TiuAlertInfo() {
    this.tiuda = 0;
    this.guiTabIndicator = null;
  }

  public String getGuiTabIndicator() {
    return guiTabIndicator;
  }

  public void setGuiTabIndicator(String guiTabIndicator) {
    this.guiTabIndicator = guiTabIndicator;
  }

  public int getTiuda() {
    return tiuda;
  }

  public void setTiuda(int tiuda) {
    this.tiuda = tiuda;
  }
}


text:
package io.pivotal.cf.tester.config;

import org.springframework.amqp.core.AbstractExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ErrorHandler;

@Configuration
public class RabbitConfig {

	@Value("${rabbit.queueName:testQueue}")
	private String rabbitQueueName;

	@Value("${rabbit.exchangeName:testExchange}")
	private String rabbitExchangeName;

	@Value("${rabbit.durable:true}")
	private boolean isRabbitDurable = true;

	@Value("${rabbit.exclusive:false}")
	private boolean isRabbitExclusive = false;

	@Value("${rabbit.autodelete:false}")
	private boolean isRabbitAutoDelete = false;

	@Autowired
	public ErrorHandler testErrorHandler;

	@Bean
	public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
		if( connectionFactory == null ) {
			return null;
		}
		RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
		rabbitAdmin.setIgnoreDeclarationExceptions(true);
		return rabbitAdmin;
	}

	@Bean
	public AbstractExchange testExchange() {
	    return new FanoutExchange(rabbitExchangeName, isRabbitDurable, isRabbitAutoDelete);
	}

	@Bean
	public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
		if( connectionFactory == null ) {
			return new RabbitTemplate() {
				@Override
				public void afterPropertiesSet() {
				}

			};
		}
		RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
		rabbitTemplate.setRoutingKey(rabbitQueueName);
		return rabbitTemplate;
	}

}


text:
package com.github.nordinh.atomfeed.notification;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.jboss.resteasy.plugins.providers.atom.Entry;
import org.jboss.resteasy.plugins.providers.atom.Feed;

public interface NotificationFeed {

	@GET
	@Path("/notifications")
	@Produces("application/atom+xml")
	public Feed getFeed();

	@GET
	@Path("/notifications/{page}")
	@Produces("application/atom+xml")
	public Feed getFeed(@PathParam("page") Integer page);

	@POST
	@Path("/notifications")
	@Produces("application/atom+xml")
	public void add(Entry entry);

}


text:
package org.apache.lucene.codecs.mocksep;

import java.io.IOException;

import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
import org.apache.lucene.codecs.blockterms.BlockTermsReader;
import org.apache.lucene.codecs.blockterms.BlockTermsWriter;
import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexReader;
import org.apache.lucene.codecs.blockterms.FixedGapTermsIndexWriter;
import org.apache.lucene.codecs.blockterms.TermsIndexReaderBase;
import org.apache.lucene.codecs.blockterms.TermsIndexWriterBase;
import org.apache.lucene.codecs.sep.SepPostingsReader;
import org.apache.lucene.codecs.sep.SepPostingsWriter;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.util.BytesRef;

/**
 * A silly codec that simply writes each file separately as
 * single vInts.  Don't use this (performance will be poor)!
 * This is here just to test the core sep codec
 * classes.
 */
public final class MockSepPostingsFormat extends PostingsFormat {

  public MockSepPostingsFormat() {
    super("MockSep");
  }

  @Override
  public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {

    PostingsWriterBase postingsWriter = new SepPostingsWriter(state, new MockSingleIntFactory());

    boolean success = false;
    TermsIndexWriterBase indexWriter;
    try {
      indexWriter = new FixedGapTermsIndexWriter(state);
      success = true;
    } finally {
      if (!success) {
        postingsWriter.close();
      }
    }

    success = false;
    try {
      FieldsConsumer ret = new BlockTermsWriter(indexWriter, state, postingsWriter);
      success = true;
      return ret;
    } finally {
      if (!success) {
        try {
          postingsWriter.close();
        } finally {
          indexWriter.close();
        }
      }
    }
  }

  @Override
  public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {

    PostingsReaderBase postingsReader = new SepPostingsReader(state.directory, state.fieldInfos, state.segmentInfo,
        state.context, new MockSingleIntFactory(), state.segmentSuffix);

    TermsIndexReaderBase indexReader;
    boolean success = false;
    try {
      indexReader = new FixedGapTermsIndexReader(state.directory,
                                                       state.fieldInfos,
                                                       state.segmentInfo.name,
                                                       BytesRef.getUTF8SortedAsUnicodeComparator(),
                                                       state.segmentSuffix, state.context);
      success = true;
    } finally {
      if (!success) {
        postingsReader.close();
      }
    }

    success = false;
    try {
      FieldsProducer ret = new BlockTermsReader(indexReader,
                                                state.directory,
                                                state.fieldInfos,
                                                state.segmentInfo,
                                                postingsReader,
                                                state.context,
                                                state.segmentSuffix);
      success = true;
      return ret;
    } finally {
      if (!success) {
        try {
          postingsReader.close();
        } finally {
          indexReader.close();
        }
      }
    }
  }
}


text:
html5-doc-template
==================

A html5 template for documentation


text:
namespace Microsoft.Data.Services.Toolkit
{
    using System;
    using System.Linq;
    using System.Web;

    /// <summary>
    /// Marks an ODataService as OutputCache aware.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class EnableOutputCacheAttribute : Attribute
    {
        /// <summary>
        /// Initializes a new instance of the EnableOutputCacheAttribute class.
        /// </summary>
        public EnableOutputCacheAttribute()
        {
            this.ExpiresInSeconds = 30;
            this.HttpCacheability = HttpCacheability.ServerAndPrivate;
        }

        /// <summary>
        /// Gets or sets a value indicating the expiration time in seconds.
        /// </summary>
        /// <remarks>By default it uses 30 seconds.</remarks>
        public int ExpiresInSeconds { get; set; }

        /// <summary>
        /// Gets or sets a value indicating the HttpCacheability settings
        /// for the current service.
        /// </summary>
        /// <remarks>By default it uses HttpCacheability.ServerAndPrivate</remarks>
        public HttpCacheability HttpCacheability { get; set; }

        /// <summary>
        /// Looks for an OutputCacheSettingsAttribute instance from
        /// the given service type.
        /// </summary>
        /// <param name="serviceType">Type of the service to extract the
        /// OuputCacheSettings instance from.</param>
        /// <returns>Returns an OutputCacheSettingsAttribute instance (null when not present).</returns>
        public static EnableOutputCacheAttribute GetServiceOutputCacheSettings(Type serviceType)
        {
            return serviceType.GetCustomAttributes(typeof(EnableOutputCacheAttribute), false)
                              .Cast<EnableOutputCacheAttribute>()
                              .SingleOrDefault();
        }
    }
}


text:
<?php //-->

/**
 * Twitter error
 *
 * @package    Eden
 * @category   twitter
 * @author     Christian Blanquera cblanquera@openovate.com
 */
class Eden_Twitter_Error extends Eden_Error {
	/* Constants
	-------------------------------*/
	/* Public Properties
	-------------------------------*/
	/* Protected Properties
	-------------------------------*/
	/* Private Properties
	-------------------------------*/
	/* Magic
	-------------------------------*/
	public static function i($message = NULL, $code = 0) {
		$class = __CLASS__;
		return new $class($message, $code);
	}

	/* Public Methods
	-------------------------------*/
	/* Protected Methods
	-------------------------------*/
	/* Private Methods
	-------------------------------*/
}


text:
package com.clicktravel.cheddar.server.rest.resource.status;

public class MaximumWorkRate {

    private int bucketCapacity;
    private long tokenReplacementDelay;

    public int getBucketCapacity() {
        return bucketCapacity;
    }

    public void setBucketCapacity(final int bucketCapacity) {
        this.bucketCapacity = bucketCapacity;
    }

    public void setTokenReplacementDelay(final long tokenReplacementDelay) {
        this.tokenReplacementDelay = tokenReplacementDelay;
    }

    public long getTokenReplacementDelay() {
        return tokenReplacementDelay;
    }

}


text:
class CreateShareAccounts < ActiveRecord::Migration
  def change
    create_table :share_accounts do |t|
      t.integer :share_level
      t.timestamps
    end
  end
end


text:
import { browserHistory } from 'react-router';
import { joinEvents, transformData } from 'd3-bumps-chart';

export const color = {
  cambridgeBlue: '#91B9A4',
  oxfordBlue: '#002147',
};

export const setMap = {
  mays: 'May Bumps',
  lents: 'Lent Bumps',
  town: 'Town Bumps',
  torpids: 'Torpids',
  eights: 'Summer Eights',
};

export const setMapInverse = {
  'May Bumps': 'mays',
  'Lent Bumps': 'lents',
  'Town Bumps': 'town',
  Torpids: 'torpids',
  'Summer Eights': 'eights',
};

export const pickEvents = (
  events,
  gender,
  set,
  yearRange = [-Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY]
) => {
  const transformedEvents = events
    .filter(e => e.gender.toLowerCase() === gender.toLowerCase())
    .filter(e => e.set === set)
    .filter(e => e.year >= yearRange[0] && e.year <= yearRange[1])
    .sort((a, b) => a.year - b.year)
    .map(event => transformData(event));

  return joinEvents(transformedEvents, set, gender);
};

export const setUrl = (set, gender, selectedCrews) => {
  if (selectedCrews.size > 0) {
    browserHistory.push(
      `/${setMapInverse[set]}/${gender.toLowerCase()}/${[...selectedCrews]
        .map(crew => crew.replace(/ /g, '_').replace(/\//g, '-'))
        .join(',')}`
    );
  } else {
    browserHistory.push(`/${setMapInverse[set]}/${gender.toLowerCase()}`);
  }
};


text:
<?
defined('C5_EXECUTE') or die("Access Denied.");
class BlockPermissionResponse extends Concrete5_Model_BlockPermissionResponse {}


text:
<?php

/**
 * The definition of a parameter of a function or procedure.
 */

namespace PhpMyAdmin\SqlParser\Components;

use PhpMyAdmin\SqlParser\Component;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;

/**
 * The definition of a parameter of a function or procedure.
 *
 * @category   Components
 *
 * @license    https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
 */
class ParameterDefinition extends Component
{
    /**
     * The name of the new column.
     *
     * @var string
     */
    public $name;

    /**
     * Parameter's direction (IN, OUT or INOUT).
     *
     * @var string
     */
    public $inOut;

    /**
     * The data type of thew new column.
     *
     * @var DataType
     */
    public $type;

    /**
     * Constructor.
     *
     * @param string $name  Parameter's name.
     * @param string $inOut Parameter's directional type (IN / OUT or None).
     * @param DataType $type Parameter's type.
     */
    public function __construct($name = null, $inOut = null, $type = null)
    {
        $this->name = $name;
        $this->inOut = $inOut;
        $this->type = $type;
    }

    /**
     * @param Parser     $parser  the parser that serves as context
     * @param TokensList $list    the list of tokens that are being parsed
     * @param array      $options parameters for parsing
     *
     * @return ParameterDefinition[]
     */
    public static function parse(Parser $parser, TokensList $list, array $options = array())
    {
        $ret = array();

        $expr = new self();

        /**
         * The state of the parser.
         *
         * Below are the states of the parser.
         *
         *      0 -----------------------[ ( ]------------------------> 1
         *
         *      1 ----------------[ IN / OUT / INOUT ]----------------> 1
         *      1 ----------------------[ name ]----------------------> 2
         *
         *      2 -------------------[ data type ]--------------------> 3
         *
         *      3 ------------------------[ , ]-----------------------> 1
         *      3 ------------------------[ ) ]-----------------------> (END)
         *
         * @var int
         */
        $state = 0;

        for (; $list->idx < $list->count; ++$list->idx) {
            /**
             * Token parsed at this moment.
             *
             * @var Token
             */
            $token = $list->tokens[$list->idx];

            // End of statement.
            if ($token->type === Token::TYPE_DELIMITER) {
                break;
            }

            // Skipping whitespaces and comments.
            if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
                continue;
            }

            if ($state === 0) {
                if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
                    $state = 1;
                }
                continue;
            } elseif ($state === 1) {
                if (($token->value === 'IN') || ($token->value === 'OUT') || ($token->value === 'INOUT')) {
                    $expr->inOut = $token->value;
                    ++$list->idx;
                } elseif ($token->value === ')') {
                    ++$list->idx;
                    break;
                } else {
                    $expr->name = $token->value;
                    $state = 2;
                }
            } elseif ($state === 2) {
                $expr->type = DataType::parse($parser, $list);
                $state = 3;
            } elseif ($state === 3) {
                $ret[] = $expr;
                $expr = new self();
                if ($token->value === ',') {
                    $state = 1;
                } elseif ($token->value === ')') {
                    ++$list->idx;
                    break;
                }
            }
        }

        // Last iteration was not saved.
        if ((isset($expr->name)) && ($expr->name !== '')) {
            $ret[] = $expr;
        }

        --$list->idx;

        return $ret;
    }

    /**
     * @param ParameterDefinition[] $component the component to be built
     * @param array                 $options   parameters for building
     *
     * @return string
     */
    public static function build($component, array $options = array())
    {
        if (is_array($component)) {
            return '(' . implode(', ', $component) . ')';
        }

        $tmp = '';
        if (!empty($component->inOut)) {
            $tmp .= $component->inOut . ' ';
        }

        return trim(
            $tmp . Context::escape($component->name) . ' ' . $component->type
        );
    }
}


text:
#ifndef __GST_I18N_PLUGIN_H__
#define __GST_I18N_PLUGIN_H__

#ifndef GETTEXT_PACKAGE
#error You must define GETTEXT_PACKAGE before including this header.
#endif

#ifdef ENABLE_NLS

#include "gettext.h" /* included with gettext distribution and copied */

/* we want to use shorthand _() for translating and N_() for marking */
#define _(String) dgettext (GETTEXT_PACKAGE, String)
#define N_(String) gettext_noop (String)
/* FIXME: if we need it, we can add Q_ as well, like in glib */

#else
#define _(String) String
#define N_(String) String
#define ngettext(Singular,Plural,Count) ((Count>1)?Plural:Singular)

#endif

#endif /* __GST_I18N_PLUGIN_H__ */


text:
layout: quiz
lesson: 3
segment: 1
---


text:
package main

import "./memberin_extend_c"

func main() {
	t := memberin_extend_c.NewPerson()
	t.SetName("Fred Bloggs")
	if t.GetName() != "FRED BLOGGS" {
		panic("name wrong")
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:id="@+id/map_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" />

    <TableRow
        android:id="@+id/upper_row"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/translucent_background">

        <org.blitzortung.android.app.view.ScaledTextView
            android:id="@+id/status"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginStart="4dp"
            android:layout_marginLeft="4dp"
            android:layout_weight="1"
            android:text=""
            android:textColor="@color/text_foreground"
            android:textSize="14sp"
            local:tablet_scaleable="true" />

        <org.blitzortung.android.app.view.ScaledTextView
            android:id="@+id/warning"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text=""
            android:textColor="@color/text_foreground"
            android:textSize="14sp"
            local:tablet_scaleable="true" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="fill_horizontal|fill_vertical">

            <ImageView
                android:id="@+id/error_indicator"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:src="@android:drawable/stat_notify_error"
                android:contentDescription="@string/error_indicator" />

            <ProgressBar
                android:id="@+id/progress"
                style="?android:attr/progressBarStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true" />

        </RelativeLayout>

    </TableRow>

    <RelativeLayout
        android:id="@+id/map_overlay"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/upper_row">

        <org.blitzortung.android.app.view.LegendView
            android:id="@+id/legend_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            local:tablet_scaleable="true"/>

        <ImageButton
            android:id="@+id/menu"
            android:layout_width="45sp"
            android:layout_height="45sp"
            android:background="@color/translucent_background"
            android:src="@android:drawable/ic_menu_more"
            android:visibility="gone" />

        <ImageButton
            android:id="@+id/historyRew"
            android:layout_width="45sp"
            android:layout_height="45sp"
            android:background="@color/translucent_background"
            android:src="@android:drawable/ic_media_rew"
            android:visibility="gone" />

        <ImageButton
            android:id="@+id/historyFfwd"
            android:layout_width="45sp"
            android:layout_height="45sp"
            android:background="@color/translucent_background"
            android:src="@android:drawable/ic_media_ff"
            android:visibility="gone" />

        <ImageButton
            android:id="@+id/goRealtime"
            android:layout_width="45sp"
            android:layout_height="45sp"
            android:background="@color/translucent_background"
            android:src="@android:drawable/ic_media_next"
            android:visibility="gone" />

        <ImageButton
            android:id="@+id/toggleExtendedMode"
            android:layout_width="45sp"
            android:layout_height="45sp"
            android:background="@color/translucent_background"
            android:enabled="false"
            android:src="@android:drawable/ic_menu_view"
            android:visibility="gone" />

        <org.blitzortung.android.app.view.AlertView
            android:id="@+id/alert_view"
            android:layout_width="90sp"
            android:layout_height="90sp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            local:tablet_scaleable="true"/>

        <org.blitzortung.android.app.view.HistogramView
            android:id="@+id/histogram_view"
            android:layout_width="100sp"
            android:layout_height="70sp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            local:tablet_scaleable="true"/>

    </RelativeLayout>
</RelativeLayout>


text:
<Record>
<Term>Proxorphan</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Opioid Receptor Agonist</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Opioid Receptor Agonist/Proxorphan Tartrate,/NCIThesaurus/Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Drug or Chemical by Structure/Organic Chemical/Alkaloid/Opioid/Proxorphan Tartrate,/NCIThesaurus/Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Analgesic Agent/Proxorphan Tartrate</ClassificationPath>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>NCIThesaurus</BroaderTerm>
<BroaderTerm>Alkaloid</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Opioid</BroaderTerm>
<BroaderTerm>Proxorphan Tartrate</BroaderTerm>
<BroaderTerm>Opioid Receptor Agonist</BroaderTerm>
<BroaderTerm>Drug or Chemical by Structure</BroaderTerm>
<BroaderTerm>Analgesic Agent</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Organic Chemical</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<BroaderTerm>Proxorphan Tartrate,</BroaderTerm>
<Synonym>PROXORPHAN TARTRATE</Synonym>
<Synonym>Proxorphan Tartrate</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
using System.IO;

namespace Yu_Gi_Oh.File_Handling.Utility
{
    public class Dump_Settings
    {
        public Dump_Settings(string outputDirectory)
        {
            OutputDirectory = outputDirectory;

            if (!string.IsNullOrEmpty(OutputDirectory) && !Directory.Exists(OutputDirectory))
                Directory.CreateDirectory(OutputDirectory);

            Deep = true;
        }

        public string OutputDirectory { get; set; }
        public bool Deep { get; set; }
        public bool HumanReadable { get; set; }
    }
}


text:
<?php
namespace datawarehouse\V1\Rest\User;

use Zend\Paginator\Paginator;

class UserCollection extends Paginator
{
}


text:
/* eslint-env mocha */
'use strict'

const assert = require('assert')
const assertThrows = require('./assertThrows')
const ValueObject = require('..')

describe('A defined ValueObject', () => {
  it('can be subclassed', () => {
    class Base extends ValueObject.define({ id: 'string', seq: 'number' }) {}

    class Sub extends Base {
      static get schema() {
        return super.schema.extend({ city: 'string', owner: 'string' })
      }
    }

    new Sub({ id: 'xyz', seq: 4, city: 'London', owner: 'Aslak' })
    assertThrows(
      () => new Sub({ seq: 4, city: 'London', owner: 'Aslak' }),
      'Sub was constructed with invalid property values\n' +
        '  Expected: { id:string, seq:number, city:string, owner:string }\n' +
        '  Actual:   { seq:number, city:string, owner:string }\n' +
        '  id is invalid:\n' +
        '    Property is missing',
      error => assert(error instanceof ValueObject.ValueObjectError)
    )
  })

  it('calls the constructor of each superclass', () => {
    class Top extends ValueObject.define({ x: 'string' }) {
      constructor(args) {
        super(Object.assign({ x: '1' }, args))
      }
    }

    class Middle extends Top {
      constructor(args) {
        super(Object.assign({ y: '2' }, args))
      }

      static get schema() {
        return super.schema.extend({ y: 'string' })
      }
    }

    class Bottom extends Middle {
      constructor() {
        super({ z: '3' })
      }

      static get schema() {
        return super.schema.extend({ z: 'string' })
      }
    }

    const bottom = new Bottom()
    assert.equal(bottom.x, '1')
    assert.equal(bottom.y, '2')
    assert.equal(bottom.z, '3')
  })

  it('can be subclassed many times', () => {
    class Top extends ValueObject.define({ x: 'string' }) {}

    class B1 extends Top {
      static get schema() {
        return super.schema.extend({ y: 'string' })
      }
    }

    class B2 extends Top {
      static get schema() {
        return super.schema.extend({ z: 'string' })
      }
    }

    const b1 = new B1({ x: 'X', y: 'Y' })
    const b2 = new B2({ x: 'X', z: 'Z' })
    assert.equal(b1.y, 'Y')
    assert.equal(b2.z, 'Z')
  })

  it('accepts new property type definitions', () => {
    ValueObject.definePropertyType('money', () => ({
      coerce(value) {
        const parts = value.split(' ')
        return { value: { amount: Number(parts[0]), currency: parts[1] } }
      },

      areEqual(a, b) {
        return a.currency == b.currency && a.amount == b.amount
      }
    }))
    const Allowance = ValueObject.define({ cash: 'money' })
    const allowance = new Allowance({ cash: '123.00 GBP' })
    assert.equal(allowance.cash.amount, 123)
    assert.equal(allowance.cash.currency, 'GBP')
    assert(allowance.isEqualTo(allowance))
    assert(!allowance.isEqualTo(allowance.with({ cash: '321.00 GBP' })))
  })
})


text:
// this data can come from firebase
var bun = 'vs food';
var ENV = 'dev';
var PORT = 3000;
var boolTrue = true;
var boolFalse = false;
var globalObj = {
  foo: 'bar',
  baz: 'qux'
};

var app = document.getElementById('app');

console.time && console.time('mount');
console.time && console.time('createAppData');
var data = quenchVue.createAppData(app);
console.timeEnd && console.timeEnd('createAppData');
console.time && console.time('createAppTemplate');
var template = quenchVue.createAppTemplate(app);
console.timeEnd && console.timeEnd('createAppTemplate');

console.log('data', data);
// console.log('outerHTML', app.outerHTML);
// console.log('template', template);

Vue.component('my-component', {
  props: ['message'],
  template: '
My component {{ message }} and hydrated
'
});

var App = new Vue({
  el: app,
  data: data,
  template: template,
  methods: {
    addName: function addName() {
      this.names.push({
        value: Math.random()
      });
    },
    deleteTodo: function deleteTodo() {
      this.todos.pop();
    }
  },
  mounted: function mounted() {
    console.timeEnd && console.timeEnd('mount');
  }
});


text:
package org.apache.hadoop.yarn.server.nodemanager.amrmproxy;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.token.SecretManager;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;
import org.apache.hadoop.yarn.server.api.records.MasterKey;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService.RecoveredAMRMProxyState;
import org.apache.hadoop.yarn.server.security.MasterKeyData;

import com.google.common.annotations.VisibleForTesting;

/**
 * This secret manager instance is used by the AMRMProxyService to generate and
 * manage tokens.
 */
public class AMRMProxyTokenSecretManager extends
    SecretManager<AMRMTokenIdentifier> {

  private static final Log LOG = LogFactory
      .getLog(AMRMProxyTokenSecretManager.class);

  private int serialNo = new SecureRandom().nextInt();
  private MasterKeyData nextMasterKey;
  private MasterKeyData currentMasterKey;

  private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
  private final Lock readLock = readWriteLock.readLock();
  private final Lock writeLock = readWriteLock.writeLock();

  private final Timer timer;
  private long rollingInterval;
  private long activationDelay;

  private NMStateStoreService nmStateStore;

  private final Set<ApplicationAttemptId> appAttemptSet =
      new HashSet<ApplicationAttemptId>();

  /**
   * Create an {@link AMRMProxyTokenSecretManager}.
   * @param nmStateStoreService NM state store
   */
  public AMRMProxyTokenSecretManager(NMStateStoreService nmStateStoreService) {
    this.timer = new Timer();
    this.nmStateStore = nmStateStoreService;
  }

  public void init(Configuration conf) {
    this.rollingInterval =
        conf.getLong(
            YarnConfiguration.RM_AMRM_TOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS,
            YarnConfiguration.DEFAULT_RM_AMRM_TOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS) * 1000;
    // Adding delay = 1.5 * expiry interval makes sure that all active AMs get
    // the updated shared-key.
    this.activationDelay =
        (long) (conf.getLong(YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS,
            YarnConfiguration.DEFAULT_RM_AM_EXPIRY_INTERVAL_MS) * 1.5);
    LOG.info("AMRMTokenKeyRollingInterval: " + this.rollingInterval
        + "ms and AMRMTokenKeyActivationDelay: " + this.activationDelay
        + " ms");
    if (rollingInterval <= activationDelay * 2) {
      throw new IllegalArgumentException(
          YarnConfiguration.RM_AMRM_TOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS
              + " should be more than 3 X "
              + YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS);
    }
  }

  public void start() {
    if (this.currentMasterKey == null) {
      this.currentMasterKey = createNewMasterKey();
      if (this.nmStateStore != null) {
        try {
          this.nmStateStore.storeAMRMProxyCurrentMasterKey(
              this.currentMasterKey.getMasterKey());
        } catch (IOException e) {
          LOG.error("Unable to update current master key in state store", e);
        }
      }
    }
    this.timer.scheduleAtFixedRate(new MasterKeyRoller(), rollingInterval,
        rollingInterval);
  }

  public void stop() {
    this.timer.cancel();
  }

  @VisibleForTesting
  public void setNMStateStoreService(NMStateStoreService nmStateStoreService) {
    this.nmStateStore = nmStateStoreService;
  }

  public void applicationMasterFinished(ApplicationAttemptId appAttemptId) {
    this.writeLock.lock();
    try {
      LOG.info("Application finished, removing password for "
          + appAttemptId);
      this.appAttemptSet.remove(appAttemptId);
    } finally {
      this.writeLock.unlock();
    }
  }

  private class MasterKeyRoller extends TimerTask {
    @Override
    public void run() {
      rollMasterKey();
    }
  }

  @Private
  @VisibleForTesting
  public void rollMasterKey() {
    this.writeLock.lock();
    try {
      LOG.info("Rolling master-key for amrm-tokens");
      this.nextMasterKey = createNewMasterKey();
      if (this.nmStateStore != null) {
        try {
          this.nmStateStore
              .storeAMRMProxyNextMasterKey(this.nextMasterKey.getMasterKey());
        } catch (IOException e) {
          LOG.error("Unable to update next master key in state store", e);
        }
      }

      this.timer.schedule(new NextKeyActivator(), this.activationDelay);
    } finally {
      this.writeLock.unlock();
    }
  }

  private class NextKeyActivator extends TimerTask {
    @Override
    public void run() {
      activateNextMasterKey();
    }
  }

  @Private
  @VisibleForTesting
  public void activateNextMasterKey() {
    this.writeLock.lock();
    try {
      LOG.info("Activating next master key with id: "
          + this.nextMasterKey.getMasterKey().getKeyId());
      this.currentMasterKey = this.nextMasterKey;
      this.nextMasterKey = null;
      if (this.nmStateStore != null) {
        try {
          this.nmStateStore.storeAMRMProxyCurrentMasterKey(
              this.currentMasterKey.getMasterKey());
          this.nmStateStore.storeAMRMProxyNextMasterKey(null);
        } catch (IOException e) {
          LOG.error("Unable to update current master key in state store", e);
        }
      }
    } finally {
      this.writeLock.unlock();
    }
  }

  @Private
  @VisibleForTesting
  public MasterKeyData createNewMasterKey() {
    this.writeLock.lock();
    try {
      return new MasterKeyData(serialNo++, generateSecret());
    } finally {
      this.writeLock.unlock();
    }
  }

  public Token<AMRMTokenIdentifier> createAndGetAMRMToken(
      ApplicationAttemptId appAttemptId) {
    this.writeLock.lock();
    try {
      LOG.info("Create AMRMToken for ApplicationAttempt: " + appAttemptId);
      AMRMTokenIdentifier identifier =
          new AMRMTokenIdentifier(appAttemptId, getMasterKey()
              .getMasterKey().getKeyId());
      byte[] password = this.createPassword(identifier);
      appAttemptSet.add(appAttemptId);
      return new Token<AMRMTokenIdentifier>(identifier.getBytes(),
          password, identifier.getKind(), new Text());
    } finally {
      this.writeLock.unlock();
    }
  }

  // If nextMasterKey is not Null, then return nextMasterKey
  // otherwise return currentMasterKey.
  @VisibleForTesting
  public MasterKeyData getMasterKey() {
    this.readLock.lock();
    try {
      return nextMasterKey == null ? currentMasterKey : nextMasterKey;
    } finally {
      this.readLock.unlock();
    }
  }

  /**
   * Retrieve the password for the given {@link AMRMTokenIdentifier}. Used by
   * RPC layer to validate a remote {@link AMRMTokenIdentifier}.
   */
  @Override
  public byte[] retrievePassword(AMRMTokenIdentifier identifier)
      throws InvalidToken {
    this.readLock.lock();
    try {
      ApplicationAttemptId applicationAttemptId =
          identifier.getApplicationAttemptId();
      if (LOG.isDebugEnabled()) {
        LOG.debug("Trying to retrieve password for "
            + applicationAttemptId);
      }
      if (!appAttemptSet.contains(applicationAttemptId)) {
        throw new InvalidToken(applicationAttemptId
            + " not found in AMRMProxyTokenSecretManager.");
      }
      if (identifier.getKeyId() == this.currentMasterKey.getMasterKey()
          .getKeyId()) {
        return createPassword(identifier.getBytes(),
            this.currentMasterKey.getSecretKey());
      } else if (nextMasterKey != null
          && identifier.getKeyId() == this.nextMasterKey.getMasterKey()
              .getKeyId()) {
        return createPassword(identifier.getBytes(),
            this.nextMasterKey.getSecretKey());
      }
      throw new InvalidToken("Invalid AMRMToken from "
          + applicationAttemptId);
    } finally {
      this.readLock.unlock();
    }
  }

  /**
   * Creates an empty TokenId to be used for de-serializing an
   * {@link AMRMTokenIdentifier} by the RPC layer.
   */
  @Override
  public AMRMTokenIdentifier createIdentifier() {
    return new AMRMTokenIdentifier();
  }

  @Private
  @VisibleForTesting
  public MasterKeyData getCurrentMasterKeyData() {
    this.readLock.lock();
    try {
      return this.currentMasterKey;
    } finally {
      this.readLock.unlock();
    }
  }

  @Private
  @VisibleForTesting
  public MasterKeyData getNextMasterKeyData() {
    this.readLock.lock();
    try {
      return this.nextMasterKey;
    } finally {
      this.readLock.unlock();
    }
  }

  @Override
  @Private
  protected byte[] createPassword(AMRMTokenIdentifier identifier) {
    this.readLock.lock();
    try {
      ApplicationAttemptId applicationAttemptId =
          identifier.getApplicationAttemptId();
      LOG.info("Creating password for " + applicationAttemptId);
      return createPassword(identifier.getBytes(), getMasterKey()
          .getSecretKey());
    } finally {
      this.readLock.unlock();
    }
  }

  /**
   * Recover secretManager from state store. Called after serviceInit before
   * serviceStart.
   *
   * @param state the state to recover from
   */
  public void recover(RecoveredAMRMProxyState state) {
    if (state != null) {
      // recover the current master key
      MasterKey currentKey = state.getCurrentMasterKey();
      if (currentKey != null) {
        this.currentMasterKey = new MasterKeyData(currentKey,
            createSecretKey(currentKey.getBytes().array()));
      } else {
        LOG.warn("No current master key recovered from NM StateStore"
            + " for AMRMProxyTokenSecretManager");
      }

      // recover the next master key if not null
      MasterKey nextKey = state.getNextMasterKey();
      if (nextKey != null) {
        this.nextMasterKey = new MasterKeyData(nextKey,
            createSecretKey(nextKey.getBytes().array()));
        this.timer.schedule(new NextKeyActivator(), this.activationDelay);
      }
    }
  }

}


text:
package org.jitsi.videobridge.rest.root.colibri.mucclient;

import org.jitsi.videobridge.rest.*;
import org.jitsi.videobridge.rest.annotations.*;
import org.jitsi.videobridge.xmpp.*;
import org.json.simple.*;
import org.json.simple.parser.*;

import javax.inject.*;
import javax.servlet.http.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;

/**
 * Add or remove XMPP environments to which the bridge will connect
 */
@Path("/colibri/muc-client")
@EnabledByConfig(RestApis.COLIBRI)
public class MucClient
{
    @Inject
    protected XmppConnection xmppConnection;

    @Path("/add")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response addMucClient(String requestBody) throws ParseException
    {
        //NOTE: unfortunately MucClientConfiguration is not a compliant bean (it doesn't have
        // a no-arg ctor) so we can't parse the json directly into a MucClientConfiguration
        // instance and just take that as an argument here, we have to read the json
        // ourselves.
        Object o = new JSONParser().parse(requestBody);
        if (!(o instanceof JSONObject))
        {
            return Response.status(HttpServletResponse.SC_BAD_REQUEST).build();
        }
        if (xmppConnection.addMucClient((JSONObject)o))
        {
            return Response.ok().build();
        }
        return Response.status(HttpServletResponse.SC_BAD_REQUEST).build();
    }

    @Path("/remove")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response removeMucClient(String requestBody) throws ParseException
    {
        Object o = new JSONParser().parse(requestBody);
        if (!(o instanceof JSONObject))
        {
            return Response.status(HttpServletResponse.SC_BAD_REQUEST).build();
        }
        if (xmppConnection.removeMucClient((JSONObject)o))
        {
            return Response.ok().build();
        }
        return Response.status(HttpServletResponse.SC_BAD_REQUEST).build();
    }

    @Path("/list")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String listMucClientIDs()
    {
        return xmppConnection.getMucClientIds();
    }
}


text:
'use strict';

dashboardApp.directive('myOnKeyDownCall', function (itRequestService) {
    return function ($scope, element, attrs) {
        element.bind('keyup', function (event) {
            if (event.keyCode === 27 || $scope.filtertext.length > 2) {
                for (var item in $scope.tasks) {
                    if (event.keyCode === 13 && $scope.tasks[item].hide === false) {
                        $scope.tasks[item].selected = true;
                    } else {
                        if (event.keyCode === 27 || $scope.tasks[item].name.search($scope.filtertext) !== -1) {
                            $scope.tasks[item].hide = false;
                        }
                        else {
                            $scope.tasks[item].hide = true;
                        }
                    }
                }
                if (event.keyCode === 27 || event.keyCode === 13) {

                    if (event.keyCode === 13) {
                        $scope.message = 'به روز رسانی....';
                        itRequestService.updatetasks(function () {setTimeout(function(){$scope.message = ''; $scope.$apply();}, 300);}, $scope.tasks);
                    } else {
                        $scope.filtertext = '';
                    }
                }
            }
            $scope.$apply();
        });
    };
});


text:
Inverse the style of any component for light or dark backgrounds.

## Usage

Add the `.uk-light` class to improve the visibility of objects on dark backgrounds in a light style. When using a dark style, add the `.uk-dark` class to elements on a light background.

**Note** Only one class will come to effect, depending on the style you are using. For example, when using a style with a light background, you can only apply the `.uk-light` class to optimize content on dark backgrounds, as text will already be displayed in a dark color on light backgrounds — and vice versa.

```html
<div class="uk-light"></div>

<div class="uk-dark"></div>
```

```html : uikit
<div class="uk-child-width-1-2@s" uk-grid>
    <div>
        <div class="uk-light uk-background-secondary uk-padding">
            <h3>Light</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
            <button class="uk-button uk-button-default">Button</button>
        </div>
    </div>
    <div>
        <div class="uk-dark uk-background-muted uk-padding">
            <h3>Dark</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
            <button class="uk-button uk-button-default">Button</button>
        </div>
    </div>
</div>
```

**Note** Some modifiers from the [Section](section.md), [Card](card.md), [Tile](tile.md), [Overlay](overlay.md) and [Off-canvas](offcanvas.md) component are extending the inverse style automatically, so you don't have to add any class.

***

## Customize using Less

The Inverse component includes additional styles to implement the flexible inverse behaviour. If your project does not make use of these styles, you can leave [disable the Inverse component](less.md#disable-inverse-component) when compiling Less.


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.containers;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.lang.ref.ReferenceQueue;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Base class for concurrent (soft/weak) key:K -> strong value:V map
 * Null keys are NOT allowed
 * Null values are NOT allowed
 */
abstract class ConcurrentRefHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>, HashingStrategy<K> {
  final ReferenceQueue<K> myReferenceQueue = new ReferenceQueue<>();
  private final ConcurrentMap<KeyReference<K>, V> myMap; // hashing strategy must be canonical, we compute corresponding hash codes using our own myHashingStrategy
  private final @NotNull HashingStrategy<? super K> myHashingStrategy;

  private static final float LOAD_FACTOR = 0.75f;
  static final int DEFAULT_CAPACITY = 16;
  static final int DEFAULT_CONCURRENCY_LEVEL = Math.min(Runtime.getRuntime().availableProcessors(), 4);

  @FunctionalInterface
  interface KeyReference<K> {
    K get();

    // In case of gced reference, equality must be identity-based (to be able to remove stale key in processQueue), otherwise it's myHashingStrategy-based
    @Override
    boolean equals(Object o);

    @Override
    int hashCode();
  }

  abstract @NotNull KeyReference<K> createKeyReference(@NotNull K key, @NotNull HashingStrategy<? super K> hashingStrategy);

  @NotNull
  private KeyReference<K> createKeyReference(@NotNull K key) {
    return createKeyReference(key, myHashingStrategy);
  }

  // returns true if some keys were processed
  private boolean processQueue() {
    KeyReference<K> wk;
    boolean processed = false;
    //noinspection unchecked
    while ((wk = (KeyReference<K>)myReferenceQueue.poll()) != null) {
      myMap.remove(wk);
      processed = true;
    }
    return processed;
  }
  ConcurrentRefHashMap() {
    this(DEFAULT_CAPACITY);
  }

  private ConcurrentRefHashMap(int initialCapacity) {
    this(initialCapacity, LOAD_FACTOR);
  }

  private static final HashingStrategy<?> THIS = new HashingStrategy<Object>() {
    @Override
    public int hashCode(Object object) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean equals(Object o1, Object o2) {
      throw new UnsupportedOperationException();
    }
  };

  private ConcurrentRefHashMap(int initialCapacity, float loadFactor) {
    //noinspection unchecked
    this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL, (HashingStrategy<? super K>)THIS);
  }

  ConcurrentRefHashMap(@NotNull HashingStrategy<? super K> hashingStrategy) {
    this(DEFAULT_CAPACITY, LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, hashingStrategy);
  }

  ConcurrentRefHashMap(int initialCapacity,
                       float loadFactor,
                       int concurrencyLevel,
                       @Nullable HashingStrategy<? super K> hashingStrategy) {
    myHashingStrategy = hashingStrategy == THIS ? this : (hashingStrategy == null ? HashingStrategy.canonical() : hashingStrategy);
    myMap = new ConcurrentHashMap<>(initialCapacity, loadFactor, concurrencyLevel);
  }

  @Override
  public int size() {
    return entrySet().size();
  }

  @Override
  public boolean isEmpty() {
    // make easier and alloc-free call to myMap first
    return myMap.isEmpty() || entrySet().isEmpty();
  }

  @Override
  public boolean containsKey(@NotNull Object key) {
    if (myMap.isEmpty()) {
      return false;
    }
    HardKey<K> hardKey = createHardKey(key);
    try {
      return myMap.containsKey(hardKey);
    }
    finally {
      hardKey.clear();
    }
  }

  @Override
  public boolean containsValue(Object value) {
    throw RefValueHashMapUtil.pointlessContainsValue();
  }

  private static class HardKey<K> implements KeyReference<K> {
    private K myKey;
    private int myHash;

    void setKey(K key, final int hash) {
      myKey = key;
      myHash = hash;
    }

    @Override
    public K get() {
      return myKey;
    }

    @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
    @Override
    public boolean equals(Object o) {
      return o.equals(this); // see com.intellij.util.containers.ConcurrentSoftHashMap.SoftKey or com.intellij.util.containers.ConcurrentWeakHashMap.WeakKey
    }

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

    private void clear() {
      setKey(null, 0);
    }
  }
  private static final ThreadLocal<HardKey<?>> HARD_KEY = ThreadLocal.withInitial(() -> new HardKey<>());

  @NotNull
  private HardKey<K> createHardKey(@NotNull Object o) {
    //noinspection unchecked
    K key = (K)o;
    //noinspection unchecked
    HardKey<K> hardKey = (HardKey<K>)HARD_KEY.get();
    hardKey.setKey(key, myHashingStrategy.hashCode(key));
    return hardKey;
  }

  @Override
  public V get(@NotNull Object key) {
    if (myMap.isEmpty()) return null;
    HardKey<K> hardKey = createHardKey(key);
    try {
      return myMap.get(hardKey);
    }
    finally {
      hardKey.clear();
    }
  }

  @Override
  public V put(@NotNull K key, @NotNull V value) {
    KeyReference<K> weakKey = createKeyReference(key);
    V prev = myMap.put(weakKey, value);
    processQueue();
    return prev;
  }

  @Override
  public V remove(@NotNull Object key) {
    HardKey<?> hardKey = createHardKey(key);
    try {
      return myMap.remove(hardKey);
    }
    finally {
      processQueue();
      hardKey.clear();
    }
  }

  @Override
  public void clear() {
    myMap.clear();
    processQueue();
  }

  private static final class RefEntry<K, V> implements Map.Entry<K, V> {
    private final Map.Entry<?, V> ent;
    private final K key; /* Strong reference to key, so that the GC
                                 will leave it alone as long as this Entry
                                 exists */

    RefEntry(@NotNull Map.Entry<?, V> ent, @Nullable K key) {
      this.ent = ent;
      this.key = key;
    }

    @Override
    public K getKey() {
      return key;
    }

    @Override
    public V getValue() {
      return ent.getValue();
    }

    @Override
    public V setValue(@NotNull V value) {
      return ent.setValue(value);
    }

    @Override
    public boolean equals(Object o) {
      if (!(o instanceof Map.Entry)) return false;
      //noinspection unchecked
      Map.Entry<K,V> e = (Map.Entry<K,V>)o;
      return Objects.equals(key, e.getKey()) && Objects.equals(getValue(), e.getValue());
    }

    @Override
    public int hashCode() {
      Object v;
      return (key == null ? 0 : key.hashCode()) ^ ((v = getValue()) == null ? 0 : v.hashCode());
    }
  }

  /* Internal class for entry sets */
  private final class EntrySet extends AbstractSet<Map.Entry<K, V>> {
    private final Set<Map.Entry<KeyReference<K>, V>> hashEntrySet = myMap.entrySet();

    @NotNull
    @Override
    public Iterator<Map.Entry<K, V>> iterator() {
      return new Iterator<Map.Entry<K, V>>() {
        private final Iterator<Map.Entry<KeyReference<K>, V>> hashIterator = hashEntrySet.iterator();
        private RefEntry<K, V> next;

        @Override
        public boolean hasNext() {
          while (hashIterator.hasNext()) {
            Map.Entry<KeyReference<K>, V> ent = hashIterator.next();
            KeyReference<K> wk = ent.getKey();
            K k = null;
            if (wk != null && (k = wk.get()) == null) {
              /* Weak key has been cleared by GC */
              continue;
            }
            next = new RefEntry<>(ent, k);
            return true;
          }
          return false;
        }

        @Override
        public Map.Entry<K, V> next() {
          if (next == null && !hasNext()) {
            throw new NoSuchElementException();
          }
          RefEntry<K, V> e = next;
          next = null;
          return e;
        }

        @Override
        public void remove() {
          hashIterator.remove();
        }
      };
    }

    @Override
    public boolean isEmpty() {
      for (Entry<KeyReference<K>, V> ent : hashEntrySet) {
        KeyReference<K> wk = ent.getKey();
        if (wk != null && wk.get() == null) {
          continue;
        }
        return false;
      }
      return true;
    }

    @Override
    public int size() {
      int j = 0;
      for (Iterator<Entry<K, V>> i = iterator(); i.hasNext(); i.next()) j++;
      return j;
    }

    @Override
    public boolean remove(Object o) {
      if (!(o instanceof Map.Entry)) return false;
      //noinspection unchecked
      Map.Entry<K,V> e = (Map.Entry<K,V>)o;
      V ev = e.getValue();

      HardKey<K> key = createHardKey(e.getKey());

      boolean toRemove;
      try {
        V hv = myMap.get(key);
        toRemove = hv == null ? ev == null && myMap.containsKey(key) : hv.equals(ev);
        if (toRemove) {
          myMap.remove(key);
        }
      }
      finally {
        key.clear();
      }
      processQueue();

      return toRemove;
    }

    @Override
    public int hashCode() {
      int h = 0;
      for (Map.Entry<KeyReference<K>, V> entry : hashEntrySet) {
        KeyReference<K> wk = entry.getKey();
        if (wk == null) continue;
        Object v;
        h += wk.hashCode() ^ ((v = entry.getValue()) == null ? 0 : v.hashCode());
      }
      return h;
    }
  }

  private Set<Map.Entry<K, V>> entrySet;

  @NotNull
  @Override
  public Set<Map.Entry<K, V>> entrySet() {
    Set<Entry<K, V>> es = entrySet;
    if (es == null) entrySet = es = new EntrySet();
    return es;
  }

  @Override
  public V putIfAbsent(@NotNull K key, @NotNull V value) {
    V prev = myMap.putIfAbsent(createKeyReference(key), value);
    processQueue();
    return prev;
  }

  @Override
  public boolean remove(@NotNull Object key, @NotNull Object value) {
    //noinspection unchecked
    boolean removed = myMap.remove(createKeyReference((K)key), value);
    processQueue();
    return removed;
  }

  @Override
  public boolean replace(@NotNull K key, @NotNull final V oldValue, @NotNull final V newValue) {
    boolean replaced = myMap.replace(createKeyReference(key), oldValue, newValue);
    processQueue();
    return replaced;
  }

  @Override
  public V replace(@NotNull K key, @NotNull final V value) {
    V replaced = myMap.replace(createKeyReference(key), value);
    processQueue();
    return replaced;
  }

  // MAKE SURE IT CONSISTENT WITH com.intellij.util.containers.ConcurrentHashMap
  @Override
  public int hashCode(@Nullable K object) {
    int h = object == null ? 0 : object.hashCode();
    h += ~(h << 9);
    h ^= h >>> 14;
    h += h << 4;
    h ^= h >>> 10;
    return h;
  }

  @Override
  public boolean equals(K o1, K o2) {
    return Objects.equals(o1, o2);
  }
}


text:
class AddIndexToTables < ActiveRecord::Migration
  def change
    add_index :contacts, :name
    add_index :contacts, :birthday
    add_index :contacts, :created_at
    add_index :users, :name
  end
end


text:
package net.yanzm.flashairdev;

import java.util.Calendar;

import android.text.format.DateFormat;

public class FlashAirFileInfo {

  public FlashAirFileInfo(String info, String dir) {
    int start;
    int end;

    start = info.lastIndexOf(",");
    int time = Integer.parseInt(info.substring(start + 1).trim());

    end = start;
    start = info.lastIndexOf(",", end - 1);
    int date = Integer.parseInt(info.substring(start + 1, end).trim());

    end = start;
    start = info.lastIndexOf(",", end - 1);
    mAttribute = Integer.parseInt(info.substring(start + 1, end).trim());

    end = start;
    start = info.lastIndexOf(",", end - 1);
    mSize = info.substring(start + 1, end);

    end = start;
    int dirLength = dir.length();
    if (dir.equals("/")) {
        dirLength = 0;
    }
    start = info.indexOf(",", dirLength);
    mFileName = info.substring(start + 1, end);

    mDir = dir;

    int year = ((date >> 9) & 0x0000007f) + 1980;
    int month = (date >> 5) & 0x0000000f - 1;
    int day = (date) & 0x0000001f;

    int hourOfDay = (time >> 11) & 0x0000001f;
    int minute = (time >> 5) & 0x0000003f;
    int second = ((time) & 0x0000001f) * 2;

    mCalendar = Calendar.getInstance();
    mCalendar.set(year, month, day, hourOfDay, minute, second);
  }

  public String mDir;
  public String mFileName;
  public String mSize;
  public int mAttribute;
  public Calendar mCalendar;

  public static final int ATTR_MASK_ARCHIVE = 0x00000020;
  public static final int ATTR_MASK_DIRECTORY = 0x00000010;
  public static final int ATTR_MASK_VOLUME = 0x00000008;
  public static final int ATTR_MASK_SYSTEM_FILE = 0x00000004;
  public static final int ATTR_MASK_HIDDEN_FILE = 0x00000002;
  public static final int ATTR_MASK_READ_ONLY = 0x00000001;

  public boolean isDirectory() {
    return (mAttribute & ATTR_MASK_DIRECTORY) > 0;
  }

  @Override
  public String toString() {
    return "DIR=" + mDir + " FILENAME=" + mFileName + " SIZE=" + mSize
        + " ATTRIBUTE=" + mAttribute + " DATE="
        + DateFormat.format("yyyy-MM-dd kk:mm:ss", mCalendar);
  }
}


text:
package org.hammerlab.varcrunch.filters;

import htsjdk.samtools.SAMRecord;
import org.apache.crunch.FilterFn;
import org.seqdoop.hadoop_bam.SAMRecordWritable;

public class UnmappedReadFilter extends FilterFn<SAMRecordWritable> {
    @Override
    public boolean accept(SAMRecordWritable input) {
        return input.get().getReadUnmappedFlag();
    }
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>Current Property</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

LevelCollection.ILevelCollectionEnumerator.Current Property

 Gets the current element in the collection.

        [Visual Basic]

Property Current As Level

        [C#]

        Level Current {get;}

See Also

        LevelCollection.ILevelCollectionEnumerator Interface | log4net.Core Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="Current property">
        </param>
        <param name="Keyword" value="Current property, LevelCollection.ILevelCollectionEnumerator interface">
        </param>
        <param name="Keyword" value="LevelCollection.ILevelCollectionEnumerator.Current property">
        </param>
      </object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
package org.springframework.boot;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * Interface used to indicate that a bean should run when it is contained within
 * a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 *

 * If you need access to {@link ApplicationArguments} instead of the raw String array
 * consider using {@link ApplicationRunner}.
 *
 * @author Dave Syer
 * @see ApplicationRunner
 */
@FunctionalInterface
public interface CommandLineRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming main method arguments
	 * @throws Exception on error
	 */
	void run(String... args) throws Exception;

}


text:
package com.github.hurshi.app_kotlin;

import android.app.Activity;
import android.app.Application;

import javax.inject.Inject;

import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.HasActivityInjector;
import github.hurshi.daggervminjector.extension.DaggerVM;
import github.hurshi.daggervminjector.extension.HasDaggerVMInjector;

/**
 * Created by gavin on 2017/10/24.
 */

public class App extends Application implements HasActivityInjector, HasDaggerVMInjector {

    @Inject
    DispatchingAndroidInjector<Activity> activityInjector;

    @Inject
    DispatchingAndroidInjector<DaggerVM> daggerVmInjector;

    @Override
    public void onCreate() {
        super.onCreate();
        DaggerAppComponent.builder()
                .build()
                .inject(this);
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return activityInjector;
    }

    @Override
    public AndroidInjector<DaggerVM> daggerVMInjector() {
        return daggerVmInjector;
    }
}


text:
cask :v1 => 'safemonk' do
  version :latest
  sha256 :no_check

  url 'https://www.safemonk.com/downloads/osx'
  appcast 'https://www.safemonk.com:/data/client/osx/appcast.xml'
  homepage 'https://www.safemonk.com/'
  license :unknown    # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder

  app 'SafeMonk.app'
end


text:
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.

Planned sample transfer mapper.
"""
from sqlalchemy.orm import mapper
from sqlalchemy.orm import relationship

from thelma.entities.liquidtransfer import PlannedSampleTransfer
from thelma.entities.liquidtransfer import TRANSFER_TYPES
from thelma.entities.rack import RackPosition

__docformat__ = 'reStructuredText en'
__all__ = ['create_mapper']

def create_mapper(planned_liquid_transfer_mapper, planned_sample_transfer_tbl,
                  rack_position_tbl):
    "Mapper factory."
    pst = planned_sample_transfer_tbl
    rp = rack_position_tbl
    m = mapper(PlannedSampleTransfer, planned_sample_transfer_tbl,
               inherits=planned_liquid_transfer_mapper,
               properties=dict(
                    _source_position=relationship(RackPosition, uselist=False,
                            primaryjoin=(pst.c.source_position_id == \
                                         rp.c.rack_position_id)),
                    _target_position=relationship(RackPosition, uselist=False,
                            primaryjoin=(pst.c.target_position_id == \
                                         rp.c.rack_position_id))
                               ),
               polymorphic_identity=TRANSFER_TYPES.SAMPLE_TRANSFER,
               )
    return m


text:
'use strict';

describe('Directive: zen-focusin zen-focusout', function() {

	beforeEach(module('ngZenApp'));

	var $timeout;
	var $window;
	var scope;
	var element;
	var compileAndDigest;

	beforeEach(inject(function($compile, $rootScope, $document, _$timeout_, _$window_) {

		$timeout = _$timeout_;
		$window = _$window_;
		scope = $rootScope.$new();

		compileAndDigest = function(template) {
			element = $compile(template)(scope);
			angular.element($document[0].body).append(element);

			scope.$digest();
		};
	}));

	afterEach(function() {
		element.remove();
	});

	it('should fire focusin and focusout events when focus changes', function() {

		scope.focusIn = function() {};
		scope.focusOut = function() {};
		spyOn(scope, 'focusIn');
		spyOn(scope, 'focusOut');

		// we define directives on parent element
		// as events are expected to bubble up
		compileAndDigest(
			'
' +
			'<input></input>' +
			'
');

		var inputs = element.find('input');

		/*var userAgent = $window.navigator.userAgent;
		if (/firefox/i.test(userAgent)) {
			// Firefox does not support these events
			triggerEvent(inputs[0], 'focus');
			triggerEvent(inputs[0], 'blur');
			scope.focusIn.should.not.have.been.called;
			scope.focusOut.should.not.have.been.called;

		} else*/ {
			triggerEvent(inputs[0], 'focus');
			expect(scope.focusIn).toHaveBeenCalledTimes(1);
			expect(scope.focusOut).not.toHaveBeenCalled();

			triggerEvent(inputs[0], 'blur');
			expect(scope.focusIn).toHaveBeenCalledTimes(1);
			expect(scope.focusOut).toHaveBeenCalledTimes(1);
		}
	});
});


text:
var service = require('../services/note');
var Note = require('../models/note');

exports.list = function(req, res, next) {
  var notes = service.list();

  res.json(200, {'notes': notes});
};

exports.create = function (req, res, next) {
  var index = req.body.index;
  var author = req.body.author;
  var content = req.body.content;

  var note = new Note(index, author, content);

  service.create(note, function (err, res) {
    if (err) next(err);
    res.json(200);
  });
};

exports.update = function (req, res, next) {
  var query = {
    _id: req.params.id,
    user: req.headers.user
  };

  var todo = {
    'title': req.body.title,
    'content': req.body.content
  };

  Todo
    .findOneAndUpdate(query, todo)
    .done(function (todo) {
      if (!todo) {
        var err = new Error('Not updated. Todo doesn\'t exists');
        err.name = 'ValidationError';
        return next(err);
      }
      res.json(200);
    }, function (err) {
      next(err);
    });
};

exports.remove = function (req, res, next) {
  var query = {
    _id: req.params.id,
    user: req.headers.user
  };

  Todo
    .findOneAndRemove(query)
    .done(function (todo) {
      if (!todo) {
        var err = new Error('Not updated. Todo doesn\'t exists');
        err.name = 'ValidationError';
        return next(err);
      }
      res.json(200);
    }, function (err) {
      next(err);
    });
};


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memcpy_82_bad.cpp
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-82_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 195 Signed to Unsigned Conversion Error
 * BadSource: listen_socket Read data using a listen socket (server side)
 * GoodSource: Positive integer
 * Sinks: memcpy
 *    BadSink : Copy strings using memcpy() with the length of data
 * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
 *
 * */
#ifndef OMITBAD

#include "std_testcase.h"
#include "CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memcpy_82.h"

namespace CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memcpy_82
{

void CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memcpy_82_bad::action(int data)
{
    {
        char source[100];
        char dest[100] = "";
        memset(source, 'A', 100-1);
        source[100-1] = '\0';
        if (data < 100)
        {
            /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
             * the sign conversion could result in a very large number */
            memcpy(dest, source, data);
            dest[data] = '\0'; /* NULL terminate */
        }
        printLine(dest);
    }
}

}
#endif /* OMITBAD */


text:
import {AbsoluteFsPath, relative} from '@angular/compiler-cli/src/ngtsc/file_system';
import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize';

import {FormatOptions, validateOptions} from './format_options';
import {extractIcuPlaceholders} from './icu_parsing';
import {TranslationSerializer} from './translation_serializer';
import {XmlFile} from './xml_file';

/** This is the maximum number of characters that can appear in a legacy XLIFF 2.0 message id. */
const MAX_LEGACY_XLIFF_2_MESSAGE_LENGTH = 20;

/**
 * A translation serializer that can write translations in XLIFF 2 format.
 *
 * http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
 *
 * @see Xliff2TranslationParser
 */
export class Xliff2TranslationSerializer implements TranslationSerializer {
  private currentPlaceholderId = 0;
  constructor(
      private sourceLocale: string, private basePath: AbsoluteFsPath, private useLegacyIds: boolean,
      private formatOptions: FormatOptions) {
    validateOptions('Xliff1TranslationSerializer', [['xml:space', ['preserve']]], formatOptions);
  }

  serialize(messages: ɵParsedMessage[]): string {
    const ids = new Set<string>();
    const xml = new XmlFile();
    xml.startTag('xliff', {
      'version': '2.0',
      'xmlns': 'urn:oasis:names:tc:xliff:document:2.0',
      'srcLang': this.sourceLocale
    });
    // NOTE: the `original` property is set to the legacy `ng.template` value for backward
    // compatibility.
    // We could compute the file from the `message.location` property, but there could
    // be multiple values for this in the collection of `messages`. In that case we would probably
    // need to change the serializer to output a new `<file>` element for each collection of
    // messages that come from a particular original file, and the translation file parsers may
    // not
    xml.startTag('file', {'id': 'ngi18n', 'original': 'ng.template', ...this.formatOptions});
    for (const message of messages) {
      const id = this.getMessageId(message);
      if (ids.has(id)) {
        // Do not render the same message more than once
        continue;
      }
      ids.add(id);
      xml.startTag('unit', {id});
      if (message.meaning || message.description || message.location) {
        xml.startTag('notes');
        if (message.location) {
          const {file, start, end} = message.location;
          const endLineString =
              end !== undefined && end.line !== start.line ? `,${end.line + 1}` : '';
          this.serializeNote(
              xml, 'location',
              `${relative(this.basePath, file)}:${start.line + 1}${endLineString}`);
        }
        if (message.description) {
          this.serializeNote(xml, 'description', message.description);
        }
        if (message.meaning) {
          this.serializeNote(xml, 'meaning', message.meaning);
        }
        xml.endTag('notes');
      }
      xml.startTag('segment');
      xml.startTag('source', {}, {preserveWhitespace: true});
      this.serializeMessage(xml, message);
      xml.endTag('source', {preserveWhitespace: false});
      xml.endTag('segment');
      xml.endTag('unit');
    }
    xml.endTag('file');
    xml.endTag('xliff');
    return xml.toString();
  }

  private serializeMessage(xml: XmlFile, message: ɵParsedMessage): void {
    this.currentPlaceholderId = 0;
    const length = message.messageParts.length - 1;
    for (let i = 0; i < length; i++) {
      this.serializeTextPart(xml, message.messageParts[i]);
      this.serializePlaceholder(xml, message.placeholderNames[i], message.substitutionLocations);
    }
    this.serializeTextPart(xml, message.messageParts[length]);
  }

  private serializeTextPart(xml: XmlFile, text: string): void {
    const pieces = extractIcuPlaceholders(text);
    const length = pieces.length - 1;
    for (let i = 0; i < length; i += 2) {
      xml.text(pieces[i]);
      this.serializePlaceholder(xml, pieces[i + 1], undefined);
    }
    xml.text(pieces[length]);
  }

  private serializePlaceholder(
      xml: XmlFile, placeholderName: string,
      substitutionLocations: Record<string, ɵSourceLocation|undefined>|undefined): void {
    const text = substitutionLocations?.[placeholderName]?.text;

    if (placeholderName.startsWith('START_')) {
      const closingPlaceholderName = placeholderName.replace(/^START/, 'CLOSE');
      const closingText = substitutionLocations?.[closingPlaceholderName]?.text;
      const attrs: Record<string, string> = {
        id: `${this.currentPlaceholderId++}`,
        equivStart: placeholderName,
        equivEnd: closingPlaceholderName,
      };
      if (text !== undefined) {
        attrs.dispStart = text;
      }
      if (closingText !== undefined) {
        attrs.dispEnd = closingText;
      }
      xml.startTag('pc', attrs);
    } else if (placeholderName.startsWith('CLOSE_')) {
      xml.endTag('pc');
    } else {
      const attrs:
          Record<string, string> = {id: `${this.currentPlaceholderId++}`, equiv: placeholderName};
      if (text !== undefined) {
        attrs.disp = text;
      }
      xml.startTag('ph', attrs, {selfClosing: true});
    }
  }

  private serializeNote(xml: XmlFile, name: string, value: string) {
    xml.startTag('note', {category: name}, {preserveWhitespace: true});
    xml.text(value);
    xml.endTag('note', {preserveWhitespace: false});
  }

  /**
   * Get the id for the given `message`.
   *
   * If there was a custom id provided, use that.
   *
   * If we have requested legacy message ids, then try to return the appropriate id
   * from the list of legacy ids that were extracted.
   *
   * Otherwise return the canonical message id.
   *
   * An Xliff 2.0 legacy message id is a 64 bit number encoded as a decimal string, which will have
   * at most 20 digits, since 2^65-1 = 36,893,488,147,419,103,231. This digest is based on:
   * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
   */
  private getMessageId(message: ɵParsedMessage): string {
    return message.customId ||
        this.useLegacyIds && message.legacyIds !== undefined &&
        message.legacyIds.find(
            id => id.length <= MAX_LEGACY_XLIFF_2_MESSAGE_LENGTH && !/[^0-9]/.test(id)) ||
        message.id;
  }
}


text:
> All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

## [v1.0.0](https://github.com/mojeto/django-in-request-cache/releases/tag/v1.0.0)

### Changed

* Removed support for Django < 1.11
* Added support for Django >= 1.11 (Jon Dufresne)
* Added support for Python 3.6 and 3.7

## [v0.0.6](https://github.com/mojeto/django-in-request-cache/releases/tag/v0.0.6)

### Changed

* Pypi wheel build added.

## [v0.0.5](https://github.com/mojeto/django-in-request-cache/releases/tag/v0.0.5)

### Added

* CacheACache class added.

## [v0.0.4](https://github.com/mojeto/django-in-request-cache/releases/tag/v0.0.4)

### Changed

* Fixed the bug with django cache location param.


text:
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
from routes.dicas.modulo import Dicas, Cidade

@login_not_required
@no_csrf
def index():
    contexto = {'dicas_lista' : Dicas.query_ordenada_por_data().fetch()}
    return TemplateResponse(contexto,template_path='/dicas/home.html')


text:
/*
 * tmcl_move_to.c
 *
 */
/* Copyright (c) 2015, Ralf Schulze <ralf.schulze@gmx.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:

 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <tmcl/tmcl.h>

#define DEVICE "/dev/ttyS2"
#define ADDRESS 1
#define BANK 0

int main(int argc, char *argv[]) {

    TMCLInterface *PGAAIface;
    TMCLMotor *PGAAMotor;
    int position;
    int current_pos;

    if(argc != 2) {
        printf("Usage: %s <position>\n", argv[0]);
    }

    position = atoi(argv[1]);

    printf("Moving to position %d\n", position);

    if (tmcl_init_interface(&PGAAIface, TMCL_RSXXX, NULL, NULL, NULL, NULL) < 0) {
        printf("Error initializing interface\n");
        exit(EXIT_FAILURE);
    }

    if (tmcl_open_interface(PGAAIface, DEVICE) < 0) {
        printf("Error opening iterface\n");
        exit(EXIT_FAILURE);
    }

    if (tmcl_init_motor(&PGAAMotor, PGAAIface, TMCM301, ADDRESS, BANK, TMCL_RSXXX) < 0) {
        printf("Error intializing motor\n");
        exit(EXIT_FAILURE);
    }

    if(tmcl_move_to_pos_abs(PGAAMotor, position) < 0) {
        printf("Error setting position\n");
        exit(EXIT_FAILURE);
    }

    do {
        sleep(1);
        current_pos = tmcl_get_position(PGAAMotor);
        if(current_pos == 0xFFFFFF) {
            printf("Reading of current position failed\n");
            exit(EXIT_FAILURE);
        }
        printf("Current position: %d\n", current_pos);
    } while(current_pos != position);

    printf("Reached position %d\n", position);

    tmcl_deinit_motor(&PGAAMotor);
    tmcl_close_interface(PGAAIface);
    tmcl_deinit_interface(&PGAAIface);

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/txtMain"
        style="@style/Main"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="@string/dialer" />

    <TextView
        android:id="@+id/txtCurrentDigit"
        style="@style/Help"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtMain"
        android:gravity="center"
        android:text="@string/digit_help" />

</RelativeLayout>


text:
package org.reasm.z80.expressions.internal;

import javax.annotation.Nonnull;

import org.reasm.commons.messages.InvalidTokenErrorMessage;

/**
 * A checked exception that is thrown when the expression parser encounters an invalid token.
 *
 * @author Francis Gagné
 */
public final class InvalidTokenException extends Exception {

    private static final long serialVersionUID = 1L;

    @Nonnull
    private final String token;

    /**
     * Initializes a new InvalidTokenException.
     *
     * @param token
     *            the invalid token
     */
    public InvalidTokenException(@Nonnull String token) {
        if (token == null) {
            throw new NullPointerException("token");
        }

        this.token = token;
    }

    /**
     * Creates an {@link InvalidTokenErrorMessage} with the token that triggered this exception.
     *
     * @return a new {@link InvalidTokenErrorMessage}
     */
    @Nonnull
    public final InvalidTokenErrorMessage createAssemblyErrorMessage() {
        return new InvalidTokenErrorMessage(this.token);
    }

    /**
     * Gets the invalid token that triggered this exception.
     *
     * @return the invalid token
     */
    @Nonnull
    public final String getToken() {
        return this.token;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    >
    <!--test-->
    <scale
        android:duration="300"
        android:fromXScale="0.0"
        android:fromYScale="0.0"
        android:toXScale="0.8"
        android:toYScale="0.8"
        android:interpolator="@android:anim/linear_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        />

    <alpha
        android:duration="300"
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        />
</set>


text:
/*
 * @test
 * @summary Tests <new> element
 * @author Sergey Malenkov
 */

import java.beans.XMLDecoder;
import java.util.ArrayList;
import java.util.List;

public final class TestNew extends AbstractTest {
    public static final String XML
            = "<java>\n"
            + " <new class=\"TestNew\"/>\n"
            + " <new class=\"TestNew\">\n"
            + "  <null/>\n"
            + " </new>\n"
            + " <new class=\"TestNew\">\n"
            + "  <string>single</string>\n"
            + " </new>\n"
            + " <new class=\"TestNew\">\n"
            + "  <string>first</string>\n"
            + "  <string>second</string>\n"
            + "  <string>third</string>\n"
            + " </new>\n"
            + "</java>";

    public static void main(String[] args) {
        new TestNew().test(true);
    }

    private List<String> list;

    public TestNew(String...messages) {
        if (messages != null) {
            this.list = new ArrayList<String>();
            for (String message : messages) {
                this.list.add(message);
            }
        }
    }

    @Override
    public boolean equals(Object object) {
        if (object instanceof TestNew) {
            TestNew test = (TestNew) object;
            return (test.list == null)
                    ? this.list == null
                    : test.list.equals(this.list);
        }
        return false;
    }

    @Override
    protected void validate(XMLDecoder decoder) {
        validate(decoder.readObject());
        validate(decoder.readObject(), null);
        validate(decoder.readObject(), "single");
        validate(decoder.readObject(), "first", "second", "third");
    }

    private static void validate(Object object, String...messages) {
        if (!object.equals(new TestNew(messages))) {
            throw new Error("expected object");
        }
    }
}


text:
 import THREE from 'three';
import $ from 'jquery';
import {} from '../../third_party/threejs_extra/OrbitControls';
import * as DeviceCheck from '../app/devicecheck';

export default function createControl( camera, domElement ){

  const orbitControls = new THREE.OrbitControls( camera, domElement );
  orbitControls.target.set( 0, 110, 0 );
  orbitControls.userPanSpeed = 0.3;
  orbitControls.zoomSpeed = 3.0;
  orbitControls.keyPanSpeed = 30.0;
  orbitControls.noRotate = false;
  orbitControls.noPan = true;
  orbitControls.minDistance = 40;
  orbitControls.maxDistance = 600;
  orbitControls.minPolarAngle = Math.PI * 0.02;
  orbitControls.maxPolarAngle = Math.PI - Math.PI * 0.43;

  //  some default location
  var startDistance = 200;
  if (DeviceCheck.isMobile()) {
    startDistance = 450;
    orbitControls.maxDistance = 1000;
  }
  camera.position.set( startDistance, 200, startDistance );
    // .normalize()
    // .multiplyScalar( 300 );

  function restore(){
    const savedCamera = JSON.parse( localStorage.getItem( 'savedCamera' ) );
    if( savedCamera ){
      camera.position.copy( savedCamera.cameraPosition );
      orbitControls.target.copy( savedCamera.targetPosition );
    }
  }

  // restore();

  orbitControls.update();

  $(window).unload( function(){
    localStorage.savedCamera = JSON.stringify({
      cameraPosition: camera.position,
      targetPosition: orbitControls.target
    });
  });

  return {
    orbit: () => orbitControls
  };
}


text:
require 'spec_helper'

RSpec.describe User do
  context 'Create a new user' do
    it 'with posts' do
      user = User.new(name: 'John', age: 25)
      user.save!

      post_1 = Post.new(title: 'Post title 1', content: 'Post 1 content')
      post_2 = Post.new(title: 'Post title 2', content: 'Post 2 content')
      post_3 = Post.new(title: 'Post title 3', content: 'Post 3 content')

      user.posts << post_1
      user.posts << post_2
      user.posts << post_3
      user.save!

      # Load user from database
      user = User.find(user.id)
      expect(user.posts.length).to eq(3)
    end
  end
end


text:
package org.clubrockisen.dao.abstracts;

import org.clubrockisen.entities.EntryMemberParty;
import org.clubrockisen.entities.Member;
import org.clubrockisen.entities.Parameter;
import org.clubrockisen.entities.Party;

import com.alexrnl.commons.database.dao.AbstractDAOFactory;
import com.alexrnl.commons.database.dao.DAO;
import com.alexrnl.commons.database.dao.DataSourceConfiguration;

/**
 * The abstract factory for the {@link DAO}s.

 * Define the different DAO objects that should be created for a complete access to the database.
 * @author Alex
 */
public abstract class EntryManagerAbstractDAOFactory extends AbstractDAOFactory {

	/**
	 * Constructor #1.

	 * @param dataSourceConfig
	 *        the data source configuration.
	 */
	public EntryManagerAbstractDAOFactory (final DataSourceConfiguration dataSourceConfig) {
		super(dataSourceConfig);
	}

	/**
	 * Retrieve a {@link DAO} for the {@link Parameter} class.
	 * @return the DAO for the parameter class.
	 */
	public abstract DAO<Parameter> getParameterDAO ();

	/**
	 * Retrieve a {@link DAO} for the {@link Member} class.
	 * @return the DAO for the member class.
	 */
	public abstract DAO<Member> getMemberDAO ();

	/**
	 * Retrieve a {@link DAO} for the {@link Party} class.
	 * @return the DAO for the party class.
	 */
	public abstract DAO<Party> getPartyDAO ();

	/**
	 * Retrieve a {@link DAO} for the {@link EntryMemberParty} class.
	 * @return the DAO for the entries class.
	 */
	public abstract DAO<EntryMemberParty> getEntryMemberPartyDAO ();
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<package name="ksa-component-security" extends="ksa-default" namespace="/component/security">

		<!-- 用户选择组件 -->
		<action name="user-selection">
			<result>/ui/security/component/user-selection.ftl</result>
		</action>

		<!-- 角色选择组件 -->
		<action name="role-selection">
			<result>/ui/security/component/role-selection.ftl</result>
		</action>

		<!-- 权限选择组件 -->
		<action name="permission-selection">
			<result>/ui/security/component/permission-selection.ftl</result>
		</action>
	</package>
</struts>


text:
[![Build Status](https://travis-ci.org/DonRyuDragoni/vibration-sim.svg?branch=master)](https://travis-ci.org/DonRyuDragoni/vibration-sim)

In vibration theory, this is the first studied system, for many reasons. This
system is simple enough for didactic demonstration in classes and complex enough
to show every basic concept needed for advanced studies.

So, to help students visualize this basic concepts and to teach me a little more
Clojure, I coded this project in my free time. I also thought it would be cool
to include it in my course completion assignment to complement some basic
explanations.

# The Project

Using Clojure, a little bit of [play-clj][play-clj], and a lot of free time and
will of learning a new programming language, I put together a simple animation
to demonstrate the response of the system for diferent levels of damping.

This project was built using the [Leiningen][leiningen] project automation tool,
with the `play-clj` template and the [Claypoole][claypoole] library, so these
are the only dependencies (though, because of the way Leiningen handles
dependencies, you probably won't worry about it).

Also, please note there are no test functions. This is to be modified later.
Maybe.

# Usage

## Running The Program

Simply launch the program (pre-compiled standalone `.jar` lives in the `target/`
folder), as any Java file

```
java -jar path_to_jar_file/vibration-sim-1.2.2-standalone.jar
```

(changing `path_to_jar_file` to the actual path of the downloaded file), and use
any keys listed in the section below. If you want to clone the whole project, it
is pretty much standart for git repositories. The command

```
git clone https://github.com/DonRyuDragoni/vibration-sim
```

will do the trick. To run with Leiningen, simply `lein run` on the cloned
folder (as of any Leiningen project, dependencies are downloaded in the first
run). To compile and generate the `.jar` file, simply run `lein uberjar`.

_Note_: if you change the screen size (variables `screen-dim-x` and
`screen-dim-y` defined in `src-common/vibration_sim/constants.clj`), you have to
make sure `src/vibration_sim/core/desktop_launcher.clj` is recompiled. I
actually don't know how to force it in `lein run`, so I just recompile the whole
project with `lein uberjar`. Please let me know of a better method.

## Vibration Modes

This simulation presents an animated representation for the really basic MSD
responses, assuming the system is not affected by external forces. The program
will automatically decide wich function to use based on the input given by the
user. The possibilities are:

1. *undamped system*: the system is reduced to the mass-spring, in
    which the mass oscilates forever, and amplitude of the movemnt remains
    constant;
2. *low-damped system*: damping means the system will lose energy
    over time, so the mass will oscilate, but its amplitude will reduce over
    time, untill the system comes to a stop;
3. *high-damped system*: high damping means the system will not
    oscilate, instead, it will return as fast as possible to the equilibrium
    position.

To quit the program, there is also the q shortcut.

Also, note that pressing any key (except q, of course) will reset the
time to zero, thus restarting the animation with the previous data. To start the
animation with the new values, simply press the helpfull Apply button.

# Bug Reports, Suggestions, Pull Requests, ...

Please read CONTRIBUTING.md file.

# TODOS

## Improvements

* [ ] add [expectations][expectations] and [lein-autoexpect][lein-autoexpect] as
    dependencies;
* [ ] write test functions using expectations and lein-autoexpect.

## New features

* [ ] adjust the sliders range and step for better animations;
* [ ] add forced vibrations and resonance;
* [ ] adjust the pressed button image;
* [x] add modifiers for the spring and damper constants, so the
    program can be run with multiple values (text input from the user
    is preferable);
* [x] show small marks at previous positions of the mass;
* [x] make the label at the botton show the current time.

## Known bugs

No bug is known at the moment.

# Changelog

* 2015-07-16: **2.0.0**
  * small change in the creation of the sliders;
  * correction of the movement equations;
  * correction of the table (sliders/labels/buttons) location;
  * changed documentation to reflect the new functionality.
* 2015-07-03: **1.2.4**
  * small correction in the Changelog section of the README.md file;
  * add a simple animation for demonstration.
* 2015-06-08: **1.2.3**
  * corrected line endings of the files;
  * contrubition instructions;
  * created development branch.
* 2015-05-13: **1.2.2**
  * changed some java-based mathematical functions to macros;
  * corrected some function contracts;
  * changed some organization of the code.
* 2015-04-25: **1.2.1**
  * add claypoole as a dependency;
  * movement functions now run in parallel;
  * "q" now kill the threadpool and exits the program.
* 2015-04-21: **1.2.0**
  * took a while to figure it out, but we have the timer printed on the
      screen;
  * blue dots now follow the mass, showing the plot of the movement equation;
  * the dots are removed from the animation as soon as they leave the screen;
  * the dots are also removed with any keypress, so re-starting any animation
      actually re-starts everything.
* 2015-04-20: **1.1.0**
  * first working version of the program;
  * the mass-rectangle-thingy changes movement type with certain keys;
  * any key resets the time (making restart easier);
  * resized the window (makes more sense to me as it is).

[play-clj]: https://github.com/oakes/play-clj
[leiningen]: http://leiningen.org/
[expectations]: https://github.com/jaycfields/expectations
[lein-autoexpect]: https://github.com/jakemcc/lein-autoexpect
[claypoole]: https://github.com/TheClimateCorporation/claypoole


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. Rep. N. Y. St. Mus. 44: 21 (1891)

#### Original name
Daedalea sulphurella Peck

### Remarks
null


text:
namespace base {

// static
SignatureCreator* SignatureCreator::Create(RSAPrivateKey* key) {
  scoped_ptr<SignatureCreator> result(new SignatureCreator);
  result->key_ = key;

  CSSM_RETURN crtn;
  crtn = CSSM_CSP_CreateSignatureContext(result->csp_handle_,
                                         CSSM_ALGID_SHA1WithRSA,
                                         NULL,
                                         key->key(),
                                         &result->sig_handle_);
  if (crtn) {
    NOTREACHED();
    return NULL;
  }

  crtn = CSSM_SignDataInit(result->sig_handle_);
  if (crtn) {
    NOTREACHED();
    return false;
  }

  return result.release();
}

SignatureCreator::SignatureCreator() : csp_handle_(0), sig_handle_(0) {
  EnsureCSSMInit();

  static CSSM_VERSION version = {2, 0};
  CSSM_RETURN crtn;
  crtn = CSSM_ModuleAttach(&gGuidAppleCSP, &version, &kCssmMemoryFunctions, 0,
                           CSSM_SERVICE_CSP, 0, CSSM_KEY_HIERARCHY_NONE,
                           NULL, 0, NULL, &csp_handle_);
  DCHECK(crtn == CSSM_OK);
}

SignatureCreator::~SignatureCreator() {
  CSSM_RETURN crtn;
  if (sig_handle_) {
    crtn = CSSM_DeleteContext(sig_handle_);
    DCHECK(crtn == CSSM_OK);
  }

  if (csp_handle_) {
    CSSM_RETURN crtn = CSSM_ModuleDetach(csp_handle_);
    DCHECK(crtn == CSSM_OK);
  }
}

bool SignatureCreator::Update(const uint8* data_part, int data_part_len) {
  CSSM_DATA data;
  data.Data = const_cast<uint8*>(data_part);
  data.Length = data_part_len;
  CSSM_RETURN crtn = CSSM_SignDataUpdate(sig_handle_, &data, 1);
  DCHECK(crtn == CSSM_OK);
  return true;
}

bool SignatureCreator::Final(std::vector<uint8>* signature) {
  CSSM_DATA sig;
  memset(&sig, 0, sizeof(CSSM_DATA)); // Allow CSSM allocate memory;
  CSSM_RETURN crtn = CSSM_SignDataFinal(sig_handle_, &sig);

  if (crtn) {
    NOTREACHED();
    return false;
  }

  signature->assign(sig.Data, sig.Data + sig.Length);
  kCssmMemoryFunctions.free_func(sig.Data, NULL); // Release data alloc'd
                                                  // by CSSM

  return true;
}

}  // namespace base