text:
"""Unit tests to cover ContentCategoryService."""

__author__ = 'api.jdilallo@gmail.com (Joseph DiLallo)'

import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
import unittest

from adspygoogle.common import Utils
from tests.adspygoogle.dfa.v1_18 import client
from tests.adspygoogle.dfa.v1_18 import HTTP_PROXY
from tests.adspygoogle.dfa.v1_18 import SERVER_V1_18
from tests.adspygoogle.dfa.v1_18 import VERSION_V1_18

class ContentCategoryServiceTestV1_18(unittest.TestCase):

  """Unittest suite for ContentCategoryService using v1_18."""

  SERVER = SERVER_V1_18
  VERSION = VERSION_V1_18
  client.debug = False
  service = None
  content_category_id = '0'

  def setUp(self):
    """Prepare unittest."""
    print self.id()
    if not self.__class__.service:
      self.__class__.service = client.GetContentCategoryService(
          self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)

  def testGetContentCategory(self):
    """Test whether we can fetch a content category by id"""
    if self.__class__.content_category_id == '0':
      self.testSaveContentCategory()
    content_category_id = self.__class__.content_category_id
    self.assert_(isinstance(self.__class__.service.GetContentCategory(
        content_category_id), tuple))

  def testSaveContentCategory(self):
    """Test whether we can save a content category"""
    content_category = {
        'name': 'Content Category #%s' % Utils.GetUniqueName(),
        'id' : '-1'
    }
    content_category = self.__class__.service.SaveContentCategory(
        content_category)
    self.__class__.content_category_id = content_category[0]['id']
    self.assert_(isinstance(content_category, tuple))

  def testGetContentCategories(self):
    """Test whether we can fetch content categories by criteria."""
    if self.__class__.content_category_id == '0':
      self.testSaveContentCategory()
    search_criteria = {
        'ids': [self.__class__.content_category_id]
    }
    self.__class__.content_category_id = \
        self.__class__.service.GetContentCategories(
        search_criteria)[0]['records'][0]['id']

  def testDeleteContentCategory(self):
    """Test whether we can delete a content category"""
    if self.__class__.content_category_id == '0':
      self.testSaveContentCategory()
    self.assertEqual(self.__class__.service.DeleteContentCategory(
        self.__class__.content_category_id), None)
    self.__class__.content_category_id = '0'

if __name__ == '__main__':
  unittest.main()


text:
(function(exports, parent) {

    "use strict";

    exports.Socket = Socket;

    // ## Global scope

    var GameMsg = parent.GameMsg,
    SocketFactory = parent.SocketFactory,
    J = parent.JSUS;

    /**
     * ## Socket constructor
     *
     * Creates a new instance of Socket
     *
     * @param {NodeGameClient} node Reference to the node instance
     */
    function Socket(node) {

        // ## Public properties

        /**
         * ### Socket.buffer
         *
         * Buffer of queued incoming messages
         *
         * @api private
         */
        this.buffer = [];

        /**
         * ### Socket.outBuffer
         *
         * Buffer of queued outgoing messages
         *
         * TODO: implement!
         *
         * @api private
         */
        // this.outBuffer = [];

        /**
         * ### Socket.session
         *
         * The session id shared with the server
         *
         * This property is initialized only when a game starts
         *
         */
        this.session = null;

        /**
         * ### Socket.userOptions
         *
         * Contains the options that will be passed to the `connect` method
         *
         * The property is set by `node.setup.socket`.
         * Passing options to the `connect` method will overwrite this property.
         *
         * @see node.setup
         * @see Socket.connect
         */
        this.userOptions = {};

        /**
         * ### Socket.socket
         *
         * The actual socket object (e.g. SocketDirect, or SocketIo)
         */
        this.socket = null;

        /**
         * ### Socket.connected
         *
         * Socket connection established
         *
         * For realiably checking whether the connection is established
         * use `Socket.isConnected()`.
         *
         * @see Socket.connecting
         * @see Socket.isConnected
         * @see Socket.onConnect
         * @see Socket.onDisconnect
         */
        this.connected = false;

        /**
         * ### Socket.connecting
         *
         * Socket connection being established
         *
         * TODO see whether we should merge connected / connecting
         * in one variable with socket states.
         *
         * @see Socket.connected
         * @see Socket.isConnected
         * @see Socket.onConnect
         * @see Socket.onDisconnect
         */
        this.connecting = false;

         /**
         * ### Socket.reconnecting
         *
         * Flags that a reconnection is in progress
         *
         * This is useful when `Socket.reconnect()` triggers a disconnection
         *
         * @see Socket.reconnect
         */
        this.reconnecting = false;

         /**
         * ### Socket.connectingTimeout
         *
         * Timeout to cancel the connecting procedure
         *
         * @see Socket.connecting
         * @see Socket.connect
         */
        this.connectingTimeout = null;

         /**
         * ### Socket.connectingTimeoutMs
         *
         * Number of milliseconds for the connecting timeout
         *
         * Default: 10000 (10 seconds)
         *
         * @see Socket.connecting
         * @see Socket.connect
         */
        this.connectingTimeoutMs = 10000;

        /**
         * ### Socket.url
         *
         * The full url to which the socket is connected
         *
         * This is set when a new connection attempt is started.
         *
         * It might not be meaningful for all types of sockets. For example,
         * in case of SocketDirect, it is not an real url.
         *
         * @see Socket.connect
         */
        this.url = null;

        /**
         * ### Socket.channelName
         *
         * The name of the channel to which the socket is connected
         *
         * This is set upon a successful connection.
         *
         * @see Socket.startSession
         */
        this.channelName = null;

        /**
         * ### Socket.type
         *
         * The type of socket used
         */
        this.type = null;

        /**
         * ### Socket.emitOutMsg
         *
         * If TRUE, outgoing messages will be emitted upon sending
         *
         * This allows, for example, to modify all outgoing messages.
         */
        this.emitOutMsg = false;

        /**
         * ### Socket.antiSpoofing
         *
         * If TRUE, sid is added to each message
         *
         * This setting is sent over by server.
         */
        this.antiSpoofing = null;

        // Experimental Journal.
        // TODO: check if we need it.
        this.journalOn = false;

        // Experimental
        this.journal = new parent.NDDB({
            update: {
                indexes: true
            }
        });
        if (!this.journal.player) {
            this.journal.hash('to');
        }

        // this.journal.comparator('stage', function(o1, o2) {
        //     return parent.GameStage.compare(o1.stage, o2.stage);
        // });

        // if (!this.journal.stage) {
        //     this.journal.hash('stage', function(gb) {
        //         if (gb.stage) {
        //             return parent.GameStage.toHash(gb.stage, 'S.s.r');
        //         }
        //     });
        // }
        // End Experimental Code.

        /**
         * ### Socket.node
         *
         * Reference to the node object.
         */
        this.node = node;
    }

    // ## Socket methods

    /**
     * ### Socket.setup
     *
     * Configures the socket
     *
     * @param {object} options Optional. Configuration options.
     *
     * @see node.setup.socket
     */
    Socket.prototype.setup = function(options) {
        if (!options) return;
        if ('object' !== typeof options) {
            throw new TypeError('Socket.setup: options must be object ' +
                                'or undefined.');
        }
        options = J.clone(options);
        if (options.connectingTimeout) {
            if (!J.isInt(options.connectingTimeout, 0)) {

                throw new TypeError('Socket.setup: options.connectingTimeout ' +
                                    'a positive number or undefined.');
            }
            this.connectingTimeoutMs = options.connectingTimeout;
        }
        if (options.type) {
            this.setSocketType(options.type, options);
            options.type = null;
        }
        if ('undefined' !== typeof options.emitOutMsg) {
            this.emitOutMsg = options.emitOutMsg;
            options.emitOutMsg = null;
        }
        this.userOptions = options;
    };

    /**
     * ### Socket.setSocketType
     *
     * Sets the default socket by requesting it to the Socket Factory
     *
     * Supported types: 'Direct', 'SocketIo'.
     *
     * @param {string} type The name of the socket to use.
     * @param {object} options Optional. Configuration options for the socket.
     *
     * @return {object} The newly created socket object.
     *
     * @see SocketFactory
     */
    Socket.prototype.setSocketType = function(type, options) {
        if ('string' !== typeof type) {
            throw new TypeError('Socket.setSocketType: type must be string.');
        }
        if (options && 'object' !== typeof options) {
            throw new TypeError('Socket.setSocketType: options must be ' +
                                'object or undefined.');
        }
        this.socket = SocketFactory.get(this.node, type, options);

        if (!this.socket) {
            throw new Error('Socket.setSocketType: type not found: ' +
                            type + '.');
        }

        this.type = type;
        return this.socket;
    };

    /**
     * ### Socket.connect
     *
     * Calls the connect method on the actual socket object
     *
     * Uri is usually empty when using SocketDirect.
     *
     * @param {string} uri Optional. The uri to which to connect.
     * @param {object} options Optional. Configuration options for the socket.
     */
    Socket.prototype.connect = function(uri, options) {
        var humanReadableUri, that;

        if (this.isConnected()) {
            throw new Error('Socket.connect: socket is already connected. ' +
                            'Only one connection is allowed.');
        }
        if (this.connecting) {
            throw new Error('Socket.connecting: one connection attempt is ' +
                            'already in progress. Please try again later.');
        }
        if (uri && 'string' !== typeof uri) {
            throw new TypeError('Socket.connect: uri must be string or ' +
                                'undefined.');
        }
        if (options) {
            if ('object' !== typeof options) {
                throw new TypeError('Socket.connect: options must be ' +
                                    'object or undefined.');
            }
            this.userOptions = options;
        }

        humanReadableUri = uri || 'local server';

        if (!this.socket) {
            throw new Error('Socket.connet: cannot connet to ' +
                            humanReadableUri + ' . No socket defined.');
        }
        this.connecting = true;
        this.url = uri;
        this.node.info('connecting to ' + humanReadableUri + '.');
        this.node.emit('SOCKET_CONNECTING');
        this.socket.connect(this.url, this.userOptions);

        // Socket Direct might be already connected.
        if (this.connected) return;

        that = this;
        this.connectingTimeout = setTimeout(function() {
            that.node.warn('connection attempt to ' + humanReadableUri +
                           ' timed out. Disconnected.');
            that.socket.disconnect();
            that.connecting = false;
        }, this.connectingTimeoutMs);
    };

    /**
     * ### Socket.reconnect
     *
     * Calls the connect method with previous parameters
     *
     * @param {boolean} force Optional. Forces the process to continue
     *   even if a previous reconnection is in progress. Warning: can
     *   cause an infinite loop. Default: FALSE
     *
     * @see Socket.connect
     * @see Socket.disconnect
     */
    Socket.prototype.reconnect = function(force) {
        if (!this.url) {
            throw new Error('Socket.reconnect: cannot find previous uri.');
        }
        if (this.reconnecting && !force) {
            node.warn('Socket.reconnect: socket is already reconnecting. ' +
                     'Try with force parameter.');
            return;
        }
        this.reconnecting = true;
        if (this.connecting || this.isConnected()) this.disconnect();
        this.connect(this.url, this.userOptions);
        this.reconnecting = false;
    };

    /**
     * ### Socket.disconnect
     *
     * Calls the disconnect method on the actual socket object
     *
     * @param {boolean} force Forces to call the underlying
     *   `socket.disconnect` method even if socket appears not connected
     *   nor connecting at the moment.
     */
    Socket.prototype.disconnect = function(force) {
        if (!force && (!this.connecting && !this.isConnected())) {
            node.warn('Socket.disconnect: socket is not connected nor ' +
                      'connecting. Try with force parameter.');
            return;
        }
        this.socket.disconnect();
        this.connecting = false;
        this.connected = false;
    };

    /**
     * ### Socket.onConnect
     *
     * Handler for connections to the server
     *
     * @emit SOCKET_CONNECT
     */
    Socket.prototype.onConnect = function() {
        this.connected = true;
        this.connecting = false;
        if (this.connectingTimeout) clearTimeout(this.connectingTimeout);
        this.node.emit('SOCKET_CONNECT');

        // The testing framework expects this, do not remove.
        this.node.info('socket connected.');
    };

    /**
     * ### Socket.onDisconnect
     *
     * Handler for disconnections from the server
     *
     * Clears the player and monitor lists.
     *
     * @emit SOCKET_DISCONNECT
     */
    Socket.prototype.onDisconnect = function() {
        this.connected = false;
        this.connecting = false;
        this.node.emit('SOCKET_DISCONNECT');

        // Save the current stage of the game
        //this.node.session.store();

        // On re-connection will receive a new ones.
        this.node.game.pl.clear();
        this.node.game.ml.clear();

        // Restore original message handler.
        this.setMsgListener(this.onMessageHI);

        // Delete session.
        this.session = null;

        this.node.info('socket closed.');
    };

    /**
     * ### Socket.secureParse
     *
     * Parses a string representing a game msg into a game msg object
     *
     * Checks that the id of the session is correct.
     *
     * @param {string} msg The msg string as received by the socket.
     * @return {GameMsg|undefined} gameMsg The parsed msg, or
     *   undefined on error.
     */
    Socket.prototype.secureParse = function(msg) {
        var gameMsg;
        try {
            gameMsg = GameMsg.clone(JSON.parse(msg));
            this.node.info('R: ' + gameMsg);
        }
        catch(e) {
            return logSecureParseError.call(this, 'malformed msg received', e);
        }
        return gameMsg;
    };

    /**
     * ### Socket.validateIncomingMsg
     *
     * Checks whether an incoming message is valid.
     *
     * Checks that the id of the session is correct.
     *
     * @param {object} msg The msg object to check
     * @return {GameMsg|undefined} gameMsg The parsed msg, or
     *   undefined on error.
     */
    Socket.prototype.validateIncomingMsg = function(gameMsg) {
        if (this.session && gameMsg.session !== this.session) {
            return logSecureParseError.call(this, 'mismatched session in ' +
                                            'incoming message.');
        }
        return gameMsg;
    };

    /**
     * ### Socket.onMessageHI
     *
     * Initial handler for incoming messages from the server
     *
     * This handler will be replaced by the FULL handler, upon receiving
     * a HI message from the server.
     *
     * This method starts the game session, by creating a player object
     * with the data received by the server.
     *
     * @param {GameMsg} msg The game message received and parsed by a socket.
     *
     * @see Socket.validateIncomingMsg
     * @see Socket.startSession
     * @see Socket.onMessageFull
     * @see node.createPlayer
     */
    Socket.prototype.onMessageHI = function(msg) {
        msg = this.validateIncomingMsg(msg);
        if (!msg) return;

        // Parsing successful.
        if (msg.target === 'HI') {

            // Check if connection was authorized.
            if (msg.to === parent.constants.UNAUTH_PLAYER) {
                this.node.warn('connection was not authorized.');
                if (msg.text === 'redirect') {
                    if ('undefined' !== typeof window) {
                        window.location = msg.data;
                    }
                }
                else {
                    this.disconnect();
                }
                return;
            }

            // Replace itself: will change onMessage to onMessageFull.
            this.setMsgListener();

            // This will emit PLAYER_CREATED
            this.startSession(msg);
            // Functions listening to these events can be executed before HI.

            this.node.emit('NODEGAME_READY');
        }
    };

    /**
     * ### Socket.onMessageFull
     *
     * Full handler for incoming messages from the server
     *
     * All parsed messages are either emitted immediately or buffered,
     * if the game is not ready, and the message priority is low.x
     *
     * @param {GameMsg} msg The game message received and parsed by a socket.
     *
     * @see Socket.validateIncomingMsg
     * @see Socket.onMessage
     * @see Game.isReady
     */
    Socket.prototype.onMessageFull = function(msg) {
        msg = this.validateIncomingMsg(msg);
        if (!msg) return;

        // Message with high priority are executed immediately.
        if (msg.priority > 0 || this.node.game.isReady()) {
            this.node.emit(msg.toInEvent(), msg);
        }
        else {
            this.node.silly('B: ' + msg);
            this.buffer.push(msg);
        }
    };

    /**
     * ### Socket.onMessage
     *
     * Handler for incoming messages from the server
     *
     * @see Socket.onMessageHI
     * @see Socket.onMessageFull
     */
    Socket.prototype.onMessage = Socket.prototype.onMessageHI;

    /**
     * ### Socket.setMsgListener
     *
     * Sets the onMessage listener
     *
     * @param msgHandler {function} Optional. Callback function which is
     *  called for every message in the buffer instead of the messages
     *  being emitted.
     *  Default: Socket.onMessageFull
     *
     * @see this.node.emit
     * @see Socket.clearBuffer
     */
    Socket.prototype.setMsgListener = function(msgHandler) {
        if (msgHandler && 'function' !== typeof msgHandler) {
            throw new TypeError('Socket.setMsgListener: msgHandler must be a ' +
                                'function or undefined. Found: ' + msgHandler);
        }

        this.onMessage = msgHandler || this.onMessageFull;
    };

    /**
     * ### Socket.shouldClearBuffer
     *
     * Returns TRUE, if buffered messages can be emitted
     *
     * @see node.emit
     * @see Socket.clearBuffer
     * @see Game.isReady
     */
    Socket.prototype.shouldClearBuffer = function() {
        return this.node.game.isReady();
    };

    /**
     * ### Socket.clearBuffer
     *
     * Emits and removes all the events in the message buffer
     *
     * @param msgHandler {function} Optional. Callback function which is
     *  called for every message in the buffer instead of the messages
     *  being emitted.
     *  Default: Emit every buffered message.
     *
     * @see node.emit
     * @see Socket.shouldClearBuffer
     */
    Socket.prototype.clearBuffer = function(msgHandler) {
        var nelem, msg, i;
        var funcCtx, func;

        if (msgHandler) {
            funcCtx = this.node.game;
            func = msgHandler;
        }
        else {
            funcCtx = this.node.events;
            func = this.node.events.emit;
        }

        nelem = this.buffer.length;
        for (i = 0; i < nelem; i++) {
            // Modify the buffer at every iteration, so that if an error
            // occurs, already emitted messages are out of the way.
            msg = this.buffer.shift();
            if (msg) {
                func.call(funcCtx, msg.toInEvent(), msg);
                this.node.silly('D: ' + msg);
            }
        }
    };

    /**
     * ### Socket.eraseBuffer
     *
     * Removes all messages currently in the buffer
     *
     * This operation is not reversible
     *
     * @see Socket.clearBuffer
     */
    Socket.prototype.eraseBuffer = function() {
        this.buffer = [];
    };

    /**
     * ### Socket.startSession
     *
     * Initializes a nodeGame session
     *
     * Creates a the player and saves it in node.player, and
     * stores the session ids in the session object.
     *
     * If a game window reference is found, sets the `uriChannel` variable.
     *
     * @param {GameMsg} msg A game-msg
     * @param {boolean} force If TRUE, a new session will be created even
     *    if an existing one is found.
     *
     * @see node.createPlayer
     * @see Socket.registerServer
     * @see GameWindow.setUriChannel
     */
    Socket.prototype.startSession = function(msg, force) {
        if (this.session && !force) {
            throw new Error('Socket.startSession: session already existing. ' +
                            'Use force parameter to overwrite it.');
        }

        // We need to first set the session,
        // and then eventually stop an ongoing game.
        this.session = msg.session;
        if (this.node.game.isStoppable()) this.node.game.stop();

        // Channel name and create player.
        this.channelName = msg.data.channel.name;
        this.node.createPlayer(msg.data.player);

        // Set anti-spoofing as requested by server.
        if (msg.data.antiSpoofing) {
            if (this.socket.enableAntiSpoofing) {
                this.antiSpoofing = true;
                this.socket.enableAntiSpoofing(true);
            }
            else {
                this.node.log('Socket.startSession: server requested anti-' +
                              'spoofing, but socket does not support it.');
            }
        }

        // Notify GameWindow (if existing, and if not default channel).
        if (this.node.window && !msg.data.channel.isDefault) {
            this.node.window.setUriChannel(this.channelName);
        }
    };

    /**
     * ### Socket.isConnected
     *
     * Returns TRUE if socket connection is ready.
     */
    Socket.prototype.isConnected = function() {
        return this.socket && this.socket.isConnected();
    };

    /**
     * ### Socket.send
     *
     * Pushes a message into the socket
     *
     * The msg is actually received by the client itself as well.
     *
     * @param {GameMsg} msg The game message to send
     *
     * @return {boolean} TRUE on success
     *
     * @see GameMsg
     *
     * TODO: when trying to send a message and the socket is not connected
     * the message is just discarded. Outgoing messages could be buffered
     * and sent out whenever the connection is available again.
     */
    Socket.prototype.send = function(msg) {
        var outEvent;

        if (!msg.from || msg.from === this.node.UNDEFINED_PLAYER) {
            this.node.err('Socket.send: cannot send message. ' +
                          'Player undefined. Message discarded.');
            return false;
        }

        if (!this.isConnected()) {
            this.node.err('Socket.send: cannot send message. ' +
                          'No open socket. Message discarded.');

            // TODO: test this
            // this.outBuffer.push(msg);
            return false;
        }

        // TODO: test this
        // if (!this.node.game.isReady()) {
        //     this.outBuffer.push(msg);
        //     return false;
        // }

        // Emit out event, if required.
        if (this.emitOutMsg) {
            outEvent = msg.toOutEvent();
            this.node.events.ee.game.emit(outEvent, msg);
            this.node.events.ee.stage.emit(outEvent, msg);
            this.node.events.ee.step.emit(outEvent, msg);
        }

        this.socket.send(msg);
        this.node.info('S: ' + msg);

        // TODO: check this.
        // Experimental code.
        if (this.journalOn) {
            // Only Game messages are stored.
            if (this.node.game.isReady()) this.journal.insert(msg);
        }
        // End experimental code.

        return true;
    };

    // Helper methods.

    function logSecureParseError(text, e) {
        var error;
        text = text || 'generic error while parsing a game message.';
        error = (e) ? text + ": " + e : text;
        this.node.err('Socket.secureParse: ' + error);
        return false;
    }

})(
    'undefined' != typeof node ? node : module.exports,
    'undefined' != typeof node ? node : module.parent.exports
);

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\HttpKernel\Profiler;

@trigger_error('The '.__NAMESPACE__.'\MemcachedProfilerStorage class is deprecated since Symfony 2.8 and will be removed in 3.0. Use FileProfilerStorage instead.', E_USER_DEPRECATED);

/**
 * Memcached Profiler Storage.
 *
 * @author Andrej Hudec <pulzarraider@gmail.com>
 *
 * @deprecated Deprecated since Symfony 2.8, to be removed in Symfony 3.0.
 *             Use {@link FileProfilerStorage} instead.
 */
class MemcachedProfilerStorage extends BaseMemcacheProfilerStorage
{
    /**
     * @var \Memcached
     */
    private $memcached;

    /**
     * Internal convenience method that returns the instance of the Memcached.
     *
     * @return \Memcached
     *
     * @throws \RuntimeException
     */
    protected function getMemcached()
    {
        if (null === $this->memcached) {
            if (!preg_match('#^memcached://(?(?=\[.*\])\[(.*)\]|(.*)):(.*)$#', $this->dsn, $matches)) {
                throw new \RuntimeException(sprintf('Please check your configuration. You are trying to use Memcached with an invalid dsn "%s". The expected format is "memcached://[host]:port".', $this->dsn));
            }

            $host = $matches[1] ?: $matches[2];
            $port = $matches[3];

            $memcached = new \Memcached();

            // disable compression to allow appending
            $memcached->setOption(\Memcached::OPT_COMPRESSION, false);

            $memcached->addServer($host, $port);

            $this->memcached = $memcached;
        }

        return $this->memcached;
    }

    /**
     * Set instance of the Memcached.
     *
     * @param \Memcached $memcached
     */
    public function setMemcached($memcached)
    {
        $this->memcached = $memcached;
    }

    /**
     * {@inheritdoc}
     */
    protected function getValue($key)
    {
        return $this->getMemcached()->get($key);
    }

    /**
     * {@inheritdoc}
     */
    protected function setValue($key, $value, $expiration = 0)
    {
        return $this->getMemcached()->set($key, $value, time() + $expiration);
    }

    /**
     * {@inheritdoc}
     */
    protected function delete($key)
    {
        return $this->getMemcached()->delete($key);
    }

    /**
     * {@inheritdoc}
     */
    protected function appendValue($key, $value, $expiration = 0)
    {
        $memcached = $this->getMemcached();

        if (!$result = $memcached->append($key, $value)) {
            return $memcached->set($key, $value, $expiration);
        }

        return $result;
    }
}


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2022 Ryo Suzuki
//	Copyright (c) 2016-2022 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3D/EngineOptions.hpp>
# include <Siv3D/ConstantBuffer/Null/ConstantBufferDetail_Null.hpp>
# include <Siv3D/ConstantBuffer/GL4/ConstantBufferDetail_GL4.hpp>
# include <Siv3D/ConstantBuffer/GLES3/ConstantBufferDetail_GLES3.hpp>

namespace s3d
{
	IConstantBufferDetail* IConstantBufferDetail::Create(const size_t size)
	{
		if (g_engineOptions.renderer == EngineOption::Renderer::Headless)
		{
			return new ConstantBufferDetail_Null(size);
		}
		else if (g_engineOptions.renderer == EngineOption::Renderer::WebGL2)
		{
			return new ConstantBufferDetail_GLES3(size);
		}
		else if (g_engineOptions.renderer == EngineOption::Renderer::PlatformDefault
			|| g_engineOptions.renderer == EngineOption::Renderer::OpenGL)
		{
			return new ConstantBufferDetail_GL4(size);
		}
		else
		{
			return new ConstantBufferDetail_Null(size);
		}
	}
}


text:
package ru.job4j.distributor.products;

import java.time.LocalDate;
import java.util.Objects;

/**
 * Food.
 * Abstract class for all products.
 * @author Ivan Belyaev
 * @since 28.12.2019
 * @version 2.0
 */
public abstract class Food {
    /** The product's name. */
    private final String name;
    /** Expiry date. */
    private final LocalDate expiryDate;
    /** Production date. */
    private final LocalDate createDate;
    /** Price. */
    private double price;
    /** Discount. */
    private double discount;

    /**
     * Constructor for all kinds of products.
     * @param name the product's name.
     * @param expiryDate expiry date.
     * @param createDate production date.
     * @param price price.
     * @param discount discount.
     */
    public Food(String name, LocalDate expiryDate, LocalDate createDate, double price, double discount) {
        this.name = name;
        this.expiryDate = expiryDate;
        this.createDate = createDate;
        this.price = price;
        this.discount = discount;
    }

    /**
     * The method sets discount.
     * @param discount discount.
     */
    public void setDiscount(double discount) {
        this.discount = discount;
    }

    /**
     * The method returns the product's name.
     * @return the product's name.
     */
    public String getName() {
        return name;
    }

    /**
     * The method returns expiry date.
     * @return expiry date.
     */
    public LocalDate getExpiryDate() {
        return expiryDate;
    }

    /**
     * The method returns production date.
     * @return production date.
     */
    public LocalDate getCreateDate() {
        return createDate;
    }

    /**
     * The method returns price.
     * @return price.
     */
    public double getPrice() {
        return price;
    }

    /**
     * The method returns discount.
     * @return discount.
     */
    public double getDiscount() {
        return discount;
    }

    /**
     * The method checks objects for equality.
     * @param o the object with which to compare this object.
     * @return true if the objects are the same otherwise returns false.
     */
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Food food = (Food) o;
        return Double.compare(food.price, price) == 0
                && Double.compare(food.discount, discount) == 0
                && name.equals(food.name)
                && expiryDate.equals(food.expiryDate)
                && createDate.equals(food.createDate);
    }

    /**
     * The method returns a hash code for this object.
     * @return returns a hash code for this object.
     */
    @Override
    public int hashCode() {
        return Objects.hash(name, expiryDate, createDate, price, discount);
    }
}


text:
Meteor.startup(function () {

  // loop over custom prefixes
  Telescope.config.customPrefixes.forEach(function (prefix) {

    // for each prefix, loop over all templates to find any replacements
    Template.forEach(function (template) {

      var templateName = template.viewName.replace("Template.", "");

      // if current template name starts with the prefix, find original template and replace it
      if (templateName.slice(0,prefix.length) === prefix) {
        var oldTemplate = templateName.slice(prefix.length);
        template.replaces(oldTemplate);
      }

    });

  });
});


text:
import React, { Component } from "react";
import { Redirect, Route } from "react-router-dom";
import Home from '../components/Home';
import About from '../components/About';
import Projects from '../components/Projects';
import Header from '../components/Header';

class MyRouter extends Component {

    render() {
        return (
            <div className="primary-layout container">
                <header className="primary-layout__header">
                    <Header/>
                </header>
                <main>
                    <Route path="/" exact
                        render={() => <Home displayName="home"/>}
                    />
                    <Route path="/home" exact
                        render={() => <Home displayName="home"/>}
                    />
                    <Route path="/about"
                        render={() => <About displayName="about"/>}
                    />
                    <Route path="/projects"
                        render={() => <Projects displayName="projects"/>}
                    />
                </main>
            </div>
        )
    }
}

export default MyRouter


text:
package com.intellij.gwt.i18n;

import com.intellij.lang.properties.IProperty;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.search.searches.DefinitionsScopedSearch;
import com.intellij.util.Processor;
import com.intellij.util.QueryExecutor;

import javax.annotation.Nonnull;

/**
 * @author peter
 */
public class PropertiesSearcher implements QueryExecutor<PsiElement, DefinitionsScopedSearch.SearchParameters>
{
	@Override
	public boolean execute(@Nonnull DefinitionsScopedSearch.SearchParameters queryParameters, @Nonnull Processor<? super PsiElement> consumer)
	{
		final PsiElement sourceElement = queryParameters.getElement();
		if(sourceElement instanceof PsiMethod)
		{
			final IProperty[] properties = ApplicationManager.getApplication().runReadAction(new Computable<IProperty[]>()
			{
				@Override
				public IProperty[] compute()
				{
					return GwtI18nManager.getInstance(sourceElement.getProject()).getProperties((PsiMethod) sourceElement);
				}
			});
			for(IProperty property : properties)
			{
				if(!consumer.process(property.getPsiElement()))
				{
					return false;
				}
			}
		}
		else if(sourceElement instanceof PsiClass)
		{
			final PropertiesFile[] files = ApplicationManager.getApplication().runReadAction(new Computable<PropertiesFile[]>()
			{
				@Override
				public PropertiesFile[] compute()
				{
					return GwtI18nManager.getInstance(sourceElement.getProject()).getPropertiesFiles((PsiClass) sourceElement);
				}
			});
			for(PropertiesFile file : files)
			{
				if(!consumer.process(file.getContainingFile()))
				{
					return false;
				}
			}
		}
		return true;
	}
}


text:
    <meta charset="UTF-8">
    <title>MTFontMathTable.stackDisplayStyleGapMin - </title>
    <link rel="stylesheet" href="../../style.css">

com.agog.mathdisplay.render / MTFontMathTable / stackDisplayStyleGapMin

stackDisplayStyleGapMin

val stackDisplayStyleGapMin: Float


text:
package org.jetbrains.plugins.scala
package lang
package psi
package impl
package expr

import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.scala.lang.psi.api.ScalaElementVisitor
import org.jetbrains.plugins.scala.lang.psi.api.expr._
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.templates.ScTemplateBody
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScTemplateDefinition, ScTypeDefinition}
import org.jetbrains.plugins.scala.lang.psi.types._
import org.jetbrains.plugins.scala.lang.psi.types.result.{Failure, Success, TypeResult, TypingContext}

/**
 * @author Alexander Podkhalyuzin
 * Date: 06.03.2008
 */

class ScThisReferenceImpl(node: ASTNode) extends ScalaPsiElementImpl(node) with ScThisReference {
  override def toString: String = "ThisReference"

  protected override def innerType(ctx: TypingContext): TypeResult[ScType] = refTemplate match {
    case Some(td) => ScThisReferenceImpl.getThisTypeForTypeDefinition(td, this)
    case _ => Failure("Cannot infer type", Some(this))
  }

  def refTemplate: Option[ScTemplateDefinition] = reference match {
    case Some(ref) => ref.resolve match {
      case td: ScTypeDefinition if PsiTreeUtil.isContextAncestor(td, ref, false) => Some(td)
      case _ => None
    }
    case None => {
      val encl = PsiTreeUtil.getContextOfType(this, false, classOf[ScTemplateBody])
      if (encl != null) Some(PsiTreeUtil.getContextOfType(encl, false, classOf[ScTemplateDefinition])) else None
    }
  }

  override def accept(visitor: ScalaElementVisitor) {
    visitor.visitThisReference(this)
  }

  override def accept(visitor: PsiElementVisitor) {
    visitor match {
      case visitor: ScalaElementVisitor => visitor.visitThisReference(this)
      case _ => super.accept(visitor)
    }
  }
}

object ScThisReferenceImpl {
  def getThisTypeForTypeDefinition(td: ScTemplateDefinition, expr: ScExpression): TypeResult[ScType] = {
    lazy val selfTypeOfClass = td.getTypeWithProjections(TypingContext.empty, thisProjections = true).map(tp =>
      td.selfType match {
        case Some(selfType) => Bounds.glb(tp, selfType)
        case _ => tp
      }
    )

    // SLS 6.5:  If the expression's expected type is a stable type,
    // or C .this occurs as the prefix of a selection, its type is C.this.type,
    // otherwise it is the self type of class C .
    expr.getContext match {
      case r: ScReferenceExpression if r.qualifier.exists(_ == expr) =>
        Success(ScThisType(td), Some(expr))
      case _ => expr.expectedType() match {
        case Some(t) if t.isStable =>
          Success(ScThisType(td), Some(expr))
        case _ =>
          Success(selfTypeOfClass.getOrElse (return Failure("No clazz type found", Some(expr))), Some(expr))
      }
    }
  }
}


text:
/*
 * Class for presentations
 */
var Presentation = Base.extend({
	recording:null,
	outer_container:null,
	inner_container:null,
	presentationId:null,
	slides:null,
	slidesData:null, //a list of slides in json format
	selectedSlide:null,
	synchronised:true,
	autoScroll:true,
	scrollOffset:2,
	editingEnabled:false,

	constructor:function(recording, outer_container, inner_container)
	{
		this.recording = recording;
		this.outer_container=outer_container;
		this.inner_container=inner_container;
	},
	initPresentation:function()
	{

		//If can edit, init the add, edit and delete buttons
		if(recording.canEdit === "true")
		{
			$("#slide_st").mask("?99:99:99");
			$("#slide_et").mask("?99:99:99");
			$("#slide_st_time").click(function(){
				var currentPosition = multimedia.getPosition();
				//console.log("curpo:"+currentPosition);
				$("#slide_st").val(milisecToString(currentPosition));
			});
			$("#slide_st_add").click(function(){
				var oldTime = stringToMilisec($("#slide_st").val());
				var newTime = oldTime+1000;
				$("#slide_st").val(milisecToString(newTime));
			});
			$("#slide_st_remove").click(function(){
				var oldTime = stringToMilisec($("#slide_st").val());
				var newTime = oldTime-1000>0?oldTime-1000:0;
				$("#slide_st").val(milisecToString(newTime));
			});
			$("#slide_et_time").click(function(){
				var currentPosition = multimedia.getPosition();
				$("#slide_et").val(milisecToString(currentPosition));
			});
			$("#slide_et_add").click(function(){
				var oldTime = stringToMilisec($("#slide_et").val());
				var newTime = oldTime+1000;
				$("#slide_et").val(milisecToString(newTime));
			});
			$("#slide_et_remove").click(function(){
				var oldTime = stringToMilisec($("#slide_et").val());
				var newTime = oldTime-1000>0?oldTime-1000:0;
				$("#slide_et").val(milisecToString(newTime));
			});
			$("#presentation_cancel").click(function(){
				$("#presentation_edit_form").resetForm();
				$("#presentation_edit_div").hide(400);
			});
			//Yunjia: Can't use combobox because the dropdownlist keep on appearing behind the dialog
			//$("#presentation_edit_dialog select").combobox();
			$("#slides_add_btn").click(function(){
				var newTime = multimedia.getPosition();
				presentation.fillPresentationForm(milisecToString(newTime),"","","","","");
				$("#presentation_edit_div").show(400);
				return;
			});

			$("#slides_edit_btn").click(function(){
				//Add slide_id first
				if(presentation.selectedSlide != null)
				{
					$("#presentation_edit_div").show(400);
					var slide_st = milisecToString(presentation.selectedSlide.attr("date-time-st"));
					var slide_index = parseInt(presentation.selectedSlide.attr("index"))+1;
					var slide_et;
					if(presentation.selectedSlide.attr("date-time-et") === "")
					{
						var next_slide = $("#image_container_div img[index='"+slide_index+"']");
						if(next_slide == null)
						{
							slide_et = slide_st;
						}
						else
						{
							slide_et =  milisecToString(next_slide.attr("date-time-st"));
						}
					}
					else
					{
						slide_et = milisecToString(presentation.selectedSlide.attr("date-time-et"));
					}

					var slide_url = presentation.selectedSlide.attr("src");
					var slide_id = presentation.selectedSlide.attr("slide_id");
					var old_index = slide_index;
					presentation.fillPresentationForm(slide_st,slide_et,slide_index,slide_url,slide_id,old_index);
					return;
				}
				else
				{
					alert("Please select a slide.");
					return;
				}
			});

			$("#slides_delete_btn").click(function(){
				if(presentation.selectedSlide == null)
				{
					alert("Please select a slide.");
					return;
				}
				else
				{
					var r = confirm("Are you sure?");
					if(r==true)
					{
						var deleteSlideURL = g.createLink({controller:'recording', action:'deleteSlideAjax'});
						$.ajax({
							type:"POST",
							url:deleteSlideURL,
							data:{multimedia_id:recording.id,slide_index:presentation.selectedSlide.attr("index"),presentation_id:presentation.presentationId},
							datatype:"text",
							success:function(data)
							{
								if(data.success) //status == 200
								{
									//console.log("success"+respJson.success.description);
									presentation.showMsg(data.success.description,null);
								}
								else if(data.error)
								{
									//console.log("not success");
									presentation.showMsg(data.error.description,"error");
								}
								presentation.refresh();
							},
							error:function(jqXHR,textStatus,errorThrown)
							{
								var resp =$.parseJSON(jqXHR.responseText);
								presentation.showMsg(resp.error.description,"error");
								return;
							}
						});
					}
					else
						return;
				}
			});

			$("#presentation_edit_form").submit(function(){
				var url;
				var params;
				if($("#slide_id").val() != null && $("#slide_id").val() !== undefined && $.trim($("#slide_id").val()).length>0) //if slide_id is not null, it means slide updates
				{
					url = g.createLink({controller:"recording",action:"updateSlideAjax",params:{multimedia_id:recording.id,presentation_id:presentation.presentationId}});
				}
				else
				{
					if(presentation.presentationId == null)
						url = g.createLink({controller:"recording",action:"saveSlideAjax",params:{multimedia_id:recording.id}});
					else
						url = g.createLink({controller:"recording",action:"saveSlideAjax",params:{multimedia_id:recording.id,presentation_id:presentation.presentationId}});
					//;
				}

				$(this).ajaxSubmit({
					url:url,
					//resetForm:true,
					type:'post',
					dataType:'json',
					//data:params,
					success:function(data, statusText, xhr, $form)
					{
						if(data.success) //status == 200
						{
							presentation.showMsg(respJson.success.description,null);
							presentation.resetPresentationForm();
							presentation.refresh();
						}
						else if(data.error)
						{
							presentation.showMsg(data.error.description);
						}

					},
					error:function(jqXHR,textStatus,errorThrown)
					{
						var resp =$.parseJSON(jqXHR.responseText);
						presentation.showMsg(resp.error.description,"error");
						return;
					}
				});

				return false;
			});

			$("#presentation_edit_form").validate(
			{
				rules: {
				    slides_st: {
					    required:true
				    },
				    slides_et:{
						required:true
					},
					slide_index:{
						required:true,
					},
					slide_url:{
						required:true,
						maxlength:255,
						url:true
					}
				 },
				highlight: function(label) {
					$(label).closest('.control-group').addClass('error');
				},
			});
		}
	},
	resetPresentationForm:function()
	{
		$('#presentation_edit_form').resetForm();
	},
	fillPresentationForm:function(slide_st,slide_et,slide_index,slide_url,slide_id, old_index)
	{
		$("#slide_st").val(slide_st);
		$("#slide_et").val(slide_et);
		$("#slide_index").val(slide_index);
		$("#slide_url").val(slide_url);
		$("#old_index").val(old_index);
		$("#slide_id").val(slide_id);
	},
	showMsg:function(msg,type)
	{
		var msg_div = $("#slides_msg_div");
		if(type == "error")
		{
			msg_div.html("
<button class='close' data-dismiss='alert'>x</button>"+msg+"
");
		}
		else
		{
			msg_div.html("
<button class='close' data-dismiss='alert'>x</button>"+msg+"
");
		}
	},
	sync:function(currentPosition)
	{
		//currentSlide is a jquery object
		//console.log("sync slide");
		if(this.slides != null && this.slides.length>0)
		{
			var currentSlide = this.getSlide(currentPosition)
			//console.log("selectedSlide:"+this.selectedSlide);
			if(currentSlide != this.selectedSlide)
			{
				this.setSlideSelected(currentSlide);
			}
		}
	},
	getSlide:function(currentPosition)
	{
		var cs = null; //current slide
		for(var i=0;i<this.slides.length;i++)
		{
			var st= parseInt($(this.slides[i]).attr("date-time-st"));//st is slide start time
			if(st>=currentPosition)
			{
				break;
			}
			else
				cs= $(this.slides[i]);
		}
		//console.log("sl date-time-st:"+cs?cs.attr("date-time-st"):"nulll");
		return cs;
	},
	setSlideSelected:function(currentSlide)
	{
		if(currentSlide != null)
		{
			if(this.selectedSlide != null)
				this.selectedSlide.removeClass("slide_selected");
			this.selectedSlide = currentSlide;
			currentSlide.addClass("slide_selected");
			if(this.autoScroll)
			{
				var index = parseInt(currentSlide.attr("index"));
				var i = index-this.scrollOffset>0?index-this.scrollOffset:index;
			}
		}
	},
	clickSlide:function(currentSlide)
	{
		this.setSlideSelected(currentSlide);
		multimedia.setPosition(parseInt(currentSlide.attr("date-time-st")));
	},
	initEditing:function()
	{
		var index_length = 1;
		if(presentation.slides != null)
		{
			index_length = presentation.slides.length+1;
		}

		$("#slide_index").empty();
		//console.log(index_length);
		for(var i=1;i<=index_length;i++)
		{
			var opt = $("<option/>").val(i).text(i);
			$("#slide_index").append(opt);
		}
	},
	showMsg:function(msg,type)
	{
		var msg_div = $("#slides_msg_div");
		if(type == "error")
		{
			msg_div.html("
<button class='close' data-dismiss='alert'>x</button>"+msg+"
");
		}
		else
		{
			msg_div.html("
<button class='close' data-dismiss='alert'>x</button>"+msg+"
");
		}
	},
	refresh:function()
	{
		var image_container_div  = this.inner_container;
		var multimediaId = this.recording.id;
		image_container_div.empty();
		var getPresentationsURL = g.createLink({controller:'recording', action:'getPresentationsAjax'});
		//var slides_div = $("
").attr("id","slides_div").appendTo("body");
		var slides_div = this.outer_container;
		var image_container_ul=$("
").attr('id',"image_container_ul").addClass("thumbnails").appendTo(image_container_div);
		$.ajax({
			   type: "GET",
			   url: getPresentationsURL,
			   data:{multimediaId:multimediaId},
			   dataType: "json",
			   beforeSend:function(jqXHR, settings)
			   {
				   $("#slides_loading_div").show();
			   },
			   success:function(data)
			   {
				   if(!data || !data[0] || data[0].slides.length==0)
				   {
					   image_container_div.html("No Presentation Slides");
					   $("#slides_count_span").text("(0)");
					   if(recording.canEdit === "true")
					   {
						   presentation.initEditing();
					   }
					   return;
				   }
				   presentation.presentationId = data[0].id;
				   $("#slides_count_span").text("("+data[0].slides.length+")");
				   $.each(data[0].slides, function(i,slide){
					   var single_slide_li = $("
").addClass("span-thumbnail");
					   var slide_a = $("
").addClass("thumbnail");
					   //var slide_time_span = $("").text(milisecToString(slide.start)).appendTo(slide_div);
					   var slide_thumb_img = $("",{
						   src: slide.url,
						   alt: slide.start,
						   id:"slide_"+slide.id,
						   //height:165,
						   //width:220,
						   mouseover:function(){$(this).addClass("slide_hover");},
						   mouseout:function(){$(this).removeClass("slide_hover");},
						   click:function()
						   {
							   presentation.clickSlide($(this));
						   }
					   }).attr("date-time-st",slide.start).attr("date-time-et",slide.end?slide.end:"").attr("index",i+1).attr("slide_id",slide.id)
					   .addClass("slide_thumb_image");//date-time-et is not used
					   slide_thumb_img.bind("dblclick",function(){

						});
					   slide_a.append(slide_thumb_img);
					   //single_slide_li.append(slide_thumb_img);
					   single_slide_li.append(slide_a);
					   image_container_ul.append(single_slide_li);
					   //Microdata: add imageObject
					   mdHelper.setMediaObject(single_slide_li,recording.isVideo == 'true'?true:false);
					   mdHelper.setItemid(single_slide_li,attachFragmentToURI(resourceBaseURI+recording.id,getFragmentString(slide.start,slide.end)));
					   mdHelper.setItemprop(slide_thumb_img,"image");
					   mdHelper.createItem(slide_thumb_img,"http://schema.org/ImageObject");
				   });

				   presentation.slides = $(".slide_thumb_image");

				   //###########################init the index in edit form############################
				   if(recording.canEdit === "true")
				   {
					   presentation.initEditing();
				   }
			   },
			   complete:function(jqXHR, textStatus)
			   {
				   $("#slides_loading_div").hide();
			   }
		});
	}
});


text:
<?php

class Hackathon_AsyncIndex_Model_Observer
{
    /**
     * @var bool
     */
    protected $_shouldLoadUnprocessedEventCount = false;

    /**
     * @see event adminhtml_block_html_before
     * @param Varien_Event_Observer $observer
     * @return Hackathon_AsyncIndex_Model_Observer
     */
    public function extendIndexProcessGrid(Varien_Event_Observer $observer)
    {
        /** @var Mage_Adminhtml_Block_Template $block */
        $block = $observer->getBlock();
        if ($block instanceof Mage_Index_Block_Adminhtml_Process_Grid) {
            $this->_addEventCountColumnTo($block);
            $this->_changeActions($block);
        }
        return $this;
    }
    /**
     * Add count of indexed data to grid
     *
     * @param Mage_Index_Block_Adminhtml_Process_Grid $grid
     * @return Hackathon_AsyncIndex_Model_Observer
     */
    protected function _addEventCountColumnTo(Mage_Index_Block_Adminhtml_Process_Grid $grid)
    {
        $grid->addColumnAfter('event_count', array(
                'header'   => Mage::helper('index')->__('Event Count'),
                'width'    => '80',
                'index'    => 'event_count',
                'sortable' => false
            ), 'ended_at'
        );
        return $this;
    }
    /**
     * Change action column to dropdown with additional actions
     * - schedule reindex
     * - schedule partial reindex
     *
     * @param Mage_Index_Block_Adminhtml_Process_Grid $grid
     * @return Hackathon_AsyncIndex_Model_Observer
     */
    protected function _changeActions(Mage_Index_Block_Adminhtml_Process_Grid $grid)
    {
        $grid->getColumn('action')->setActions(array(
                array(
                    'caption' => Mage::helper('index')->__('Reindex Data'),
                    'url'     => array('base' => '*/*/reindexProcess'),
                    'field'   => 'process'
                ),
                array(
                    'caption' => Mage::helper('index')->__('Schedule Reindex'),
                    'url'     => array('base' => 'asyncindex/asyncindex/index'),
                    'params'  => array('_current' => true, '_secure' => false),
                    'field'   => 'process'
                ),
                array(
                    'caption' => Mage::helper('index')->__('Schedule partial index'),
                    'url'     => array('base' => 'asyncindex/asyncindex/schedulePartial'),
                    'params'  => array('_current' => true, '_secure' => false),
                    'field'   => 'process'
                ),
            ));
        return $this;
    }
    /**
     * Set flag to add unprocessed event count after load.
     * Uses core_block_abstract_to_html_before because this is the only event fired before
     * grid is prepared and collection loaded. Cannot use collection flag because collection
     * is not instantiated yet.
     *
     * @see event core_block_abstract_to_html_before
     * @param Varien_Event_Observer $observer
     * @return Hackathon_AsyncIndex_Model_Observer
     */
    public function prepareCollectionForGrid(Varien_Event_Observer $observer)
    {
        /* @var $block Mage_Core_Block_Abstract $block */
        $block = $observer->getBlock();
        if ($block instanceof Mage_Index_Block_Adminhtml_Process_Grid) {
            $this->_shouldLoadUnprocessedEventCount = true;
        }
        return $this;
    }
    /**
     * Add event count to process collection if flag has been set
     *
     * @see event process_collection_load_after
     * @param Varien_Event_Observer $observer
     * @return Hackathon_AsyncIndex_Model_Observer
     */
    public function addEventCountToCollection(Varien_Event_Observer $observer)
    {
        /* @var $processCollection Mage_Index_Model_Resource_Process_Collection */
        $processCollection = $observer->getProcessCollection();
        if ($this->_shouldLoadUnprocessedEventCount) {
            /* @var $process Mage_Index_Model_Process */
            foreach ($processCollection as $process) {
                $process->setEventCount($process->getUnprocessedEventsCollection()->count());
            }
        }

        return $this;
    }

    /**
     * Executes manually scheduled reindex
     */
    public function schedule_index()
    {
        // Only one job should be running.
        $scheduledJob = Mage::getModel('cron/schedule')->getCollection()
            ->addFieldToFilter('job_code', 'hackathon_asyncindex_cron')
            ->addFieldToFilter('status', 'running')
            ->getFirstItem();

        $message = json_decode($scheduledJob->getMessages(), true);
        if (isset($message['indexerCode'])) {
            $indexer = $message['indexerCode'];
            /** @var Hackathon_AsyncIndex_Model_Manager $indexManager */
            $indexManager = Mage::getModel('hackathon_asyncindex/manager');

            $indexProcess = Mage::getSingleton('index/indexer')->getProcessByCode($indexer);

            if ($indexProcess) {
                if ($message['fullReindex'] === true) {
                    $indexProcess->reindexEverything();
                } else {
                    $indexManager->executePartialIndex($indexProcess);
                }
            }
        }
    }

    /**
     * Indexes a specific number of events
     *
     * @throws Exception
     */
    public function unprocessed_events_index()
    {

        if ( !Mage::getStoreConfig('system/asyncindex/auto_index') ) {
            return null;
        }

        /** @var $resourceModel Mage_Index_Model_Resource_Process */
        $resourceModel = Mage::getResourceSingleton('index/process');

        $resourceModel->beginTransaction();

        try
        {
            $pCollection = Mage::getSingleton('index/indexer')->getProcessesCollection();
            /** @var Mage_Index_Model_Process $process */
            foreach ($pCollection as $process) {
                $process->setMode(Mage_Index_Model_Process::MODE_SCHEDULE);
                $eventLimit            = (int)Mage::getStoreConfig('system/asyncindex/event_limit');
                $unprocessedColl = $process->getUnprocessedEventsCollection()->setPageSize($eventLimit);

                /** @var Mage_Index_Model_Event $unprocessedEvent */
                foreach ($unprocessedColl as $unprocessedEvent) {
                    $process->processEvent($unprocessedEvent);
                    $unprocessedEvent->save();
                }
                if ( count(Mage::getResourceSingleton('index/event')->getUnprocessedEvents($process) ) === 0) {
                    $process->changeStatus(Mage_Index_Model_Process::STATUS_PENDING);
                }
            }
            $resourceModel->commit();
        }
        catch (Exception $e)
        {
            $resourceModel->rollBack();
            throw $e;
        }
    }

    public function runIndex() {

        if ( !Mage::getStoreConfig('system/asyncindex/auto_index') ) {
            return null;
        }

        $blacklistCfg = Mage::getStoreConfig('system/asyncindex/blacklist_indexes');
        $blacklist = explode(',', $blacklistCfg);

        $partialIndex = Mage::getStoreConfig('system/asyncindex/partial_cron_index');

        if($partialIndex) {

            $indexManager = Mage::getModel('hackathon_asyncindex/manager');
            $pCollection = Mage::getSingleton('index/indexer')->getProcessesCollection();

            /** @var Mage_Index_Model_Process $process */
            foreach ($pCollection as $process) {
                if ( in_array($process->getIndexerCode(), $blacklist) )
                {
                  continue;
                }
                $indexManager->executePartialIndex($process);
            }

        } else {

            // run the normal indexer method
            $this->unprocessed_events_index();

        }

    }
}


text:
namespace TraktApiSharp.Objects.Post.Syncs.Collection.Json.Factories
{
    using Objects.Json;
    using System;
    using Writer;

    internal class SyncCollectionPostJsonIOFactory : IJsonIOFactory<ITraktSyncCollectionPost>
    {
        public IObjectJsonReader<ITraktSyncCollectionPost> CreateObjectReader()
            => throw new NotSupportedException($"A object json reader for {nameof(ITraktSyncCollectionPost)} is not supported.");

        public IArrayJsonReader<ITraktSyncCollectionPost> CreateArrayReader()
            => throw new NotSupportedException($"A array json reader for {nameof(ITraktSyncCollectionPost)} is not supported.");

        public IObjectJsonWriter<ITraktSyncCollectionPost> CreateObjectWriter() => new SyncCollectionPostObjectJsonWriter();
    }
}


text:
Dictionary Matchers
-------------------

Matchers of dictionaries.

has_entries
^^^^^^^^^^^

.. automodule:: hamcrest.library.collection.isdict_containingentries
    :exclude-members: has_entries
.. autofunction:: has_entries(matcher_dict)

has_entry
^^^^^^^^^

.. automodule:: hamcrest.library.collection.isdict_containing

has_key
^^^^^^^

.. automodule:: hamcrest.library.collection.isdict_containingkey

has_value
^^^^^^^^^

.. automodule:: hamcrest.library.collection.isdict_containingvalue


text:
package testapi

import (
	"fmt"
	"github.com/go-chef/chef"
	"os"
	"strings"
)

// principle test the chef api
func Principals() {
	// Use the default test org
	client := Client()

	// Create a client
	client1 := chef.ApiNewClient{
		Name:      "client1",
		CreateKey: true,
		Validator: false,
	}
	_, err := client.Clients.Create(client1)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Couldn't create client client1. ", err)
	}

	// Get principals - public key information
	clientInfo, err := client.Principals.Get("client1")
	if err != nil {
		fmt.Fprintln(os.Stderr, "Couldn't get client1 keys: ", err)
	}
	clientinfof := strings.Replace(fmt.Sprintf("%+v", clientInfo), "\n", "", -1)
	fmt.Printf("Client principal %+v\n", clientinfof)

	userInfo, err := client.Principals.Get("usr1")
	if err != nil {
		fmt.Fprintln(os.Stderr, "Couldn't get usr1 keys: ", err)
	}
	userinfof := strings.Replace(fmt.Sprintf("%+v", userInfo), "\n", "", -1)
	fmt.Printf("User principal %+v\n", userinfof)

	// Delete clients
	err = client.Clients.Delete("client1")
	fmt.Printf("Delete client1 %+v\n", err)
}


text:
#ifndef _CONDOR_READ_USER_LOG_CPP_H
#define _CONDOR_READ_USER_LOG_CPP_H

/* Since this is a Condor API header file, we want to minimize our
   reliance on other Condor files to ease distribution.  -Jim B. */
#include "condor_event.h"

/* Predeclare some classes */
class FileLockBase;
class FileLock;

/** API for reading a log file.

    This class was written at the same time the ULogEvent class was written,
    so it does not contain the old deprecated functions and parameters that
    the WriteUserLog class is plagued with.
*/
class ReadUserLogState;
class ReadUserLogMatch;
class ReadUserLog
{
  public:

	/** Use this to structure to serialize the current state.
		Always use InitFileState() to initialize this structure.
		More documentation below.
	*/
	struct FileState {
		void	*buf;
		int		size;
	};

	/** Returned values from the file status check operation
	 */
	enum FileStatus {
		LOG_STATUS_ERROR = -1,
		LOG_STATUS_NOCHANGE,
		LOG_STATUS_GROWN,
		LOG_STATUS_SHRUNK
	};

	/** Simple error information
	 */
	enum ErrorType {
		LOG_ERROR_NONE,					/* No error */
		LOG_ERROR_NOT_INITIALIZED,		/* Reader not initialized */
		LOG_ERROR_RE_INITIALIZE,		/* Attempt to re-initialize */
		LOG_ERROR_FILE_NOT_FOUND,		/* Log file not found */
		LOG_ERROR_FILE_OTHER,			/* Other file error */
		LOG_ERROR_STATE_ERROR			/* Invalid state */
	};

    /** Default constructor.
        @param isEventLog setup reader to read the global event log?
	*/
    ReadUserLog( bool isEventLog = false );

    /** Constructor for a limited functionality reader
		- No rotation handling
		- No locking
        @param fp the file to read from
		@param XML mode?
		@param close the FP when done?
	*/
    ReadUserLog( FILE *fp, int log_type, bool enable_close = false );

    /** Constructor.
        @param filename the file to read from
	*/
    ReadUserLog(const char * filename, bool read_only = false );

    /** Constructor.
        @param State to restore from
		@param Read only access to the file (locking disabled)
	*/
    ReadUserLog( const FileState &state, bool read_only = false );

    /** Destructor.
	*/
    ~ReadUserLog() { releaseResources(); }

    /** Detect whether the object has been initialized
	*/
    bool isInitialized( void ) const { return m_initialized; };

    /** Initialize to read the EventLog file.  This function will return
		false if it can't open the event log (among other problems).
        @return true for success
    */
    bool initialize ( void );

    /** Initialize the log file.  This function will return false
        if it can't open the log file (among other problems).
        @param file the file to read from
		@param handle_rotation enables the reader to handle rotating
		 log files (only useful for global user logs)
		@param check_for_rotated try to open the rotated
		 (".old" or ".1", ".2", ..) files first?
        @return true for success
    */
    bool initialize (const char *filename,
					 bool handle_rotation = false,
					 bool check_for_rotated = false,
					 bool read_only = false );

    /** Initialize the log file.  Similar to above, but takes an integer
		as its second parameter. This function will return false
        if it can't open the log file (among other problems).
        @param file the file to read from
		@param max_rotation sets max rotation file # the reader will
		 try to read (0 disables) (only useful for global user logs)
		@param check_for_rotated try to open the rotated
		 (".old" or ".1", ".2", ..) files first?
        @return true for success
    */
    bool initialize (const char *filename,
					 int max_rotation,
					 bool check_for_rotated = true,
					 bool read_only = false );

    /** Initialize the log file from a saved state.
		This function will return false if it can't open the log file
		 (among other problems).
        @param FileState saved file state
		@param Read only access to the file (locking disabled)
        @return true for success
    */
    bool initialize (const ReadUserLog::FileState &state,
					 bool read_only = false );

    /** Initialize the log file from a saved state and set the
		  rotation parameters
		This function will return false if it can't open the log file
		 (among other problems).
        @param FileState saved file state
        @param Maximum rotation files
		@param Read only access to the file (locking disabled)
        @return true for success
    */
    bool initialize (const ReadUserLog::FileState &state,
					 int max_rotations,
					 bool read_only = false );

    /** Read the next event from the log file.  The event pointer to
        set to point to a newly instatiated ULogEvent object.
        @param event pointer to be set to new object
        @return the outcome of attempting to read the log
    */
    ULogEventOutcome readEvent (ULogEvent * & event);

	/** Read the next event from the log file.  The event pointer to
		set to point to a newly instatiated ULogEvent object.
		@param event pointer to be set to new object
		@return the outcome of attempting to read the log
	*/
	ULogEventOutcome readEventWithLock (ULogEvent * & event, FileLockBase &lock);

    /** Synchronize the log file if the last event read was an error.  This
        safe guard function should be called if there is some error reading an
        event, but there are events after it in the file.  Will skip over the
        "bad" event (i.e., read up to and including the event separator (...))
        so that the rest of the events can be read.
        @return true: success, false: failure
    */
    bool synchronize ();

	/** Output the current file position
	 */
	void outputFilePos(const char *pszWhereAmI);

	/** Lock / unlock the file
	 */
	void Lock(void)   { Lock(nullptr, true);   };
	void Unlock(void) { Unlock(nullptr, true); };

	/** Enable / disable locking
	 */
	void setLock( bool enable ) { m_lock_enable = enable; };

	/** Set the # of rotations used
	 */
	void setRotations( int rotations ) { m_max_rotations = rotations; }

	/** Set whether the log file should be treated as XML. The constructor will
		attempt to figure this out on its own.
		@param is_xml should be true if we have an XML log file,
		 false otherwise
	*/
	void setIsCLASSADLog( int log_type ); // 0 = not classad, 1 = xml, 2 = json

	/** Determine whether this ReadUserLog thinks its log file is XML.
		Note that false may mean that the type is not yet known (e.g.,
		the log file is empty).
		@return true if XML, false otherwise
	*/
	int getIsCLASSADLog( void ) const;

    /** Check the status of the file - has it grown, shrunk, etc.
		@return LOG_STATUS_{ERROR,NOCHANGE,GROWN,SHRUNK}
	*/
	FileStatus CheckFileStatus( void );

    /** Check the status of the file - has it grown, shrunk, etc.
		@param reference: returned as true of the file is empty
		@return LOG_STATUS_{ERROR,NOCHANGE,GROWN,SHRUNK}
	*/
	FileStatus CheckFileStatus( bool &is_emtpy );

	/** Set whether the log file should be treated as "old-style" (non-XML).
	    The constructor will attempt to figure this out on its own.
		@param is_old should be true if we have a "old-style" log file,
		false otherwise
	*/
	//void setIsOldLog( bool is_old );

	/** Determine whether this ReadUserLog thinks its log file is "old-style"
	    (non-XML).
		Note that false may mean that the type is not yet known (e.g.,
		the log file is empty).
		@return true if "old-style", false otherwise
	*/
	//bool getIsOldLog( void ) const;

	/** Get error data
		@param error type
		@param source line # where error was detected
		@return void
	 */
	void getErrorInfo( ErrorType &error,
					   const char *& error_str,
					   unsigned &line_num ) const;

	/** These methods only do anything useful for anything other
	    than job event logs (which do not rotate). */
	size_t getOffset() const { return ftell(m_fp); }
	void setOffset(size_t offset) { fseek(m_fp, offset, SEEK_SET); }

	/** Methods to serialize the state.
		Always use InitFileState() to initialize this structure.
		All of these methods take a reference to a state buffer
		  as their only parameter.
		All of these methods return true upon success.

		To save the state, do something like this:
		  ReadUserLog				reader;
		  ReadUserLog::FileState	statebuf;

		  status = ReadUserLog::InitFileState( statebuf );

		  status = reader.GetFileState( statebuf );
		  write( fd, statebuf.buf, statebuf.size );
		  ...
		  status = reader.GetFileState( statebuf );
		  write( fd, statebuf.buf, statebuf.size );
		  ...

		  status = UninitFileState( statebuf );

		To restore the state, do something like this:
		  ReadUserLog::FileState	statebuf;
		  status = ReadUserLog::InitFileState( statebuf );

		  read( fd, statebuf.buf, statebuf.size );

		  ReadUserLog  				reader;
		  status = reader.initialize( statebuf );

		  status = UninitFileState( statebuf );
		  ....
	 */

	/** Use this method to initialize a file state buffer
		@param file state buffer
		@return true on success
	 */
	static bool InitFileState( ReadUserLog::FileState &state );

	/** Use this method to clean up a file state buffer (when done with it)
		@param file state buffer
		@return true on success
	 */
	static bool UninitFileState( ReadUserLog::FileState &state );

	/** Use this method to get the current state (before saving it off)
		@param file state buffer
		@return true on success
	 */
	bool GetFileState( ReadUserLog::FileState &state ) const;

	/** Use this method to set the current state (after restoring it).
		NOTE: The state buffer is *not* automatically updated; you *must*
		call the GetFileState() method each time before persisting the
		buffer to disk (or however else).
		@param file state buffer
		@return true on success
	 */
	bool SetFileState( const ReadUserLog::FileState &state );

	/** Release all resources this object has claimed/allocated.
	*/
	void releaseResources( void );

  private:

    /** Internal initializer from saved state.
		This function will return falseif it can't open the log file
		 (among other problems).
        @param FileState saved file state
        @param Change the max rotation value?
		@param max_rotations max rotations value of the logs
        @return true for success
    */
    bool InternalInitialize ( const ReadUserLog::FileState &state,
							  bool set_rotations,
							  int max_rotations,
							  bool read_only );

    /** Internal initializer.  This function will return false
        if it can't open the log file (among other things).
		@param max_rotation sets max rotation file # the reader will
		 try to read (0 disables) (only useful for global user logs)
		@param Max number of rotations to handle (0 = none)
		@param Restore previous file position
		@param Enable reading of the file header?
        @return true for success
    */
    bool InternalInitialize ( int max_rotation,
							  bool check_for_rotated,
							  bool restore_position,
							  bool enable_header_read,
							  bool read_only );

	/** Initialize rotation parameters
		@param Max number of rotations to handle (0 = none)
	 */
	void initRotParms( int max_rotation );

	/** Get max rotation parameter based
		@param Handle rotations?
	 */
	int getMaxRot( bool handle_rotation );

	/** Internal lock/unlock methods
		@param Verify that initialization has been done
	 */
	void Lock( FileLockBase *, bool verify_init );
	void Unlock( FileLockBase *, bool verify_init );

	/** Set all members to their cleared values.
	*/
	void clear( void );

    /** Read the next event from the log file.  The event pointer to
        set to point to a newly instatiated ULogEvent object.
        @param event pointer to be set to new object
		@param store the state after the read?
        @return the outcome of attempting to read the log
    */
    ULogEventOutcome readEventWithLock (ULogEvent * & event, bool store_state, FileLockBase *lock );

    /** Raw read of the next event from the log file.
        @param event pointer to be set to new object
		@param should the caller try the read again (after reopen) (returned)?
        @return the outcome of attempting to read the log
    */
    ULogEventOutcome rawReadEvent (ULogEvent * & event, bool *try_again, FileLockBase *lock );

	/** Determine the type of log this is; note that if called on an
	    empty log, this will return true and the log type will stay
		LOG_TYPE_UNKNOWN.
        @return true for success, false otherwise
	*/
	bool determineLogType( FileLockBase *lock );

	/** Skip the XML header of this log, if there is one.
	    @param the first character after the opening '<'
		@param the initial file position
        @return true for success, false otherwise
	*/
	bool skipXMLHeader(int afterangle, long filepos);

    /** Read the next event from the XML log file. The event pointer to
        set to point to a newly instatiated ULogEvent object.
        @param event pointer to be set to new object
        @return the outcome of attempting to read the log
    */
    ULogEventOutcome readEventClassad (ULogEvent * & event, int log_type, FileLockBase *lock);

    /** Read the next event from the old style log file. The event pointer to
        set to point to a newly instatiated ULogEvent object.
        @param event pointer to be set to new object
        @return the outcome of attempting to read the log
    */
    ULogEventOutcome readEventNormal (ULogEvent * & event, FileLockBase *lock);

	/** Reopen the log file
		@param Restore from state?
		@return the outcome of the re-open attempt
	 */
	ULogEventOutcome ReopenLogFile( bool restore = false );

	/** Find the previous log file starting with start
		@param log file rotation # to start the search with
		@param max number of files to look for before giving up (0==all)
		@param Store stat in state?
		@return true:success, false:none found
	 */
	bool FindPrevFile( int start, int num, bool store_stat );

	/** Open the log file
		@param Seek to previous location?
		@param Read file header?
		@return outcome of the open attempt
	 */
	ULogEventOutcome OpenLogFile( bool do_seek, bool read_header = true );

	/** Close the log file between operations
		@param force close even if "don't close" mode is set?
		@return true:success, false:failure
	 */
	bool CloseLogFile( bool force );

	/** Report error
		@param error type
		@param line number where error was detected
	*/
	void Error( ErrorType error, unsigned line_num ) const
		{ m_error = error; m_line_num = line_num; };

	/** Class private data
	 */
	bool				 m_initialized;	  /** Are we initialized? */
	bool				 m_missed_event;  /** Need to report event lost? */

	ReadUserLogState	*m_state;		  /** The state of the file */
	ReadUserLogMatch	*m_match;		  /** Detects file matches */

    int    				 m_fd;			  /** The log's file descriptor */
    FILE				*m_fp;			  /** The log's file pointer */

	bool				 m_close_file;	  /** Close file between operations? */
	bool				 m_enable_close;  /** enable close operations? */
	bool				 m_handle_rot;	  /** Do we handle file rotation? */
	int					 m_max_rotations; /** Max rotation number */
	bool				 m_read_header;	  /** Read the file's header? */
	bool				 m_read_only;	  /** Open file read only? */

	bool				 m_lock_enable;	  /** Should we lock the file? */
    FileLockBase		*m_lock;		  /** The log file lock */
	int					 m_lock_rot;	  /** Lock managing what rotation #? */

	/* Error history data */
	mutable ErrorType	 m_error;		/** Type of latest error (think errno) */
	mutable unsigned	 m_line_num;	/** Line number of latest error */
};

// Provide access to parts of the user log state data
class ReadUserLogFileState;
class ReadUserLogStateAccess
{
public:

	ReadUserLogStateAccess(const ReadUserLog::FileState &state);
	~ReadUserLogStateAccess(void);

	// Is the buffer initialized?
	bool isInitialized( void ) const;

	// Is the buffer valid for use by the ReadUserLog::initialize()?
	bool isValid( void ) const;

	// Position in individual file
	// Note: Can return an error if the result is too large
	//  to be stored in a long
	bool getFileOffset( unsigned long &pos ) const;

	// Positional difference between to states (this - other)
	bool getFileOffsetDiff( const ReadUserLogStateAccess &other,
							long &diff ) const;

	// Event number in individual file
	// Note: Can return an error if the result is too large
	//  to be stored in a long
	bool getFileEventNum( unsigned long &num ) const;

	// # of events between to states (this - other)
	bool getFileEventNumDiff( const ReadUserLogStateAccess &other,
							  long &diff ) const;

	// Position OF THE CURRENT FILE in overall log
	// Note: Can return an error if the result is too large
	//  to be stored in a long
	bool getLogPosition( unsigned long &pos ) const;

	// Positional difference between to states (this - other)
	bool getLogPositionDiff( const ReadUserLogStateAccess &other,
							 long &diff ) const;

	// Absolute event number OF THE FIRST EVENT IN THE CURRENT FILE
	// Note: Can return an error if the result is too large
	//  to be stored in a long
	bool getEventNumber( unsigned long &num ) const;

	// # of events between to states (this - other)
	bool getEventNumberDiff( const ReadUserLogStateAccess &other,
						  long &diff ) const;

	// Get the unique ID and sequence # of the associated state file
	bool getUniqId( char *buf, int len ) const;
	bool getSequenceNumber( int &seqno ) const;

	// Access to the state
protected:
	bool getState( const ReadUserLogFileState *&state ) const;

private:
	const ReadUserLogFileState	*m_state;
};

#endif /* _CONDOR_USER_LOG_CPP_H */

/*
### Local Variables: ***
### mode:c++ ***
### tab-width:4 ***
### End: ***
*/


text:
These are a set of test projects for `skaffold debug`.  There are two
configurations:

  - `skaffold.yaml` configures docker- and jib-based builders
  - `skaffold-bp.yaml` configures buildpacks-based builders

The test projects endeavour to support both docker or jib, and buildpacks.


text:
(function($){
  $.declare('wait',{
    defaults : {
      title : 'Loading...',
      preventClicks : true,
      theme : 'dark',
      onShow : $.noop,
      onHide : $.noop,
      pprogressSupport : false,
      pprogressFill : '#000',
      overlayTemplate : '

',
      modalTemplate : '

',
      pprogressTemplate : '

'
    },
    show : function (options){
      this.setOptions(options);

      if (this.preventClicks){
        this.el.addClass('wait-blur');
      }

      this.previousOverflow = this.el.css('overflow');
      this.el.css('overflow','hidden');

      this._createOverlay();
      this._createModal();
      this._bindEvents();

      this.pprogress('start',true);

      this.onShow.call(this);
      this.emit('show');
    },
    hide : function(){
      this._unbindEvents();

      if (this.preventClicks){
        this.el.removeClass('wait-blur');
      }

      this.el.css('overflow',this.previousOverflow);

      this._removeModal();
      this._removeOverlay();

      this.onHide.call(this);
      this.emit('hide');
    },
    setOptions : function(options){
      options = options || {};
      this.title = options.title || this.title;

      if (typeof options.preventClicks !== "undefined"){
        this.preventClicks = options.preventClicks;
      }

      if (typeof options.pprogressSupport !== "undefined"){
        this.pprogressSupport = options.pprogressSupport;
      }

      this.theme = options.theme || this.theme;
      this.onShow = options.onShow || this.onShow;
      this.onHide = options.onHide || this.onHide;
    },
    setText : function(text) {
      this.paragraph.text(text);
    },
    pprogress : function(){
      if (this.pprogressSupport){
        var args = Array.prototype.slice.call(arguments);
        if (args.length){
          this.pprogressDiv.pprogress.apply(this.pprogressDiv,args);
        }
      }
    },
    _createOverlay : function(){
      this.overlay = $(this.overlayTemplate)
          .addClass('wait-' + this.theme)
          .appendTo('body');

      this._positionOverlay();
    },
    _removeOverlay : function(){
      this.overlay.remove();
    },
    _positionOverlay : function() {
        var left = '0px',
            top = '0px',
            width = '100%',
            height = '100%',
            position = 'fixed';

        if (this.el[0].nodeName.toLowerCase() !== 'body'){
          var offset = this.el.offset();
          left = offset.left + 'px';
          top = offset.top + 'px';
          width = this.el.width() + 'px';
          height = this.el.height() + 'px';
          position = 'absolute';
        }

      this.overlay.css({
        width : width,
        height : height,
        left : left,
        top : top,
        position : position
      });
    },
    _createModal : function(){
      this.modal = $(this.modalTemplate).addClass('wait-' + this.theme).appendTo('body');
      this.paragraph = $('

').text(this.title).appendTo(this.modal);
      if (this.pprogressSupport){
        this.pprogressDiv = $(this.pprogressTemplate).appendTo(this.modal);
        this.pprogressDiv.pprogress({
          fillColor: this.pprogressFill
        });
      }

      this._positionModal();
    },
    _removeModal : function(){
      this.modal.remove();
    },
    _positionModal : function(){
      var left, top,
          position = 'absolute';

      if (this.el[0].nodeName.toLowerCase() !== 'body'){
        var offset = this.el.offset();
        top = ((this.el.height() - this.modal.outerHeight())/2 + offset.top);
        left = ((this.el.width() - this.modal.outerWidth())/2 + offset.left);
      }
      else {
        top = (($(window).height() - this.modal.outerHeight())/2 + $(document).scrollTop());
        left = (($(window).width() - this.modal.outerWidth())/2 + $(document).scrollLeft());
      }

      this.modal.css({
        left : left,
        top : top,
        position : position
      });
    },
    _bindEvents : function(){
      if (this.preventClicks){
        this.overlay.on('click',this._preventClick);
      }
      if (this.pprogressSupport){
        this.pprogressDiv.on('complete', this.proxy(this.hide));
      }
    },
    _unbindEvents : function(){
      if (this.preventClicks){
        this.overlay.off();
      }
      if (this.pprogressSupport){
        this.pprogressDiv.off();
      }
    },
    _preventClick : function(){
      return false;
    }
  });
})(jQuery);


text:
using AnnuaireCertifies.Domaine.Composite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AnnuaireCertifies.Domaine.Caching
{
    public class ModuleCache
    {
        public long ID { get; set; }
        public long TypeActionID { get; set; }
        public long TypeActionGeneraleID { get; set; }
        public string CodeRoute { get; set; }
    }
}


text:
title: Angle Between Vectors
localeTitle: Ângulo entre vetores
---
## Ângulo entre vetores

Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/vectors/angle-between-vectors/index.md) .

[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Mais Informações:


text:
<?php

namespace Illuminate\Foundation\Http\Middleware;

use Closure;
use Illuminate\Http\Exception\PostTooLargeException;

class VerifyPostSize
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     *
     * @throws \Illuminate\Http\Exception\PostTooLargeException
     */
    public function handle($request, Closure $next)
    {
        if ($request->server('CONTENT_LENGTH') > $this->getPostMaxSize()) {
            throw new PostTooLargeException;
        }

        return $next($request);
    }

    /**
     * Determine the server 'post_max_size' as bytes.
     *
     * @return int
     */
    protected function getPostMaxSize()
    {
        $postMaxSize = ini_get('post_max_size');

        $metric = strtoupper(substr($postMaxSize, -1));

        switch ($metric) {
            case 'K':
                return (int) $postMaxSize * 1024;
            case 'M':
                return (int) $postMaxSize * 1048576;
            case 'G':
                return (int) $postMaxSize * 1073741824;
            default:
                return (int) $postMaxSize;
        }
    }
}


text:
{% load i18n %}

{% trans 'Políticas de publicación en la red social' %}:

{% trans 'Todo usuario debe subir una foto al perfil, preferentemente de carácter personal.(No pueden ser sin camisa).' %}

{% trans 'No se pueden poner imágenes o avatares pornográficos.' %}

{% trans 'Todo usuario debe llenar su perfil con la mayor cantidad de datos posible, preferentemente su ubicación.' %}

{% trans 'Ser cuidadoso para lograr un uso correcto de la lengua materna y/o extranjera empleada en la redacción de los mensajes.' %}

{% trans 'Es prohibido los mensajes, blogs, páginas, archivos e imágenes con contenidos obscenos, eróticos y no acordes con los principios éticos y morales.' %}

{% trans 'Los Grupos deben tener más de 3 usuarios para que estén activos.' %}

{% trans 'Están prohibido los contenidos con carácter contrarrevolucionarios.' %}

{% trans 'Está prohibido utilizar la red para actividades económicas.' %}

{% trans 'No caer en faltas de respeto entre los usuarios de la red.' %}

{% trans 'Los Administradores se reservan el derecho a eliminar todo contenido que no cumpla con las normas del sitio.' %}

{% trans 'El desconocimiento de las reglas no exime de responsabilidad.' %}


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

  angular
    .module('app')
    .controller('HomeController', HomeController);

  HomeController.$inject = [
  ];

  function HomeController() {
    var vm = this;

    _active();

    function _active() {
      // var e = document.getElementById('prld');
      // if (e) e.remove();
    }
  }

})();


text:
package openrtb_ext

// ExtImpOpenx defines the contract for bidrequest.imp[i].ext.openx
type ExtImpOpenx struct {
	Unit         string                 `json:"unit"`
	Platform     string                 `json:"platform"`
	DelDomain    string                 `json:"delDomain"`
	CustomFloor  float64                `json:"customFloor"`
	CustomParams map[string]interface{} `json:"customParams"`
}


text:
package bravo.game.manager;

import java.util.Timer;
import java.util.TimerTask;

import com.example.bravo.MainActivity;
import com.example.bravo.R;

import android.widget.TextView;

public class GameTimer {
	protected static final int START_TIME = 5;
	protected static final String TAG = "FP";
	private String mText;
	private MainActivity mMainActivity;
	private TextView mTextTime;
	int sec = 0;
	int min = 5;

	public GameTimer(MainActivity Activity){
		mMainActivity = Activity;
		mTextTime = (TextView) mMainActivity.findViewById(R.id.TextTime);
		mTextTime.setText(String.format("TIME"));
	}

	Timer timer = new Timer();
	TimerTask task = new TimerTask() {
		int tenMilSec = 0;
		int sec = 0;
		int min = START_TIME;
		public void run() {
			printTime("" + min + ":" + sec + ":" + tenMilSec);
			if (mMainActivity.mGameManager.GameIsRuning() == false){return;}
			updateGame(min, sec, tenMilSec); //update all game activities that require time;
			if (tenMilSec == 0) {
				tenMilSec = 99;
				if (sec == 0) {
					sec = 59;
					min--;
				} else {
					sec--;
				}
			}else {
				tenMilSec--;
			}
		}

	};

	public void start() {
		timer.scheduleAtFixedRate(task, 10, 10);
	}

	public void printTime(String text){
		mText = text;
		mMainActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // This code will always run on the UI thread, therefore is safe to modify UI elements.
            	mTextTime.setText(String.format(mText));
            }
        });
	}

	public void resetCoin(){
		mMainActivity.mGameManager.CoinDistribution(true);
	}

	public void coinUpdate(int min, int sec, int tMilSec){
		if (((sec == 30) || (sec == 0)) && (tMilSec == 0)){
			resetCoin(); // to change position of the coin
		}
		mMainActivity.mGameManager.rotateCoin();
	}

	private void updateGame(int min, int sec, int tMilSec){
		coinUpdate(min, sec, tMilSec);
		lazerUpdate(min, sec, tMilSec);
	}

	private void lazerUpdate(int min, int sec, int tMilSec){
		if ((min > START_TIME - 2) && ((sec > 45) || (sec == 0))){
			return;
		}
		if((sec % 10 == 5) && (tMilSec == 0)){
			mMainActivity.mGameManager.laserDistribution(true);
		}
		for(int i = 1; i < 4; i++){
			if((sec % 10 == i ) && (tMilSec == 0)){
				mMainActivity.mGameManager.laserWarningOn();
			}
			if((sec % 10 == i - 1) && (tMilSec == 50)){
				mMainActivity.mGameManager.laserWarningOff();
			}
		}
		if((sec % 10 == 0) && (tMilSec == 0)){
			mMainActivity.mGameManager.laserOn();
		}
		if((sec % 10 == 8) && (tMilSec == 0)){
			mMainActivity.mGameManager.laserOff();
		}
	}
}


text:
package quarks.oplet.core;

/**
 * Oplet that allows a peek at each tuple and always forwards a tuple onto
 * its single output port.
 *
 * {@link #peek(Object)} is called before the tuple is forwarded
 * and it is intended that the peek be a low cost operation
 * such as increasing a metric.
 *
 * @param <T>
 *            Type of the tuple.
 */
public abstract class Peek<T> extends Pipe<T, T> {
    private static final long serialVersionUID = 1L;

    @Override
    public final void accept(T tuple) {
        peek(tuple);
        submit(tuple);
    }

    protected abstract void peek(T tuple);
}


text:
@implementation MyMapBlockCode

+(MyMapBlockCode *)blockCodeWithDictionary:(NSDictionary *)dict {
    MyMapBlockCode *me = [[MyMapBlockCode alloc] init];
    me.value = [dict nullSafeObjectForKey:@"value"];
    me.apiType = [dict nullSafeObjectForKey:@"api_type"];
    me.desc = [dict nullSafeObjectForKey:@"desc"];
    return me;
}

-(NSString *)abbreviation {
    return self.desc;
}

-(NSString *)displayText {
    return self.desc;
}

-(NSString *)displayDetailText {
    return @"";
}

@end


text:
class InvalidApnsModeError < StandardError
  def initialize
    super 'Tried to set invalid APNS mode.'
  end
end


text:
/* <DESC>
 * IMAP example showing how to search for new e-mails
 * </DESC>
 */

#include <stdio.h>
#include <curl/curl.h>

/* This is a simple example showing how to search for new messages using
 * libcurl's IMAP capabilities.
 *
 * Note that this example requires libcurl 7.30.0 or above.
 */

int main(void)
{
  CURL *curl;
  CURLcode res = CURLE_OK;

  curl = curl_easy_init();
  if(curl) {
    /* Set username and password */
    curl_easy_setopt(curl, CURLOPT_USERNAME, "user");
    curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret");

    /* This is mailbox folder to select */
    curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com/INBOX");

    /* Set the SEARCH command specifing what we want to search for. Note that
     * this can contain a message sequence set and a number of search criteria
     * keywords including flags such as ANSWERED, DELETED, DRAFT, FLAGGED, NEW,
     * RECENT and SEEN. For more information about the search criteria please
     * see RFC-3501 section 6.4.4.   */
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "SEARCH NEW");

    /* Perform the custom request */
    res = curl_easy_perform(curl);

    /* Check for errors */
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    /* Always cleanup */
    curl_easy_cleanup(curl);
  }

  return (int)res;
}


text:
sudo apt-get install -y --upgrade python3-pip python3-setuptools
pip3 install --upgrade wheel
pip3 install --upgrade PyYAML requests

cat << EOF > $2
{"envs": {"PATH": "$JAVA_HOME_11_X64/bin:$PATH", "JAVA_HOME": "$JAVA_HOME_11_X64"}}
EOF


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

    <com.example.shli.slip.support.SlipImage
        android:id="@+id/gallery_view"
        android:layout_width="match_parent"
        android:layout_height="330dp"/>

    <com.example.shli.slip.support.SlipText
        android:id="@+id/title_view"
        android:layout_width="match_parent"
        android:layout_height="60dp"/>

</LinearLayout>


text:
  <link rel="stylesheet" href="maven-theme.css">
  <title>AppSecInc. MSI Extensions</title>

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

Wix

Extensions

DataSource

AccessDataSource

Public Attributes |
List of all members

Wix::Extensions::DataSource::AccessDataSource Class Reference

Public Attributes

string 	Id

string 	Name

string 	DBQ

string 	Username

string 	Password

string 	Description

YesNoType 	CreateOnInstall

YesNoType 	CreateOnUnInstall

YesNoType 	DeleteOnInstall

YesNoType 	DeleteOnUnInstall

DSNType 	Type

Detailed Description

Implements creation and deletion of a Microsoft Access DSN.

    AccessDataSource can be nested under a component or product/module/fragment. When nested
    under a component, conditions of the latter apply. When nested under product, module or fragment, you
    can specify explicit conditions that will be combined with CreateOnInstall, CreateOnUnInstall, DeleteOnInstall and
    DeleteOnUnInstall options.

    Note that AccessDataSource runs automatically before databases are created on install and after databases are dropped
    on uninstall.

 May be nested under Component.

Member Data Documentation

          YesNoType Wix::Extensions::DataSource::AccessDataSource::CreateOnInstall

Create DSN at install time.

          YesNoType Wix::Extensions::DataSource::AccessDataSource::CreateOnUnInstall

Create DSN at uninstall time.

          string Wix::Extensions::DataSource::AccessDataSource::DBQ

Complete path to the .mdb database file. Note that creating the DSN will succeed with the wrong path, but the database will be inaccessible.

          YesNoType Wix::Extensions::DataSource::AccessDataSource::DeleteOnInstall

Delete DSN at install time.

          YesNoType Wix::Extensions::DataSource::AccessDataSource::DeleteOnUnInstall

Delete DSN at uninstall time.

          string Wix::Extensions::DataSource::AccessDataSource::Description

Optional DSN description.

          string Wix::Extensions::DataSource::AccessDataSource::Id

Identifier for the ODBC datasource (primary key).

          string Wix::Extensions::DataSource::AccessDataSource::Name

Name of the DSN.

          string Wix::Extensions::DataSource::AccessDataSource::Password

Optional database password.

          DSNType Wix::Extensions::DataSource::AccessDataSource::Type

DSN type.

          string Wix::Extensions::DataSource::AccessDataSource::Username

Optional database username.

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

src/WixExtensions/DataSourceExtension/wixext/Xsd/DataSource.xsd

     © Application Security Inc. - All Rights Reserved

     http://msiext.codeplex.com

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


text:
using Microsoft.AspNetCore.Routing.Constraints;

namespace Exceptionless.Web.Utility;

public class TokensRouteConstraint : RegexRouteConstraint {
    public TokensRouteConstraint() : base(@"^[a-zA-Z\d-]{24,40}(,[a-zA-Z\d-]{24,40})*$") { }
}


text:
import React from 'react/addons';
import Options from './';
import TestUtils from 'TestUtils';

let component;

describe('Option list', () => {

  afterEach(done => {
    React.unmountComponentAtNode(document.body);
    document.body.innerHTML = '';
    done();
  });

  //INITIAL STATE

  describe('by default', () => {

    beforeEach(() => {
      component = TestUtils.renderComponent(Options);
    });

    it('has empty options array', () => {
        expect(component.props.options).to.be.instanceof(Array);
        expect(component.props.options).to.be.empty;
    });

    it('has empty term', () => {
        expect(component.props.term).to.equal('');
    });

    it('has default empty info', () => {
        expect(component.props.emptyInfo).to.equal('no suggestions');
    });

  });

  //UNIT

  //FUNCTIONAL
  it('displays options', () => {

    const component = TestUtils.renderComponent(Options, {
      options: ['a', 'a', 'a', 'a', 'a', 'a']
    });

    const options = React.findDOMNode(component.refs.wrapper).querySelectorAll('div');

    expect(options.length).to.equal(6);

  });

  it('selects first option by default', () => {

    const component = TestUtils.renderComponent(Options, {
      options: ['a', 'a', 'a', 'a', 'a', 'a']
    });

    expect(component.state.selected).to.equal(0);

  });

  it('cycles through list', () => {

    const component = TestUtils.renderComponent(Options, {
      options: ['a', 'a', 'a']
    });

    component.selectNext();
    expect(component.state.selected).to.equal(1);
    component.selectNext();
    component.selectNext();
    expect(component.state.selected).to.equal(0);
    component.selectPrev();
    expect(component.state.selected).to.equal(2);
    component.selectPrev();
    expect(component.state.selected).to.equal(1);

  });

  it('displays empty info if options list is empty', () => {

    const component1 = TestUtils.renderComponent(Options, {
      options: ['a']
    });

    const component2 = TestUtils.renderComponent(Options, {
        options: []
      });

    const emptyInfoNode = React.findDOMNode(component2.refs.emptyInfo);

    expect(component1.refs.emptyInfo).not.to.exist;
    expect(component2.refs.emptyInfo).to.exist;
    expect(emptyInfoNode.textContent).to.equal('no suggestions');

  });

});