text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/tinderbox/XR-Trunk/WINNT_5.2_Depend/mozilla/uriloader/base/nsIURILoader.idl
 */

#ifndef __gen_nsIURILoader_h__
#define __gen_nsIURILoader_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIURIContentListener; /* forward declaration */

class nsIURI; /* forward declaration */

class nsILoadGroup; /* forward declaration */

class nsIProgressEventSink; /* forward declaration */

class nsIChannel; /* forward declaration */

class nsIRequest; /* forward declaration */

class nsIStreamListener; /* forward declaration */

class nsIInputStream; /* forward declaration */

class nsIInterfaceRequestor; /* forward declaration */

/* starting interface:    nsIURILoader */
#define NS_IURILOADER_IID_STR "2f7e8051-f1c9-4bcc-8584-9cfd5849e343"

#define NS_IURILOADER_IID \
  {0x2f7e8051, 0xf1c9, 0x4bcc, \
    { 0x85, 0x84, 0x9c, 0xfd, 0x58, 0x49, 0xe3, 0x43 }}

/**
 * The uri dispatcher is responsible for taking uri's, determining
 * the content and routing the opened url to the correct content
 * handler.
 *
 * When you encounter a url you want to open, you typically call
 * openURI, passing it the content listener for the window the uri is
 * originating from. The uri dispatcher opens the url to discover the
 * content type. It then gives the content listener first crack at
 * handling the content. If it doesn't want it, the dispatcher tries
 * to hand it off one of the registered content listeners. This allows
 * running applications the chance to jump in and handle the content.
 *
 * If that also fails, then the uri dispatcher goes to the registry
 * looking for the preferred content handler for the content type
 * of the uri. The content handler may create an app instance
 * or it may hand the contents off to a platform specific plugin
 * or helper app. Or it may hand the url off to an OS registered
 * application.
 */
class NS_NO_VTABLE NS_SCRIPTABLE nsIURILoader : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IURILOADER_IID)

  /**
   * @name Flags for opening URIs.
   */
/**
   * Should the content be displayed in a container that prefers the
   * content-type, or will any container do.
   */
  enum { IS_CONTENT_PREFERRED = 1U };

  /**
   * If this flag is set, only the listener of the specified window context will
   * be considered for content handling; if it refuses the load, an error will
   * be indicated.
   */
  enum { DONT_RETARGET = 2U };

  /**
   * As applications such as messenger and the browser are instantiated,
   * they register content listener's with the uri dispatcher corresponding
   * to content windows within that application.
   *
   * Note to self: we may want to optimize things a bit more by requiring
   * the content types the registered content listener cares about.
   *
   * @param aContentListener
   *        The listener to register. This listener must implement
   *        nsISupportsWeakReference.
   *
   * @see the nsIURILoader class description
   */
  /* void registerContentListener (in nsIURIContentListener aContentListener); */
  NS_SCRIPTABLE NS_IMETHOD RegisterContentListener(nsIURIContentListener *aContentListener) = 0;

  /* void unRegisterContentListener (in nsIURIContentListener aContentListener); */
  NS_SCRIPTABLE NS_IMETHOD UnRegisterContentListener(nsIURIContentListener *aContentListener) = 0;

  /**
   * OpenURI requires the following parameters.....
   * @param aChannel
   *        The channel that should be opened. This must not be asyncOpen'd yet!
   *        If a loadgroup is set on the channel, it will get replaced with a
   *        different one.
   * @param aIsContentPreferred
   *        Should the content be displayed in a container that prefers the
   *        content-type, or will any container do.
   * @param aWindowContext
   *        If you are running the url from a doc shell or a web shell, this is
   *        your window context. If you have a content listener you want to
   *        give first crack to, the uri loader needs to be able to get it
   *        from the window context. We will also be using the window context
   *        to get at the progress event sink interface.
   *        Must not be null!
   */
  /* void openURI (in nsIChannel aChannel, in boolean aIsContentPreferred, in nsIInterfaceRequestor aWindowContext); */
  NS_SCRIPTABLE NS_IMETHOD OpenURI(nsIChannel *aChannel, PRBool aIsContentPreferred, nsIInterfaceRequestor *aWindowContext) = 0;

  /**
   * Loads data from a channel. This differs from openURI in that the channel
   * may already be opened, and that it returns a stream listener into which the
   * caller should pump data. The caller is responsible for opening the channel
   * and pumping the channel's data into the returned stream listener.
   *
   * Note: If the channel already has a loadgroup, it will be replaced with the
   * window context's load group, or null if the context doesn't have one.
   *
   * If the window context's nsIURIContentListener refuses the load immediately
   * (e.g. in nsIURIContentListener::onStartURIOpen), this method will return
   * NS_ERROR_WONT_HANDLE_CONTENT. At that point, the caller should probably
   * cancel the channel if it's already open (this method will not cancel the
   * channel).
   *
   * If flags include DONT_RETARGET, and the content listener refuses the load
   * during onStartRequest (e.g. in canHandleContent/isPreferred), then the
   * returned stream listener's onStartRequest method will return
   * NS_ERROR_WONT_HANDLE_CONTENT.
   *
   * @param aChannel
   *        The channel that should be loaded. The channel may already be
   *        opened. It must not be closed (i.e. this must be called before the
   *        channel calls onStopRequest on its stream listener).
   * @param aFlags
   *        Combination (bitwise OR) of the flags specified above. 0 indicates
   *        default handling.
   * @param aWindowContext
   *        If you are running the url from a doc shell or a web shell, this is
   *        your window context. If you have a content listener you want to
   *        give first crack to, the uri loader needs to be able to get it
   *        from the window context. We will also be using the window context
   *        to get at the progress event sink interface.
   *        Must not be null!
   */
  /* nsIStreamListener openChannel (in nsIChannel aChannel, in unsigned long aFlags, in nsIInterfaceRequestor aWindowContext); */
  NS_SCRIPTABLE NS_IMETHOD OpenChannel(nsIChannel *aChannel, PRUint32 aFlags, nsIInterfaceRequestor *aWindowContext, nsIStreamListener **_retval) = 0;

  /**
   * Stops an in progress load
   */
  /* void stop (in nsISupports aLoadCookie); */
  NS_SCRIPTABLE NS_IMETHOD Stop(nsISupports *aLoadCookie) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIURILoader, NS_IURILOADER_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIURILOADER \
  NS_SCRIPTABLE NS_IMETHOD RegisterContentListener(nsIURIContentListener *aContentListener); \
  NS_SCRIPTABLE NS_IMETHOD UnRegisterContentListener(nsIURIContentListener *aContentListener); \
  NS_SCRIPTABLE NS_IMETHOD OpenURI(nsIChannel *aChannel, PRBool aIsContentPreferred, nsIInterfaceRequestor *aWindowContext); \
  NS_SCRIPTABLE NS_IMETHOD OpenChannel(nsIChannel *aChannel, PRUint32 aFlags, nsIInterfaceRequestor *aWindowContext, nsIStreamListener **_retval); \
  NS_SCRIPTABLE NS_IMETHOD Stop(nsISupports *aLoadCookie);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIURILOADER(_to) \
  NS_SCRIPTABLE NS_IMETHOD RegisterContentListener(nsIURIContentListener *aContentListener) { return _to RegisterContentListener(aContentListener); } \
  NS_SCRIPTABLE NS_IMETHOD UnRegisterContentListener(nsIURIContentListener *aContentListener) { return _to UnRegisterContentListener(aContentListener); } \
  NS_SCRIPTABLE NS_IMETHOD OpenURI(nsIChannel *aChannel, PRBool aIsContentPreferred, nsIInterfaceRequestor *aWindowContext) { return _to OpenURI(aChannel, aIsContentPreferred, aWindowContext); } \
  NS_SCRIPTABLE NS_IMETHOD OpenChannel(nsIChannel *aChannel, PRUint32 aFlags, nsIInterfaceRequestor *aWindowContext, nsIStreamListener **_retval) { return _to OpenChannel(aChannel, aFlags, aWindowContext, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD Stop(nsISupports *aLoadCookie) { return _to Stop(aLoadCookie); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIURILOADER(_to) \
  NS_SCRIPTABLE NS_IMETHOD RegisterContentListener(nsIURIContentListener *aContentListener) { return !_to ? NS_ERROR_NULL_POINTER : _to->RegisterContentListener(aContentListener); } \
  NS_SCRIPTABLE NS_IMETHOD UnRegisterContentListener(nsIURIContentListener *aContentListener) { return !_to ? NS_ERROR_NULL_POINTER : _to->UnRegisterContentListener(aContentListener); } \
  NS_SCRIPTABLE NS_IMETHOD OpenURI(nsIChannel *aChannel, PRBool aIsContentPreferred, nsIInterfaceRequestor *aWindowContext) { return !_to ? NS_ERROR_NULL_POINTER : _to->OpenURI(aChannel, aIsContentPreferred, aWindowContext); } \
  NS_SCRIPTABLE NS_IMETHOD OpenChannel(nsIChannel *aChannel, PRUint32 aFlags, nsIInterfaceRequestor *aWindowContext, nsIStreamListener **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->OpenChannel(aChannel, aFlags, aWindowContext, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD Stop(nsISupports *aLoadCookie) { return !_to ? NS_ERROR_NULL_POINTER : _to->Stop(aLoadCookie); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsURILoader : public nsIURILoader
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIURILOADER

  nsURILoader();

private:
  ~nsURILoader();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsURILoader, nsIURILoader)

nsURILoader::nsURILoader()
{
  /* member initializers and constructor code */
}

nsURILoader::~nsURILoader()
{
  /* destructor code */
}

/* void registerContentListener (in nsIURIContentListener aContentListener); */
NS_IMETHODIMP nsURILoader::RegisterContentListener(nsIURIContentListener *aContentListener)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void unRegisterContentListener (in nsIURIContentListener aContentListener); */
NS_IMETHODIMP nsURILoader::UnRegisterContentListener(nsIURIContentListener *aContentListener)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void openURI (in nsIChannel aChannel, in boolean aIsContentPreferred, in nsIInterfaceRequestor aWindowContext); */
NS_IMETHODIMP nsURILoader::OpenURI(nsIChannel *aChannel, PRBool aIsContentPreferred, nsIInterfaceRequestor *aWindowContext)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIStreamListener openChannel (in nsIChannel aChannel, in unsigned long aFlags, in nsIInterfaceRequestor aWindowContext); */
NS_IMETHODIMP nsURILoader::OpenChannel(nsIChannel *aChannel, PRUint32 aFlags, nsIInterfaceRequestor *aWindowContext, nsIStreamListener **_retval)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void stop (in nsISupports aLoadCookie); */
NS_IMETHODIMP nsURILoader::Stop(nsISupports *aLoadCookie)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIURILoader_h__ */


text:
package pacer

import (
	"sync"
	"time"

	"github.com/ncw/rclone/fs"
)

type Pacer struct {
	minSleep       time.Duration // minimum sleep time
	maxSleep       time.Duration // maximum sleep time
	decayConstant  uint          // decay constant
	pacer          chan struct{} // To pace the operations
	sleepTime      time.Duration // Time to sleep for each transaction
	retries        int           // Max number of retries
	mu             sync.Mutex    // Protecting read/writes
	maxConnections int           // Maximum number of concurrent connections
	connTokens     chan struct{} // Connection tokens
}

// Paced is a function which is called by the Call and CallNoRetry
// methods.  It should return a boolean, true if it would like to be
// retried, and an error.  This error may be returned or returned
// wrapped in a RetryError.
type Paced func() (bool, error)

// New returns a Pacer with sensible defaults
func New() *Pacer {
	p := &Pacer{
		minSleep:      10 * time.Millisecond,
		maxSleep:      2 * time.Second,
		decayConstant: 2,
		retries:       10,
		pacer:         make(chan struct{}, 1),
	}
	p.sleepTime = p.minSleep
	p.SetMaxConnections(fs.Config.Checkers)
	// Put the first pacing token in
	p.pacer <- struct{}{}

	return p
}

// SetMinSleep sets the minimum sleep time for the pacer
func (p *Pacer) SetMinSleep(t time.Duration) *Pacer {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.minSleep = t
	p.sleepTime = p.minSleep
	return p
}

// SetMaxSleep sets the maximum sleep time for the pacer
func (p *Pacer) SetMaxSleep(t time.Duration) *Pacer {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.maxSleep = t
	p.sleepTime = p.minSleep
	return p
}

// SetMaxConnections sets the maximum number of concurrent connections.
// Setting the value to 0 will allow unlimited number of connections.
// Should not be changed once you have started calling the pacer.
// By default this will be set to fs.Config.Checkers.
func (p *Pacer) SetMaxConnections(n int) *Pacer {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.maxConnections = n
	if n <= 0 {
		p.connTokens = nil
	} else {
		p.connTokens = make(chan struct{}, n)
		for i := 0; i < n; i++ {
			p.connTokens <- struct{}{}
		}
	}
	return p
}

// SetDecayConstant sets the decay constant for the pacer
//
// This is the speed the time falls back to the minimum after errors
// have occurred.
//
// bigger for slower decay, exponential
func (p *Pacer) SetDecayConstant(decay uint) *Pacer {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.decayConstant = decay
	return p
}

// SetRetries sets the max number of tries for Call
func (p *Pacer) SetRetries(retries int) *Pacer {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.retries = retries
	return p
}

// Start a call to the API
//
// This must be called as a pair with endCall
//
// This waits for the pacer token
func (p *Pacer) beginCall() {
	// pacer starts with a token in and whenever we take one out
	// XXX ms later we put another in.  We could do this with a
	// Ticker more accurately, but then we'd have to work out how
	// not to run it when it wasn't needed
	<-p.pacer
	if p.maxConnections > 0 {
		<-p.connTokens
	}

	p.mu.Lock()
	// Restart the timer
	go func(t time.Duration) {
		// fs.Debug(f, "New sleep for %v at %v", t, time.Now())
		time.Sleep(t)
		p.pacer <- struct{}{}
	}(p.sleepTime)
	p.mu.Unlock()
}

// End a call to the API
//
// Refresh the pace given an error that was returned.  It returns a
// boolean as to whether the operation should be retried.
func (p *Pacer) endCall(again bool) {
	if p.maxConnections > 0 {
		p.connTokens <- struct{}{}
	}
	p.mu.Lock()
	oldSleepTime := p.sleepTime
	if again {
		p.sleepTime *= 2
		if p.sleepTime > p.maxSleep {
			p.sleepTime = p.maxSleep
		}
		if p.sleepTime != oldSleepTime {
			fs.Debug("pacer", "Rate limited, increasing sleep to %v", p.sleepTime)
		}
	} else {
		p.sleepTime = (p.sleepTime<<p.decayConstant - p.sleepTime) >> p.decayConstant
		if p.sleepTime < p.minSleep {
			p.sleepTime = p.minSleep
		}
		if p.sleepTime != oldSleepTime {
			fs.Debug("pacer", "Reducing sleep to %v", p.sleepTime)
		}
	}
	p.mu.Unlock()
}

// call implements Call but with settable retries
func (p *Pacer) call(fn Paced, retries int) (err error) {
	var again bool
	for i := 0; i < retries; i++ {
		p.beginCall()
		again, err = fn()
		p.endCall(again)
		if !again {
			break
		}
	}
	if again {
		err = fs.RetryError(err)
	}
	return err
}

// Call paces the remote operations to not exceed the limits and retry
// on rate limit exceeded
//
// This calls fn, expecting it to return a retry flag and an
// error. This error may be returned wrapped in a RetryError if the
// number of retries is exceeded.
func (p *Pacer) Call(fn Paced) (err error) {
	p.mu.Lock()
	retries := p.retries
	p.mu.Unlock()
	return p.call(fn, retries)
}

// Pace the remote operations to not exceed Amazon's limits and return
// a retry error on rate limit exceeded
//
// This calls fn and wraps the output in a RetryError if it would like
// it to be retried
func (p *Pacer) CallNoRetry(fn Paced) error {
	return p.call(fn, 1)
}

redpajama_set_name: RedPajamaGithub


text:
Package.describe({
  name: 'minicast:qml-game',
  summary: 'defines basic functionality for games of quantified modal logic ',
  version: '0.1.0',
  // git: 'https://github.com/minicast/meteor-qml-game'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0.1');
  api.use(['meteor', 'ddp', 'jquery', 'coffeescript']);

  api.addFiles('server/game.coffee', ['server']);

  api.export(['G', 'S', 'F']);
});

Package.onTest(function(api){
  api.use('mike:mocha-package');
  api.addFiles('server/game.coffee', ['server']);
  api.addFiles('tests/tests.js', ['server']);
});


text:
<?php

namespace Sylius\Bundle\ResourceBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\Request;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 * @author Dosena Ishmael <nukboon@gmail.com>
 */
final class ParametersParser implements ParametersParserInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @var ExpressionLanguage
     */
    private $expression;

    /**
     * @param ContainerInterface $container
     * @param ExpressionLanguage $expression
     */
    public function __construct(ContainerInterface $container, ExpressionLanguage $expression)
    {
        $this->container = $container;
        $this->expression = $expression;
    }

    /**
     * {@inheritdoc}
     */
    public function parseRequestValues(array $parameters, Request $request)
    {
        foreach ($parameters as $key => $value) {
            if (is_array($value)) {
                $parameters[$key] = $this->parseRequestValues($value, $request);
            }

            if (is_string($value) && 0 === strpos($value, '$')) {
                $parameterName = substr($value, 1);
                $parameters[$key] = $request->get($parameterName);
            }

            if (is_string($value) && 0 === strpos($value, 'expr:')) {
                $service = substr($value, 5);

                if (preg_match_all('/(\$\w+)\W/', $service, $match)) {
                    foreach ($match[1] as $parameterName) {
                        $parameter = $request->get(substr(trim($parameterName), 1));
                        $parameter = is_string($parameter) ? sprintf('"%s"', $parameter) : $parameter;
                        $service = str_replace($parameterName, $parameter, $service);
                    }
                }

                $parameters[$key] = $this->expression->evaluate($service, ['container' => $this->container]);
            }
        }

        return $parameters;
    }
}


text:
SK_EXPORT @interface SKComponentScene : SKScene <SKPhysicsContactDelegate> {
}

@property (nonatomic) CFTimeInterval dt;
@property (nonatomic) CFTimeInterval dtLimit;

- (void) registerComponentNode:(SKComponentNode*)node;
- (void) unregisterComponentNode:(SKComponentNode*)node;
- (void)update:(NSTimeInterval)currentTime __attribute__((objc_requires_super));
@end


text:
frappe.ui.form.on("RQ Worker", {
	refresh: function (frm) {
		// Nothing in this form is supposed to be editable.
		frm.disable_form();
	},
});


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="whisper">
        <note>
            Frames file for 'whisper' based on sentences in financial subcorpus
            and automatic expansion via verbnet.
        </note>

        <roleset id="whisper.01" name="speak quietly" vncls="37.3">
            <roles>
                <role descr="speaker" n="0">

                    <vnrole vncls="37.3" vntheta="Agent"/>
                </role>

                <role descr="utterance" n="1">

                    <vnrole vncls="37.3" vntheta="Topic"/>
                </role>

                <role descr="hearer" n="2">

                    <vnrole vncls="37.3" vntheta="Recipient"/>
                </role>

            </roles>

            <example name="all args">
                <inflection aspect="progressive" form="participle" person="ns" tense="ns" voice="active"/>
                <text>
                    The executive recalls Mr. Corry whispering to him and others,
                    ``Remember, this was Dave's deal.''
                </text>
                <arg n="0">Mr. Corry</arg>
                <rel>whispering</rel>
                <arg n="2">to him and others</arg>
                <arg n="1">Remember, this was Dave's deal</arg>
            </example>

            <example name="without utterance" src="scream.01">
                <text>
                    John whispered in Mary's ear.
                </text>
                <arg n="0">John</arg>
                <rel>whispered</rel>
                <arg n="2">in Mary's ear</arg>
            </example>

        </roleset>
    </predicate>
</frameset>


text:
import React from 'react';
import { get } from 'lodash';

import { FormField, CheckboxInput } from 'core/presentation';
import { HelpField } from 'core/help/HelpField';
import { ITriggerTemplateComponentProps } from '../../../manualExecution/TriggerTemplate';

export class ManualExecutionBake extends React.Component<ITriggerTemplateComponentProps> {
  private handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const target = event.target;
    const checked = target.checked;
    this.props.updateCommand('trigger.rebake', checked);
    this.setState({});
  };

  public render() {
    const force = get(this.props.command, 'trigger.rebake', false);

    return (
      <FormField
        label="Rebake"
        onChange={this.handleChange}
        value={force}
        help={<HelpField id="execution.forceRebake" />}
        input={props => <CheckboxInput {...props} text="Force Rebake" />}
      />
    );
  }
}


text:
package com.donoroncall.server.rest.undertow.handlers

import io.undertow.server.{HttpServerExchange, HttpHandler}

/**
  * Created by vishnu on 20/1/16.
  */
class DefaultApiHandler extends HttpHandler {
  override def handleRequest(exchange: HttpServerExchange): Unit = {
    exchange.getResponseSender.send("{\"status\":\"ok\"}")
  }
}


text:
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// ReSharper disable CheckNamespace

namespace System.Buffers {
    // SourceTools-Start
    // Remote-File C:\ASP\src\Shared\Buffers.MemoryPool\DiagnosticMemoryPool.cs
    // Start-At-Remote-Line 9
    // SourceTools-End
    /// <summary>
    /// Used to allocate and distribute re-usable blocks of memory.
    /// </summary>
    internal class DiagnosticMemoryPool : MemoryPool<byte> {
        private readonly MemoryPool<byte> _pool;

        private readonly bool _allowLateReturn;

        private readonly bool _rentTracking;

        private readonly object _syncObj;

        private readonly HashSet<DiagnosticPoolBlock> _blocks;

        private readonly List<Exception> _blockAccessExceptions;

        private readonly TaskCompletionSource<object> _allBlocksReturned;

        private int _totalBlocks;

        /// <summary>
        /// This default value passed in to Rent to use the default value for the pool.
        /// </summary>
        private const int AnySize = -1;

        public DiagnosticMemoryPool(MemoryPool<byte> pool, bool allowLateReturn = false, bool rentTracking = false) {
            _pool = pool;
            _allowLateReturn = allowLateReturn;
            _rentTracking = rentTracking;
            _blocks = new HashSet<DiagnosticPoolBlock>();
            _syncObj = new object();
            _allBlocksReturned = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
            _blockAccessExceptions = new List<Exception>();
        }

        public bool IsDisposed { get; private set; }

        public override IMemoryOwner<byte> Rent(int size = AnySize) {
            lock (_syncObj) {
                if (IsDisposed) {
                    MemoryPoolThrowHelper.ThrowObjectDisposedException(MemoryPoolThrowHelper.ExceptionArgument.MemoryPool);
                }

                var diagnosticPoolBlock = new DiagnosticPoolBlock(this, _pool.Rent(size));
                if (_rentTracking) {
                    diagnosticPoolBlock.Track();
                }
                _totalBlocks++;
                _blocks.Add(diagnosticPoolBlock);
                return diagnosticPoolBlock;
            }
        }

        public override int MaxBufferSize => _pool.MaxBufferSize;

        internal void Return(DiagnosticPoolBlock block) {
            bool returnedAllBlocks;
            lock (_syncObj) {
                _blocks.Remove(block);
                returnedAllBlocks = _blocks.Count == 0;
            }

            if (IsDisposed) {
                if (!_allowLateReturn) {
                    MemoryPoolThrowHelper.ThrowInvalidOperationException_BlockReturnedToDisposedPool(block);
                }

                if (returnedAllBlocks) {
                    SetAllBlocksReturned();
                }
            }

        }

        internal void ReportException(Exception exception) {
            lock (_syncObj) {
                _blockAccessExceptions.Add(exception);
            }
        }

        protected override void Dispose(bool disposing) {
            if (IsDisposed) {
                MemoryPoolThrowHelper.ThrowInvalidOperationException_DoubleDispose();
            }

            bool allBlocksReturned = false;
            try {
                lock (_syncObj) {
                    IsDisposed = true;
                    allBlocksReturned = _blocks.Count == 0;
                    if (!allBlocksReturned && !_allowLateReturn) {
                        MemoryPoolThrowHelper.ThrowInvalidOperationException_DisposingPoolWithActiveBlocks(_totalBlocks - _blocks.Count, _totalBlocks, _blocks.ToArray());
                    }

                    if (_blockAccessExceptions.Any()) {
                        throw CreateAccessExceptions();
                    }
                }
            } finally {
                if (allBlocksReturned) {
                    SetAllBlocksReturned();
                }
            }
        }

        private void SetAllBlocksReturned() {
            if (_blockAccessExceptions.Any()) {
                _allBlocksReturned.SetException(CreateAccessExceptions());
            } else {
                _allBlocksReturned.SetResult(null);
            }
        }

        private AggregateException CreateAccessExceptions() {
            return new AggregateException("Exceptions occurred while accessing blocks", _blockAccessExceptions.ToArray());
        }

        public async Task WhenAllBlocksReturnedAsync(TimeSpan timeout) {
            var task = await Task.WhenAny(_allBlocksReturned.Task, Task.Delay(timeout));
            if (task != _allBlocksReturned.Task) {
                MemoryPoolThrowHelper.ThrowInvalidOperationException_BlocksWereNotReturnedInTime(_totalBlocks - _blocks.Count, _totalBlocks, _blocks.ToArray());
            }

            await task;
        }
    }
}


text:
package com.amazonaws.services.redshift.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Describes the status of the elastic IP (EIP) address.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ElasticIpStatus implements Serializable, Cloneable {

    /**
     *

     * The elastic IP (EIP) address for the cluster.
     *

     */
    private String elasticIp;
    /**
     *

     * The status of the elastic IP (EIP) address.
     *

     */
    private String status;

    /**
     *

     * The elastic IP (EIP) address for the cluster.
     *

     *
     * @param elasticIp
     *        The elastic IP (EIP) address for the cluster.
     */

    public void setElasticIp(String elasticIp) {
        this.elasticIp = elasticIp;
    }

    /**
     *

     * The elastic IP (EIP) address for the cluster.
     *

     *
     * @return The elastic IP (EIP) address for the cluster.
     */

    public String getElasticIp() {
        return this.elasticIp;
    }

    /**
     *

     * The elastic IP (EIP) address for the cluster.
     *

     *
     * @param elasticIp
     *        The elastic IP (EIP) address for the cluster.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ElasticIpStatus withElasticIp(String elasticIp) {
        setElasticIp(elasticIp);
        return this;
    }

    /**
     *

     * The status of the elastic IP (EIP) address.
     *

     *
     * @param status
     *        The status of the elastic IP (EIP) address.
     */

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     *

     * The status of the elastic IP (EIP) address.
     *

     *
     * @return The status of the elastic IP (EIP) address.
     */

    public String getStatus() {
        return this.status;
    }

    /**
     *

     * The status of the elastic IP (EIP) address.
     *

     *
     * @param status
     *        The status of the elastic IP (EIP) address.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ElasticIpStatus withStatus(String status) {
        setStatus(status);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getElasticIp() != null)
            sb.append("ElasticIp: ").append(getElasticIp()).append(",");
        if (getStatus() != null)
            sb.append("Status: ").append(getStatus());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof ElasticIpStatus == false)
            return false;
        ElasticIpStatus other = (ElasticIpStatus) obj;
        if (other.getElasticIp() == null ^ this.getElasticIp() == null)
            return false;
        if (other.getElasticIp() != null && other.getElasticIp().equals(this.getElasticIp()) == false)
            return false;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getElasticIp() == null) ? 0 : getElasticIp().hashCode());
        hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
        return hashCode;
    }

    @Override
    public ElasticIpStatus clone() {
        try {
            return (ElasticIpStatus) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


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

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center" >

        <SurfaceView
            android:id="@+id/surfaceView2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="right|bottom" />

        <Button
            android:id="@+id/button"
            android:layout_width="67dp"
            android:layout_height="63dp"
            android:layout_gravity="left|bottom"
            android:background="@drawable/refresh" />

        <view
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|bottom"
            class="ru.o2genum.coregame.link.MyProgress" />

        <Button
            android:id="@+id/button1"
            android:layout_width="67dp"
            android:layout_height="63dp"
            android:layout_gravity="right|bottom"
            android:background="@drawable/tip" />

    </FrameLayout>

</LinearLayout>


text:
package com.plivo.api.models.message;

import com.plivo.api.models.base.BaseResource;

public class MmsMedia extends BaseResource {
  private String content_type;
  private String media_id;
  private String media_url;
  private String message_uuid;
  private long size;

  public String getContentType() {
    return content_type;
  }

  public String getMediaId() {
    return media_id;
  }

  public String getMediaUrl() {
    return media_url;
  }

  public String getMessageUuid() {
    return message_uuid;
  }

  public long getSize() {
    return size;
  }

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


text:
#nullable disable

using System;
using System.Collections.Generic;
using System.IO;
using SharpCompress.Common.Tar.Headers;
using SharpCompress.IO;

namespace SharpCompress.Common.Tar
{
    public class TarEntry : Entry
    {
        private readonly TarFilePart _filePart;

        internal TarEntry(TarFilePart filePart, CompressionType type)
        {
            this._filePart = filePart;
            CompressionType = type;
        }

        public override CompressionType CompressionType { get; }

        public override long Crc => 0;

        public override string Key => _filePart.Header.Name;

        public override string LinkTarget => _filePart.Header.LinkName;

        public override long CompressedSize => _filePart.Header.Size;

        public override long Size => _filePart.Header.Size;

        public override DateTime? LastModifiedTime => _filePart.Header.LastModifiedTime;

        public override DateTime? CreatedTime => null;

        public override DateTime? LastAccessedTime => null;

        public override DateTime? ArchivedTime => null;

        public override bool IsEncrypted => false;

        public override bool IsDirectory => _filePart.Header.EntryType == EntryType.Directory;

        public override bool IsSplitAfter => false;

        public long Mode => _filePart.Header.Mode;

        public long UserID => _filePart.Header.UserId;

        public long GroupId => _filePart.Header.GroupId;

        internal override IEnumerable<FilePart> Parts => _filePart.AsEnumerable<FilePart>();

        internal static IEnumerable<TarEntry> GetEntries(StreamingMode mode, Stream stream,
                                                         CompressionType compressionType, ArchiveEncoding archiveEncoding)
        {
            foreach (TarHeader h in TarHeaderFactory.ReadHeader(mode, stream, archiveEncoding))
            {
                if (h != null)
                {
                    if (mode == StreamingMode.Seekable)
                    {
                        yield return new TarEntry(new TarFilePart(h, stream), compressionType);
                    }
                    else
                    {
                        yield return new TarEntry(new TarFilePart(h, null), compressionType);
                    }
                }
            }
        }
    }
}


text:
package ru.job4j.chess;

/**
 * class Horse - extends Figure.
 * @author Evgeniy lanov (komrad1812@yandex.ru).
 * @version $Id$
 * @since 0.1
 */
public class Horse extends Figure {

	/**
	 * constructor.
	 * @param start - cell were figure set.
	 */
	public Horse(Cell start) {
		super(start);
	}

	/**
	 * metod valideMove - checks correct move.
	 * @param dest - destanation cell.
	 * @return boolean.
	 */
	public boolean valideMove(Cell dest) {
		this.setMoveBehavior(new MoveLikeHorse(this.getPosition()));
		int xPos = Math.abs(dest.getX() - this.getPosition().getX());
		int yPos = Math.abs(dest.getY() - this.getPosition().getY());
		if ((xPos == 2) && (yPos == 1)) {
			return true;
		} else if ((yPos == 2) && (xPos == 1)) {
			return true;
		}
		return false;
	}

	/**
	 * metod show.
	 * @return String.
	 */
	public String show() {
		return "H";
	}
}


text:
#ifndef COCOS_EVENT_HANDLER_H_
#define COCOS_EVENT_HANDLER_H_

#include <QObject>

class CocosEventHandler: public QObject {
Q_OBJECT

public:
    static CocosEventHandler* getInstance();

public slots:
    void cleanup();
    void onTweetPress(QString, QString);
    void onFriendStaged(QString);
    void onStarStaged(QString);
    void onStagePicked(QString, QString);
    void resetControls();

signals:
    void tweet(QString, QString);
    void buddy(QString);
    void star(QString);
    void stage(QString, QString);
    void reset();

private:
    CocosEventHandler();
    ~CocosEventHandler();
    CocosEventHandler(const CocosEventHandler &);
    CocosEventHandler& operator=(const CocosEventHandler &);
};

#endif /* CocosEventHANDLER_H_ */


text:
package ccc

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// SaveRTCStatsV2 invokes the ccc.SaveRTCStatsV2 API synchronously
func (client *Client) SaveRTCStatsV2(request *SaveRTCStatsV2Request) (response *SaveRTCStatsV2Response, err error) {
	response = CreateSaveRTCStatsV2Response()
	err = client.DoAction(request, response)
	return
}

// SaveRTCStatsV2WithChan invokes the ccc.SaveRTCStatsV2 API asynchronously
func (client *Client) SaveRTCStatsV2WithChan(request *SaveRTCStatsV2Request) (<-chan *SaveRTCStatsV2Response, <-chan error) {
	responseChan := make(chan *SaveRTCStatsV2Response, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.SaveRTCStatsV2(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// SaveRTCStatsV2WithCallback invokes the ccc.SaveRTCStatsV2 API asynchronously
func (client *Client) SaveRTCStatsV2WithCallback(request *SaveRTCStatsV2Request, callback func(response *SaveRTCStatsV2Response, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *SaveRTCStatsV2Response
		var err error
		defer close(result)
		response, err = client.SaveRTCStatsV2(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// SaveRTCStatsV2Request is the request struct for api SaveRTCStatsV2
type SaveRTCStatsV2Request struct {
	*requests.RpcRequest
	CallId         string `position:"Query" name:"CallId"`
	SenderReport   string `position:"Query" name:"SenderReport"`
	InstanceId     string `position:"Query" name:"InstanceId"`
	ReceiverReport string `position:"Query" name:"ReceiverReport"`
	GoogAddress    string `position:"Query" name:"GoogAddress"`
	GeneralInfo    string `position:"Query" name:"GeneralInfo"`
}

// SaveRTCStatsV2Response is the response struct for api SaveRTCStatsV2
type SaveRTCStatsV2Response struct {
	*responses.BaseResponse
	HttpStatusCode int64  `json:"HttpStatusCode" xml:"HttpStatusCode"`
	RequestId      string `json:"RequestId" xml:"RequestId"`
	Success        bool   `json:"Success" xml:"Success"`
	Code           string `json:"Code" xml:"Code"`
	Message        string `json:"Message" xml:"Message"`
	TimeStamp      int64  `json:"TimeStamp" xml:"TimeStamp"`
	RowCount       int64  `json:"RowCount" xml:"RowCount"`
}

// CreateSaveRTCStatsV2Request creates a request to invoke SaveRTCStatsV2 API
func CreateSaveRTCStatsV2Request() (request *SaveRTCStatsV2Request) {
	request = &SaveRTCStatsV2Request{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("CCC", "2020-07-01", "SaveRTCStatsV2", "", "")
	request.Method = requests.POST
	return
}

// CreateSaveRTCStatsV2Response creates a response to parse from SaveRTCStatsV2 response
func CreateSaveRTCStatsV2Response() (response *SaveRTCStatsV2Response) {
	response = &SaveRTCStatsV2Response{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

// for custrom navigation transition animation
@property (strong, nonatomic) UINavigationController *AppNavigationController;
@property (assign, nonatomic) CGPoint UserTouchPoint;
@property (strong, nonatomic) UIView *UserTouchView;
@property (strong, nonatomic) TestNavigationControllerDelegate *NaviDelegate;
@end


text:
cmake_minimum_required(VERSION 2.8)

option (BUILD_GL_3_0_RENDERER "Build a faster OpenGL 3.0 renderer backend" ON)
option (BUILD_GL_2_0_RENDERER "Build an OpenGL 2.0 renderer backend" ON)

set (RENDERERS "")
set (RENDERER_SOURCES "")
set (RENDERER_LIBRARIES "")
set (RENDERER_INCLUDE_DIRS "")

if(BUILD_GL_3_0_RENDERER)
		find_package(OpenGL)
		if (NOT OPENGL_FOUND)
				message(WARNING "OpenGL not found for GL_3_0 renderer")
		else()
			if (NOT RENDERERS)
				set(RENDERERS "GL_3_0")
			else()
				set(RENDERERS "${RENDERERS}:GL_3_0")
			endif()
			AUX_SOURCE_DIRECTORY(framework/render/gl30 RENDERER_SOURCES)
			list(APPEND RENDERER_LIBRARIES ${OPENGL_gl_LIBRARY})
			list(APPEND RENDERER_INCLUDE_DIRS ${OPENGL_INCLUDE_DIR})
		endif()
endif()

if(BUILD_GL_2_0_RENDERER)
		find_package(OpenGL)
		if (NOT OPENGL_FOUND)
				message(WARNING "OpenGL not found for GL_2_0 renderer")
		else()
			if (NOT RENDERERS)
				set(RENDERERS "GL_2_0")
			else()
				set(RENDERERS "${RENDERERS}:GL_2_0")
			endif()
			AUX_SOURCE_DIRECTORY(framework/render/gl20 RENDERER_SOURCES)
			list(APPEND RENDERER_LIBRARIES ${OPENGL_gl_LIBRARY})
			list(APPEND RENDERER_INCLUDE_DIRS ${OPENGL_INCLUDE_DIR})
		endif()
endif()

message("Building renderers: ${RENDERERS}")
add_definitions("-DRENDERERS=\"${RENDERERS}\"")


text:
require "spray_paint/engine"
require "digest/sha1"

module SprayPaint
  module Tags
    extend ActiveSupport::Concern

    included do
      has_many :taggings, :class_name => "SprayPaint::Tagging", :dependent => :destroy, :as => :taggable
      has_many :tags, :through => :taggings, :class_name => "SprayPaint::Tag", :source => :tag do
        def names
          pluck 'name'
        end

        def inspect
          names.inspect
        end

        def <<(*args)
          args.flatten.map(&:downcase).uniq.each do |tag|
            self.push SprayPaint::Tag.find_or_create_by_name(tag) unless tagged?(tag)
          end
          self
        end

        def ==(other)
          names == other
        end

        private
        def tagged?(name)
          names.include?(name.downcase)
        end
      end

      def self.tagged(*tags)
        tags.flatten.inject scoped do |scope, tag|
          uniq_key = Digest::SHA1.hexdigest("#{Time.now.to_i}-#{tag}")[0..5]

          join_table = "tag_#{uniq_key}"
          tagging_table = "tagging_#{uniq_key}"

          taggings_join = %Q{
            INNER JOIN spray_paint_taggings AS #{tagging_table}
            ON #{table_name}.id = #{tagging_table}.taggable_id AND #{tagging_table}.taggable_type = '#{base_class.to_s}'
          }

          tag_join = "INNER JOIN spray_paint_tags AS #{join_table} ON #{join_table}.id = #{tagging_table}.tag_id"

          scope.joins(taggings_join).joins(tag_join).where(join_table.to_sym => {:name => tag.downcase})
        end
      end
    end

    def tags=(*args)
      tags.clear

      tags << args

      tags
    end
  end
end


text:
package ru.stqa.pft.jira.tests;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpHost;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.openqa.selenium.remote.BrowserType;
import org.testng.SkipException;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import ru.stqa.pft.jira.appmanager.ApplicationManager;
import ru.stqa.pft.jira.model.Issue;

import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * Created by Юрий on 09.04.2016.
 */
public class TestBase {

  protected static final ApplicationManager app =
          new ApplicationManager(System.getProperty("browser", BrowserType.FIREFOX)) ;

  @BeforeSuite
  public void setUp() throws Exception {
    app.init();
  }

  @AfterSuite(alwaysRun = true)
  public void tearDown() throws IOException {
    app.stop();
  }

  public void skipIfNotFixed(int issueId) throws IOException {
    if (isIssueOpen(issueId)) {
      System.out.println("Ignored because of issue " + issueId);
      throw new SkipException("Ignored because of issue " + issueId);
    }
  }

  private boolean isIssueOpen(int issueId) throws IOException {
    boolean isIssueOpen = false;
    Set<Issue> issues = getIssue();
    Issue anyIssue = issues.iterator().next();
    String status = "";
    for (Issue issue : issues) {
      if (issue.getId() == issueId) {
        status = getIssueStatus(issueId);
        if (status.equals("Open") || status.equals("In Progress"))
        isIssueOpen = true;
        break;
      }
    }
    return isIssueOpen;
  }

  private String getIssueStatus(int issueId) throws IOException {
    String requestString = "http://demo.bugify.com/api/issues/" + issueId + ".json";
    String json = getExecutor().execute(Request.Get(requestString))
            .returnContent().asString();
    JsonElement parsed = new JsonParser().parse(json);
    JsonElement issues = parsed.getAsJsonObject().get("issues");
    List<Issue> issueData = new Gson().fromJson(issues, new TypeToken<List<Issue>>(){}.getType());
    Issue issue = issueData.iterator().next();
    return issue.getState_name();
  }

  Set<Issue> getIssue() throws IOException {
    String json = getExecutor().execute(Request.Get("http://demo.bugify.com/api/issues.json"))
            .returnContent().asString();
    JsonElement parsed = new JsonParser().parse(json);
    JsonElement issues = parsed.getAsJsonObject().get("issues");
    return new Gson().fromJson(issues, new TypeToken<Set<Issue>>(){}.getType());
  }

  private Executor getExecutor() {
    CloseableHttpClient httpClient = HttpClients.custom()
                .setProxy(new HttpHost("proxy.mdi.ru", 3128))
                .setRedirectStrategy(new LaxRedirectStrategy()).build();
    return Executor.newInstance(httpClient).auth("LSGjeU4yP1X493ud1hNniA==", "");
  }

  int createIssue(Issue newIssue) throws IOException {
    String json = getExecutor().execute(Request.Post("http://demo.bugify.com/api/issues.json")
            .bodyForm(new BasicNameValuePair("subject", newIssue.getSubject()),
                      new BasicNameValuePair("description", newIssue.getDescription())))
            .returnContent().asString();
    JsonElement parsed = new JsonParser().parse(json);
    return parsed.getAsJsonObject().get("issue_id").getAsInt();
  }
}


text: <?php if (!defined('APPLICATION')) exit(); ?>


text:
namespace Backend.Fx.BuildingBlocks
{
    /// <summary>
    /// A marker interface to domain application services to be auto registered in the container on boot
    /// </summary>
    public interface IDomainService
    {
    }
}


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>Return just PID of script with 'ps' and 'awk' · Leif Madsen</title>

  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/poole.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/poole-overrides.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde-overrides.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde-x.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/highlight/monokai.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://blog.leifmadsen.com/touch-icon-144-precomposed.png">
  <link href="http://blog.leifmadsen.com/favicon.png" rel="icon">

  <meta name="description" content="">
  <meta name="keywords" content="">

Leif Madsen

Asterisk, and other worldly endeavours

Blog

Copyright © 2016 License

       Powered by Hugo and Hyde-X

Return just PID of script with 'ps' and 'awk'

Today I ran into an issue where I am running a python script that I needed to get the process ID (PID) of, but that the process was being output with a space between ‘python’ and the actual script name (in this case, jiraircbot.py).

I’m sure it’s totally overkill and there is a much easier way I didn’t find to do this, but after some scouring of The Google, I found something that works! (The purpose of this was to kill off a rogue script process each night so I could restart it.)

Here is what the output looks like with just ps aux | grep python

# ps aux | grep python
root      1120  0.0  0.2  50176  4380 ?        Sl   Aug04  24:52 /usr/bin/python /usr/bin/fail2ban-server -b -s /var/run/fail2ban/fail2ban.sock
root     18182  2.2  1.5  35328 32148 pts/0    S    08:21   0:11 python jiraircbot.py
root     18219  0.0  0.0   3328   804 pts/0    S+   08:29   0:00 grep python

A little bit more data than I wanted, plus of course ‘grep python’ is always going to be returned if I just use grep straight up. Putting many pieces together from a few websites, this is what I came up with to just return the PID of the jiraircbot.py script:

ps -eo pid,command | grep "jiraircbot.py" | grep -v grep | awk '{print $1}'

What I’m doing, is controlling what is returned, so in this case have ps just return the pid and command fields. Run that through grep to just get the script I wanted, pipe that back through grep to remove the line including grep python and then pipe that through awk to just return the first field (which would be the pid of the process I wanted).

All in all, a nice hack :)


text:
#include <stdlib.h>

#include <isl/ctx.h>
#include <isl/options.h>
#include <isl/cpp-checked-conversion.h>

/* Check that converting a NULL object from the checked C++ bindings
 * (where the user is expected to check for NULL return values)
 * to the default C++ bindings (where exceptions are raised
 * instead of returning a NULL object) raises an exception.
 */
static void check_conversion_null(isl_ctx *ctx)
{
	isl::checked::set checked_set;
	isl::set set;

	bool caught = false;
	try {
		set = isl::uncheck(checked_set);
		isl_die(ctx, isl_error_unknown, "no exception raised", return);
	} catch (const isl::exception &e) {
		caught = true;
	}
	if (!caught)
		isl_die(ctx, isl_error_unknown, "no exception raised", return);
}

/* Dummy function on a set in the checked C++ bindings.
 */
static void f_checked(isl::checked::set set)
{
}

/* Dummy function on a set in the default C++ bindings.
 */
static void f_unchecked(isl::set set)
{
}

/* Check the conversion between C++ bindings in function calls.
 * An incorrect call will result in a compiler error.
 */
static void check_conversion_call(isl_ctx *ctx)
{
	isl::set set(ctx, "{ S[i] : 0 <= i < 10 }");
	isl::checked::set checked_set(ctx, "{ S[i] : 0 <= i < 10 }");

	f_unchecked(set);
	f_checked(isl::check(set));
	f_unchecked(isl::uncheck(checked_set));
	f_checked(checked_set);
}

/* Check that a double conversion results in the original set,
 * or at least something that is equal to the original set.
 */
static void check_conversion_equal(isl_ctx *ctx)
{
	isl::set set(ctx, "{ S[i] : 0 <= i < 10 }");
	isl::set set2;
	isl::checked::set checked_set;

	checked_set = isl::check(set);
	set2 = isl::uncheck(checked_set);

	if (!set.is_equal(set2))
		isl_die(ctx, isl_error_unknown, "bad conversion", return);
}

/* Perform some tests on the conversion between the default C++ bindings and
 * the checked C++ bindings.
 */
static void check_conversion(isl_ctx *ctx)
{
	check_conversion_null(ctx);
	check_conversion_call(ctx);
	check_conversion_equal(ctx);
}

int main()
{
	isl_ctx *ctx = isl_ctx_alloc();

	isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);

	check_conversion(ctx);

	isl_ctx_free(ctx);

	return EXIT_SUCCESS;
}


text:
package org.springframework.cloud.dataflow.scheduler.launcher;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.cloud.dataflow.scheduler.launcher.configuration.SchedulerTaskLauncherException;

import static org.hamcrest.CoreMatchers.is;

public class SchedulerTaskLauncherExceptionTests {
	public static final String ERROR_MESSAGE = "ERROR_MESSAGE";

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Test
	public void testMessage() {
		thrown.expect(SchedulerTaskLauncherException.class);
		thrown.expectMessage(ERROR_MESSAGE);
		throw new SchedulerTaskLauncherException(ERROR_MESSAGE);
	}

	@Test
	public void testMessageAndCause() {
		thrown.expect(SchedulerTaskLauncherException.class);
		thrown.expectMessage(ERROR_MESSAGE);
		NullPointerException expectedCause = new NullPointerException();
		thrown.expectCause(is(expectedCause));
		throw new SchedulerTaskLauncherException(ERROR_MESSAGE, expectedCause);
	}

	@Test
	public void testCause() {
		thrown.expect(SchedulerTaskLauncherException.class);
		NullPointerException expectedCause = new NullPointerException();
		thrown.expectCause(is(expectedCause));
		throw new SchedulerTaskLauncherException(expectedCause);
	}
}


text:
UPDATE meta SET meta_value='102' WHERE meta_key='schema_version';

# Patch identifier
INSERT INTO meta (species_id, meta_key, meta_value)
  VALUES (NULL, 'patch', 'patch_101_102_a.sql|schema_version');


text:
// Copyright (c) DNN Software. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Collections.Generic;
using Newtonsoft.Json;

namespace Dnn.Modules.DynamicContentManager.Services.ViewModels
{
    /// <summary>
    /// SnippetViewModel represents a Code Snippet object within the ContentType Web Service API
    /// </summary>
    public class SnippetViewModel
    {
        /// <summary>
        /// Name of the Snippet
        /// </summary>
        [JsonProperty("name")]
        public string Name { get; set; }

        /// <summary>
        /// Code content of the Snippet
        /// </summary>
        [JsonProperty("snippet")]
        public string Snippet { get; set; }
    }
}


text:
(function () {
  'use strict';

  var namespace = angular.module('app.acceptd.acceptd.controllers', [
    'app.settings',
    'app.acceptd.service',
    'app.acceptd.progressbar',
    'app.directory-selector'
  ]);

  namespace.controller('AcceptdController', AcceptdController);

  function AcceptdController($scope, $http, $q, $window, $state, Settings, AcceptdService, Progressbar) {
    var self = this;

    this.scope = $scope;
    this.http = $http;
    this.q = $q;
    this.window = $window;
    this.state = $state;

    this.settings = Settings;
    this.acceptdService = AcceptdService;
    this.progressbar = Progressbar;

    this.scope.progressbar = this.progressbar;

    this.scope.script_params = {};
    this.scope.result = '';
    this.scope.running_script = false;

    this.acceptdService.load_config().success(function (config) {
      $scope.script_params = config;

      self.acceptdService.feature_files(config.selected_project).success(function (feature_files) {
        $scope.feature_files = feature_files;
      });
    });

    this.scope.selectedFiles = function () {
      self.save_config();
    };
  }

  AcceptdController.prototype.save_config = function () {
    //this.scope.script_params.selected_project = this.scope.mySelection[0].id;

    this.acceptdService.save_config(this.scope.script_params);
  };

  AcceptdController.prototype.navigate_to_config = function () {
    this.state.transitionTo('config');
  };

  AcceptdController.prototype.cancel_run = function() {
    if(this.progressbar && this.progressbar.status() == 'started') {
      this.progressbar.stop();
    }
  };

  AcceptdController.prototype.reset_session = function() {
    var url = this.settings.baseUrl + '/reset_session';

    var successHandler = function(result) {};

    var errorHandler = function(result) {};

    this.http.get(url).success(successHandler).error(errorHandler);
  };

  AcceptdController.prototype.run_script = function() {
    var self = this;

    this.scope.running_script = true;

    this.scope.result = '';

    var onSuccess = function (result) {
      self.scope.result += result.data;
    };

    var onError = function (result) {
      self.scope.result += result.data;

      self.progressbar.error();
    };

    var onComplete = function () {
      self.progressbar.stop();
    };

    var selectedFiles = this.scope.script_params.selected_files;

    this.progressbar.start();

    self.acceptdService.run_tests(selectedFiles, this.scope.script_params, onSuccess, onError, onComplete);
  };

})();


text:
namespace system_logs {

// Gathers log data from a single debugd log source, via DebugDaemonClient.
class SingleDebugDaemonLogSource : public SystemLogsSource {
 public:
  enum class SupportedSource {
    // For "modetest" command.
    kModetest,

    // For "lsusb" command.
    kLsusb,

    // For "lspci" command.
    kLspci,

    // For "ifconfig" command.
    kIfconfig,

    // For "/proc/uptime" entry.
    kUptime,
  };

  explicit SingleDebugDaemonLogSource(SupportedSource source);
  ~SingleDebugDaemonLogSource() override;

  // system_logs::SystemLogsSource:
  void Fetch(SysLogsSourceCallback callback) override;

 private:
  // Callback for handling response from DebugDaemonClient.
  void OnFetchComplete(const std::string& log_name,
                       SysLogsSourceCallback callback,
                       base::Optional<std::string> result) const;

  base::WeakPtrFactory<SingleDebugDaemonLogSource> weak_ptr_factory_{this};

  DISALLOW_COPY_AND_ASSIGN(SingleDebugDaemonLogSource);
};

}  // namespace system_logs

#endif  // CHROME_BROWSER_CHROMEOS_SYSTEM_LOGS_SINGLE_DEBUG_DAEMON_LOG_SOURCE_H_


text:
const Base = require('./base');

module.exports = class Conversation extends Base {
  static async create(props) {
    const data = {
      type: props.type,
      network: props.network,
      name: props.name,
      owner: props.owner || null,
      topic: props.topic || null,
      password: props.password || null,
      team: props.team || null,
      secret: props.secret || false
    };

    return super.create(data);
  }

  static get mutableProperties() {
    return ['name', 'owner', 'topic', 'password'];
  }
};


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef _MOTIONGR_MANAGER_H_
#define _MOTIONGR_MANAGER_H_

#ifdef __cplusplus
extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "string.h"
#include "motion_gr.h"
#include "main.h"

/** @addtogroup MOTION_GR_Applications
  * @{
  */

/** @addtogroup GESTURE_RECOGNITION
  * @{
  */

/* Extern variables ----------------------------------------------------------*/
/* Exported Macros -----------------------------------------------------------*/
/* Exported Types ------------------------------------------------------------*/
/* Imported Variables --------------------------------------------------------*/
/* Exported Functions Prototypes ---------------------------------------------*/
uint8_t MotionGR_manager_init(void *handle);
void MotionGR_manager_run(MGR_input_t *data_in, MGR_output_t *data_out);
void MotionGR_manager_get_version(char *version, int *length);

/**
  * @}
  */

/**
  * @}
  */

#ifdef __cplusplus
}
#endif

#endif /* _MOTIONGR_MANAGER_H_ */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


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

      <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"></meta>
      <title>dom4j 1.6.1 Reference Package org.dom4j.tree</title>
      <link rel="stylesheet" href="../../../stylesheet.css" type="text/css" title="style"></link>

        org.dom4j.tree

Classes

            CDataTest

            DefaultDocumentTest

            DefaultElementTest

            NamespaceCacheTest


text:
class CTimedProgressDlg : public CDialog
{
// Construction
public:
	CTimedProgressDlg(CWnd* pParent = NULL);	// standard constructor

// Dialog Data
	//{{AFX_DATA(CTimedProgressDlg)
	enum { IDD = IDD_TIMEDPROGRESS_DIALOG };
	CSliderCtrl	m_slider;
	CButton	m_btnGo;
	CButton	m_btnStop;
	CProgressCtrl	m_progress8;
	CProgressCtrl	m_progress7;
	CProgressCtrl	m_progress6;
	CProgressCtrl	m_progress5;
	TProgressTimeToComplete	m_progress4;
	TProgressTimeToComplete	m_progress3;
	TProgressTimeToComplete	m_progress2;
	TProgressTimeToComplete	m_progress1;
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CTimedProgressDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	HICON m_hIcon;

	// Generated message map functions
	//{{AFX_MSG(CTimedProgressDlg)
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	virtual void OnCancel();
	afx_msg void OnGo();
	afx_msg void OnTimer(UINT nIDEvent);
	afx_msg void OnStop();
	afx_msg void OnDestroy();
	afx_msg void OnSpeedReleasedCapture(NMHDR* pNMHDR, LRESULT* pResult);
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_TIMEDPROGRESSDLG_H__770907F7_A66F_11D4_85BA_00A0CC5F2805__INCLUDED_)


text:
<?php
/**
 * Created by PhpStorm.
 * User: Muhannad Shelleh
 * Date: 9/20/2016
 * Time: 12:26 PM
 */

namespace ItvisionSy\Time;

use ErrorException;

/**
 * Class Time
 *
 * A class to manage time operations and values. It represents a counter of a time units in positive or negative.
 *
 * @package ItvisionSy\Time
 * @property integer hours
 * @property integer minutes
 * @property integer seconds
 * @property integer millis
 * @property integer timestamp
 * @property float inHours
 * @property float inMinutes
 * @property float inSeconds
 * @property float inMillis
 * @method Time|integer hours(integer|string $set = null)
 * @method Time|integer minutes(integer|string $set = null)
 * @method Time|integer seconds(integer|string $set = null)
 * @method Time|integer millis(integer|string $set = null)
 */
class Time
{

    protected static $config = [
        'full_format' => "H:M:S.C",
        'format' => "h:m:s.c",
    ];

    const UNIT_HOURS = 0;
    const UNIT_MINUTES = 1;
    const UNIT_SECONDS = 2;
    const UNIT_MILLIS = 3;
    protected static $multipliers = [
        60 * 60 * 1000,
        60 * 1000,
        1000,
        1
    ];
    protected static $units = [
        'hours',
        'minutes',
        'seconds',
        'millis'
    ];

    protected $time = 0;

    /**
     * Time constructor.
     * @param null $time
     */
    public function __construct($time = null)
    {
        if (!$time) {
            return;
        } elseif (is_string($time)) {
            $this->parseString($time);
        } elseif (is_int($time)) {
            $this->seconds($time);
        } elseif (is_float($time)) {
            $this->seconds((int)$time);
            $this->millis(@(int)explode(".", "{$time}")[1] ?: 0);
        }
    }

    /**
     * @param $timeString
     * @return Time
     */
    public static function makeFromString($timeString)
    {
        return (new static())->parseString($timeString);
    }

    /**
     * @param $timestamp
     * @return Time
     */
    public static function makeFromTimestamp($timestamp)
    {
        return (new static())->seconds($timestamp);
    }

    /**
     * @param string|integer $time
     * @return Time
     */
    public static function make($time = null)
    {
        return new static($time);
    }

    /**
     * @param $timeString
     * @return Time|$this
     */
    public function parseString($timeString)
    {
        $result = preg_match("#^(\d+)(\:(\d+)(\:(\d+)(\.(\d+))?)?)?$#", $timeString, $matches);
        if ($result) {
            $this->hours($matches[1]);
            $this->minutes(@$matches[3] ?: "0");
            $this->seconds(@$matches[5] ?: "0");
            $this->millis(substr(@$matches[7] ?: "0", 0, 3));
        }
        return $this;
    }

    function __get($name)
    {
        switch ($name) {
            case 'hours':
            case 'minutes':
            case 'seconds':
            case 'millis':
                return $this->get($name);
                break;
            case 'inHours':
            case 'inMinutes':
            case 'inSeconds':
            case 'inMillis':
                return $this->represent(substr(strtolower($name), 2));
                break;
            case 'timestamp':
                return $this->time;
                break;
            default:
                trigger_error("Property not defined: {$name}");
        }
        return null;
    }

    function __set($name, $value)
    {
        switch ($name) {
            case 'hours':
            case 'minutes':
            case 'seconds':
            case 'millis':
                return $this->set($name, $value);
                break;
            default:
                throw new ErrorException("Property not defined: {$name}");
        }
        return $this;
    }

    function __call($name, $args)
    {
        switch ($name) {
            case 'hours':
            case 'minutes':
            case 'seconds':
            case 'millis':
                return count($args) == 1 ? $this->set($name, $args[0]) : $this->get($name);
                break;
            default:
                throw new ErrorException("Method not defined: {$name}");
        }
        return null;
    }

    /**
     * @param $unit
     * @return float
     */
    public function get($unit)
    {
        $unitKey = $this->getUnitKey($unit);
        $unitMultiplier = static::$multipliers[$unitKey];
        $unitReminder = $unitKey == 0 ? 0 : static::$multipliers[$unitKey - 1];
        $value = floor(($unitReminder ? $this->time % $unitReminder : $this->time) / $unitMultiplier);
        return $value;
    }

    /**
     * @param string $unit
     * @param string|integer $value
     * @return Time|$this
     */
    public function set($unit, $value)
    {
        $unitKey = $this->getUnitKey($unit);
        $oldValue = $this->get($unit);
        $unitMultiplier = static::$multipliers[$unitKey];
        $newValue = gettype($value) === 'string' ? $this->parseStringValue($value, $oldValue) : (int)$value;
        $this->time = $this->time + ($newValue - $oldValue) * $unitMultiplier;
        return $this;
    }

    /**
     * @param string $value
     * @param $oldValue
     * @return int
     */
    protected function parseStringValue($value, $oldValue)
    {
        if (array_search(substr("{$value}", 0, 1), ["+", "-"]) !== false) {
            $delta = (int)$value;
            return $oldValue + $delta;
        } else {
            return (int)$value;
        }
    }

    /**
     * @param bool $leadingZeros
     * @return string
     */
    public function toTimeString($leadingZeros = false)
    {
        $sign = $this->hours < 0 ? "-" : "";
        $hours = $this->hours;
        $minutes = $leadingZeros ? str_pad($this->minutes, 2, "0", STR_PAD_LEFT) : $this->minutes;
        $seconds = $leadingZeros ? str_pad($this->seconds, 2, "0", STR_PAD_LEFT) : $this->seconds;
        $millis = $leadingZeros ? str_pad($this->millis, 3, "0", STR_PAD_LEFT) : $this->millis;
        return $sign . str_replace("-", "", "{$hours}:{$minutes}:{$seconds}.{$millis}");
    }

    /**
     * @param string $format c=milli, C=leading milli, h=hours, H=leading hours, m=minutes, M=leading minutes, s=seconds, S=leading seconds
     * @return string
     */
    public function format($format = null)
    {
        if ($format === true) {
            $format = static::$config['full_format'];//"H:M:S.C";
        } elseif ($format === null) {
            $format = static::$config['format'];//"h:m:s.c"
        }
        $result = preg_replace_callback("#(\\\\)?([HhMmSsCc])#", function ($matches) {
            if ($matches[1] === "\\") {
                return $matches[0];
            }
            switch ($matches[2]) {
                case 'S':
                    return str_pad($this->seconds, 2, '0', STR_PAD_LEFT);
                    break;
                case 's':
                    return $this->seconds;
                    break;
                case 'M':
                    return str_pad($this->minutes, 2, '0', STR_PAD_LEFT);
                    break;
                case 'm':
                    return $this->minutes;
                    break;
                case 'H':
                    return str_pad($this->hours, 2, '0', STR_PAD_LEFT);
                    break;
                case 'h':
                    return $this->hours;
                    break;
                case 'C':
                    return str_pad($this->millis, 3, '0', STR_PAD_LEFT);
                    break;
                case 'c':
                    return $this->millis;
                    break;
            }
        }, $format);
        return $result;
    }

    function __toString()
    {
        return $this->format();
    }

    /**
     * @param string $unit
     * @return Time|$this
     */
    public function tick($unit = "seconds")
    {
        return $this->set($unit, "+1");
    }

    /**
     * Creates a new instance with the current time value
     * @return Time
     */
    public function copy()
    {
        return new static($this->format());
    }

    /**
     * @return int
     */
    public function timestamp()
    {
        return $this->time;
    }

    /**
     * @param Time $compareTo
     * @return Time
     */
    public function diff(Time $compareTo)
    {
        return new static(($this->timestamp() - $compareTo->timestamp) / 1000);
    }

    /**
     * @param string $unit
     * @return float|int
     */
    public function represent($unit)
    {
        $unitKey = $this->getUnitKey($unit);
        $unitMultiplier = static::$multipliers[$unitKey];
        return round($this->time / $unitMultiplier, 3);
    }

    /**
     * @return bool
     */
    public function isMinus()
    {
        return $this->hours < 0;
    }

    /**
     * @return bool
     */
    public function isZero()
    {
        return $this->timestamp === 0;
    }

    /**
     * @param Time $compareTo
     * @return bool
     */
    public function isBefore(Time $compareTo)
    {
        return $this->diff($compareTo)->isMinus();
    }

    /**
     * @param Time $compareTo
     * @return bool
     */
    public function isAfter(Time $compareTo)
    {
        return !$this->diff($compareTo)->isZero() && !$this->isBefore($compareTo);
    }

    /**
     * @param Time $compareTo
     * @return bool
     */
    public function isEqual(Time $compareTo)
    {
        return $this->timestamp === $compareTo->timestamp;
    }

    /**
     * @param $unit
     * @return mixed
     * @throws ErrorException
     */
    protected function getUnitKey($unit)
    {
        $unitKey = array_search($unit, static::$units);
        if ($unitKey === false) {
            throw new ErrorException("Unit not defined: {$unit}");
        }
        return $unitKey;
    }

    /**
     * @param $format
     * @param bool $full
     */
    public static function setDefaultFormat($format, $full = false)
    {
        static::$config[($full ? "full_" : "") . "format"] = $format;
    }

    public function add(Time $time)
    {
        return $this->millis('+' . $time->timestamp);
    }

    public function sub(Time $time)
    {
        return $this->millis('-' . $time->timestamp);
    }

}


text:
package com.amazonaws.services.sagemaker.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Provides summary information about a training job.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TrainingJobSummary implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The name of the training job that you want a summary for.
     *

     */
    private String trainingJobName;
    /**
     *

     * The Amazon Resource Name (ARN) of the training job.
     *

     */
    private String trainingJobArn;
    /**
     *

     * A timestamp that shows when the training job was created.
     *

     */
    private java.util.Date creationTime;
    /**
     *

     * A timestamp that shows when the training job ended. This field is set only if the training job has one of the
     * terminal statuses (Completed, Failed, or Stopped).
     *

     */
    private java.util.Date trainingEndTime;
    /**
     *

     * Timestamp when the training job was last modified.
     *

     */
    private java.util.Date lastModifiedTime;
    /**
     *

     * The status of the training job.
     *

     */
    private String trainingJobStatus;

    /**
     *

     * The name of the training job that you want a summary for.
     *

     *
     * @param trainingJobName
     *        The name of the training job that you want a summary for.
     */

    public void setTrainingJobName(String trainingJobName) {
        this.trainingJobName = trainingJobName;
    }

    /**
     *

     * The name of the training job that you want a summary for.
     *

     *
     * @return The name of the training job that you want a summary for.
     */

    public String getTrainingJobName() {
        return this.trainingJobName;
    }

    /**
     *

     * The name of the training job that you want a summary for.
     *

     *
     * @param trainingJobName
     *        The name of the training job that you want a summary for.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TrainingJobSummary withTrainingJobName(String trainingJobName) {
        setTrainingJobName(trainingJobName);
        return this;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the training job.
     *

     *
     * @param trainingJobArn
     *        The Amazon Resource Name (ARN) of the training job.
     */

    public void setTrainingJobArn(String trainingJobArn) {
        this.trainingJobArn = trainingJobArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the training job.
     *

     *
     * @return The Amazon Resource Name (ARN) of the training job.
     */

    public String getTrainingJobArn() {
        return this.trainingJobArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the training job.
     *

     *
     * @param trainingJobArn
     *        The Amazon Resource Name (ARN) of the training job.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TrainingJobSummary withTrainingJobArn(String trainingJobArn) {
        setTrainingJobArn(trainingJobArn);
        return this;
    }

    /**
     *

     * A timestamp that shows when the training job was created.
     *

     *
     * @param creationTime
     *        A timestamp that shows when the training job was created.
     */

    public void setCreationTime(java.util.Date creationTime) {
        this.creationTime = creationTime;
    }

    /**
     *

     * A timestamp that shows when the training job was created.
     *

     *
     * @return A timestamp that shows when the training job was created.
     */

    public java.util.Date getCreationTime() {
        return this.creationTime;
    }

    /**
     *

     * A timestamp that shows when the training job was created.
     *

     *
     * @param creationTime
     *        A timestamp that shows when the training job was created.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TrainingJobSummary withCreationTime(java.util.Date creationTime) {
        setCreationTime(creationTime);
        return this;
    }

    /**
     *

     * A timestamp that shows when the training job ended. This field is set only if the training job has one of the
     * terminal statuses (Completed, Failed, or Stopped).
     *

     *
     * @param trainingEndTime
     *        A timestamp that shows when the training job ended. This field is set only if the training job has one of
     *        the terminal statuses (Completed, Failed, or Stopped).
     */

    public void setTrainingEndTime(java.util.Date trainingEndTime) {
        this.trainingEndTime = trainingEndTime;
    }

    /**
     *

     * A timestamp that shows when the training job ended. This field is set only if the training job has one of the
     * terminal statuses (Completed, Failed, or Stopped).
     *

     *
     * @return A timestamp that shows when the training job ended. This field is set only if the training job has one of
     *         the terminal statuses (Completed, Failed, or Stopped).
     */

    public java.util.Date getTrainingEndTime() {
        return this.trainingEndTime;
    }

    /**
     *

     * A timestamp that shows when the training job ended. This field is set only if the training job has one of the
     * terminal statuses (Completed, Failed, or Stopped).
     *

     *
     * @param trainingEndTime
     *        A timestamp that shows when the training job ended. This field is set only if the training job has one of
     *        the terminal statuses (Completed, Failed, or Stopped).
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TrainingJobSummary withTrainingEndTime(java.util.Date trainingEndTime) {
        setTrainingEndTime(trainingEndTime);
        return this;
    }

    /**
     *

     * Timestamp when the training job was last modified.
     *

     *
     * @param lastModifiedTime
     *        Timestamp when the training job was last modified.
     */

    public void setLastModifiedTime(java.util.Date lastModifiedTime) {
        this.lastModifiedTime = lastModifiedTime;
    }

    /**
     *

     * Timestamp when the training job was last modified.
     *

     *
     * @return Timestamp when the training job was last modified.
     */

    public java.util.Date getLastModifiedTime() {
        return this.lastModifiedTime;
    }

    /**
     *

     * Timestamp when the training job was last modified.
     *

     *
     * @param lastModifiedTime
     *        Timestamp when the training job was last modified.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TrainingJobSummary withLastModifiedTime(java.util.Date lastModifiedTime) {
        setLastModifiedTime(lastModifiedTime);
        return this;
    }

    /**
     *

     * The status of the training job.
     *

     *
     * @param trainingJobStatus
     *        The status of the training job.
     * @see TrainingJobStatus
     */

    public void setTrainingJobStatus(String trainingJobStatus) {
        this.trainingJobStatus = trainingJobStatus;
    }

    /**
     *

     * The status of the training job.
     *

     *
     * @return The status of the training job.
     * @see TrainingJobStatus
     */

    public String getTrainingJobStatus() {
        return this.trainingJobStatus;
    }

    /**
     *

     * The status of the training job.
     *

     *
     * @param trainingJobStatus
     *        The status of the training job.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see TrainingJobStatus
     */

    public TrainingJobSummary withTrainingJobStatus(String trainingJobStatus) {
        setTrainingJobStatus(trainingJobStatus);
        return this;
    }

    /**
     *

     * The status of the training job.
     *

     *
     * @param trainingJobStatus
     *        The status of the training job.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see TrainingJobStatus
     */

    public TrainingJobSummary withTrainingJobStatus(TrainingJobStatus trainingJobStatus) {
        this.trainingJobStatus = trainingJobStatus.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getTrainingJobName() != null)
            sb.append("TrainingJobName: ").append(getTrainingJobName()).append(",");
        if (getTrainingJobArn() != null)
            sb.append("TrainingJobArn: ").append(getTrainingJobArn()).append(",");
        if (getCreationTime() != null)
            sb.append("CreationTime: ").append(getCreationTime()).append(",");
        if (getTrainingEndTime() != null)
            sb.append("TrainingEndTime: ").append(getTrainingEndTime()).append(",");
        if (getLastModifiedTime() != null)
            sb.append("LastModifiedTime: ").append(getLastModifiedTime()).append(",");
        if (getTrainingJobStatus() != null)
            sb.append("TrainingJobStatus: ").append(getTrainingJobStatus());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof TrainingJobSummary == false)
            return false;
        TrainingJobSummary other = (TrainingJobSummary) obj;
        if (other.getTrainingJobName() == null ^ this.getTrainingJobName() == null)
            return false;
        if (other.getTrainingJobName() != null && other.getTrainingJobName().equals(this.getTrainingJobName()) == false)
            return false;
        if (other.getTrainingJobArn() == null ^ this.getTrainingJobArn() == null)
            return false;
        if (other.getTrainingJobArn() != null && other.getTrainingJobArn().equals(this.getTrainingJobArn()) == false)
            return false;
        if (other.getCreationTime() == null ^ this.getCreationTime() == null)
            return false;
        if (other.getCreationTime() != null && other.getCreationTime().equals(this.getCreationTime()) == false)
            return false;
        if (other.getTrainingEndTime() == null ^ this.getTrainingEndTime() == null)
            return false;
        if (other.getTrainingEndTime() != null && other.getTrainingEndTime().equals(this.getTrainingEndTime()) == false)
            return false;
        if (other.getLastModifiedTime() == null ^ this.getLastModifiedTime() == null)
            return false;
        if (other.getLastModifiedTime() != null && other.getLastModifiedTime().equals(this.getLastModifiedTime()) == false)
            return false;
        if (other.getTrainingJobStatus() == null ^ this.getTrainingJobStatus() == null)
            return false;
        if (other.getTrainingJobStatus() != null && other.getTrainingJobStatus().equals(this.getTrainingJobStatus()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getTrainingJobName() == null) ? 0 : getTrainingJobName().hashCode());
        hashCode = prime * hashCode + ((getTrainingJobArn() == null) ? 0 : getTrainingJobArn().hashCode());
        hashCode = prime * hashCode + ((getCreationTime() == null) ? 0 : getCreationTime().hashCode());
        hashCode = prime * hashCode + ((getTrainingEndTime() == null) ? 0 : getTrainingEndTime().hashCode());
        hashCode = prime * hashCode + ((getLastModifiedTime() == null) ? 0 : getLastModifiedTime().hashCode());
        hashCode = prime * hashCode + ((getTrainingJobStatus() == null) ? 0 : getTrainingJobStatus().hashCode());
        return hashCode;
    }

    @Override
    public TrainingJobSummary clone() {
        try {
            return (TrainingJobSummary) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.sagemaker.model.transform.TrainingJobSummaryMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
namespace caffe2 {

template <typename T, class Context>
class BatchSparseToDenseOp : public Operator<Context> {
 public:
  USE_OPERATOR_CONTEXT_FUNCTIONS;
  BatchSparseToDenseOp(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws),
        OP_SINGLE_ARG(TIndex, "dense_last_dim", dense_last_dim_, -1),
        OP_SINGLE_ARG(T, "default_value", default_value_, static_cast<T>(0)) {}
  bool RunOnDevice() override;

 private:
  TIndex dense_last_dim_;
  T default_value_;
  INPUT_TAGS(LENGTHS, INDICES, VALUES);
};

template <typename T, class Context>
class BatchDenseToSparseOp : public Operator<Context> {
 public:
  USE_OPERATOR_CONTEXT_FUNCTIONS;
  BatchDenseToSparseOp(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws) {}
  bool RunOnDevice() override;

 private:
  TIndex dense_last_dim_;
  INPUT_TAGS(LENGTHS, INDICES, DENSE);
};

} // namespace caffe2

#endif // CAFFE2_OPERATORS_BATCH_SPARSE_TO_DENSE_OP_H_


text:
#ifndef ScrollingTreeStickyNode_h
#define ScrollingTreeStickyNode_h

#if ENABLE(ASYNC_SCROLLING)

#include "ScrollingConstraints.h"
#include "ScrollingTreeNode.h"
#include <wtf/RetainPtr.h>

OBJC_CLASS CALayer;

namespace WebCore {

class StickyPositionViewportConstraints;

class ScrollingTreeStickyNode : public ScrollingTreeNode {
public:
    WEBCORE_EXPORT static Ref<ScrollingTreeStickyNode> create(ScrollingTree&, ScrollingNodeID);

    virtual ~ScrollingTreeStickyNode();

private:
    ScrollingTreeStickyNode(ScrollingTree&, ScrollingNodeID);

    void updateBeforeChildren(const ScrollingStateNode&) override;
    void updateLayersAfterAncestorChange(const ScrollingTreeNode& changedNode, const FloatRect& fixedPositionRect, const FloatSize& cumulativeDelta) override;

    StickyPositionViewportConstraints m_constraints;
    RetainPtr<CALayer> m_layer;
};

} // namespace WebCore

SPECIALIZE_TYPE_TRAITS_SCROLLING_NODE(ScrollingTreeStickyNode, isStickyNode())

#endif // ENABLE(ASYNC_SCROLLING)

#endif // ScrollingTreeStickyNode_h


text:
using media_router::interfaces::IssuePtr;
using media_router::interfaces::MediaRoutePtr;
using media_router::interfaces::MediaSinkPtr;

using PresentationConnectionState =
    media_router::interfaces::MediaRouter::PresentationConnectionState;

namespace mojo {

media_router::MediaSink::IconType SinkIconTypeFromMojo(
    media_router::interfaces::MediaSink::IconType type) {
  switch (type) {
    case media_router::interfaces::MediaSink::IconType::ICON_TYPE_CAST:
      return media_router::MediaSink::CAST;
    case media_router::interfaces::MediaSink::IconType::ICON_TYPE_CAST_AUDIO:
      return media_router::MediaSink::CAST_AUDIO;
    case media_router::interfaces::MediaSink::
        IconType::ICON_TYPE_CAST_AUDIO_GROUP:
      return media_router::MediaSink::CAST_AUDIO_GROUP;
    case media_router::interfaces::MediaSink::IconType::ICON_TYPE_HANGOUT:
      return media_router::MediaSink::HANGOUT;
    case media_router::interfaces::MediaSink::IconType::ICON_TYPE_GENERIC:
      return media_router::MediaSink::GENERIC;
    default:
      NOTREACHED() << "Unknown sink icon type " << type;
      return media_router::MediaSink::GENERIC;
  }
}

media_router::interfaces::MediaSink::IconType SinkIconTypeToMojo(
    media_router::MediaSink::IconType type) {
  switch (type) {
    case media_router::MediaSink::CAST:
      return media_router::interfaces::MediaSink::IconType::ICON_TYPE_CAST;
    case media_router::MediaSink::CAST_AUDIO:
      return
          media_router::interfaces::MediaSink::IconType::ICON_TYPE_CAST_AUDIO;
    case media_router::MediaSink::CAST_AUDIO_GROUP:
      return
          media_router::interfaces::MediaSink::
              IconType::ICON_TYPE_CAST_AUDIO_GROUP;
    case media_router::MediaSink::HANGOUT:
      return media_router::interfaces::MediaSink::IconType::ICON_TYPE_HANGOUT;
    case media_router::MediaSink::GENERIC:
      return media_router::interfaces::MediaSink::IconType::ICON_TYPE_GENERIC;
    default:
      NOTREACHED() << "Unknown sink icon type " << type;
      return media_router::interfaces::MediaSink::ICON_TYPE_GENERIC;
  }
}

// static
media_router::MediaSink
TypeConverter<media_router::MediaSink, MediaSinkPtr>::Convert(
    const MediaSinkPtr& input) {
  return media_router::MediaSink(input->sink_id, input->name,
                                 SinkIconTypeFromMojo(input->icon_type));
}

// static
media_router::MediaRoute
TypeConverter<media_router::MediaRoute, MediaRoutePtr>::Convert(
    const MediaRoutePtr& input) {
  return media_router::MediaRoute(
      input->media_route_id, media_router::MediaSource(input->media_source),
      input->media_sink_id, input->description, input->is_local,
      input->custom_controller_path, input->for_display);
}

// static
scoped_ptr<media_router::MediaRoute>
TypeConverter<scoped_ptr<media_router::MediaRoute>, MediaRoutePtr>::Convert(
    const MediaRoutePtr& input) {
  return make_scoped_ptr(new media_router::MediaRoute(
      input->media_route_id, media_router::MediaSource(input->media_source),
      input->media_sink_id, input->description, input->is_local,
      input->custom_controller_path, input->for_display));
}

media_router::Issue::Severity IssueSeverityFromMojo(
    media_router::interfaces::Issue::Severity severity) {
  switch (severity) {
    case media_router::interfaces::Issue::Severity::SEVERITY_FATAL:
      return media_router::Issue::FATAL;
    case media_router::interfaces::Issue::Severity::SEVERITY_WARNING:
      return media_router::Issue::WARNING;
    case media_router::interfaces::Issue::Severity::SEVERITY_NOTIFICATION:
      return media_router::Issue::NOTIFICATION;
    default:
      NOTREACHED() << "Unknown issue severity " << severity;
      return media_router::Issue::WARNING;
  }
}

media_router::IssueAction::Type IssueActionTypeFromMojo(
    media_router::interfaces::Issue::ActionType action_type) {
  switch (action_type) {
    case media_router::interfaces::Issue::ActionType::ACTION_TYPE_DISMISS:
      return media_router::IssueAction::TYPE_DISMISS;
    case media_router::interfaces::Issue::ActionType::ACTION_TYPE_LEARN_MORE:
      return media_router::IssueAction::TYPE_LEARN_MORE;
    default:
      NOTREACHED() << "Unknown issue action type " << action_type;
      return media_router::IssueAction::TYPE_DISMISS;
  }
}

// static
media_router::Issue TypeConverter<media_router::Issue, IssuePtr>::Convert(
    const IssuePtr& input) {
  std::vector<media_router::IssueAction> actions;
  if (input->secondary_actions) {
    actions.reserve(input->secondary_actions.size());
    for (size_t i = 0; i < input->secondary_actions.size(); ++i) {
      actions.push_back(media_router::IssueAction(
          IssueActionTypeFromMojo(input->secondary_actions[i])));
    }
  }
  return media_router::Issue(
      input->title, input->message,
      media_router::IssueAction(IssueActionTypeFromMojo(input->default_action)),
      actions, input->route_id, IssueSeverityFromMojo(input->severity),
      input->is_blocking, input->help_url);
}

content::PresentationConnectionState PresentationConnectionStateFromMojo(
    PresentationConnectionState state) {
  switch (state) {
    case PresentationConnectionState::PRESENTATION_CONNECTION_STATE_CONNECTED:
      return content::PRESENTATION_CONNECTION_STATE_CONNECTED;
    case PresentationConnectionState::PRESENTATION_CONNECTION_STATE_CLOSED:
      return content::PRESENTATION_CONNECTION_STATE_CLOSED;
    case PresentationConnectionState::PRESENTATION_CONNECTION_STATE_TERMINATED:
      return content::PRESENTATION_CONNECTION_STATE_TERMINATED;
    default:
      NOTREACHED() << "Unknown PresentationConnectionState " << state;
      return content::PRESENTATION_CONNECTION_STATE_TERMINATED;
  }
}

}  // namespace mojo