text:
<?php

namespace Illuminate\Support\Facades;

use Illuminate\Contracts\Auth\PasswordBroker;

/**
 * @method static mixed reset(array $credentials, \Closure $callback)
 * @method static string sendResetLink(array $credentials, \Closure $callback = null)
 * @method static \Illuminate\Contracts\Auth\CanResetPassword|null getUser(array $credentials)
 * @method static string createToken(\Illuminate\Contracts\Auth\CanResetPassword $user)
 * @method static void deleteToken(\Illuminate\Contracts\Auth\CanResetPassword $user)
 * @method static bool tokenExists(\Illuminate\Contracts\Auth\CanResetPassword $user, string $token)
 * @method static \Illuminate\Auth\Passwords\TokenRepositoryInterface getRepository()
 * @method static \Illuminate\Contracts\Auth\PasswordBroker broker(string|null $name = null)
 *
 * @see \Illuminate\Auth\Passwords\PasswordBroker
 */
class Password extends Facade
{
    /**
     * Constant representing a successfully sent reminder.
     *
     * @var string
     */
    const RESET_LINK_SENT = PasswordBroker::RESET_LINK_SENT;

    /**
     * Constant representing a successfully reset password.
     *
     * @var string
     */
    const PASSWORD_RESET = PasswordBroker::PASSWORD_RESET;

    /**
     * Constant representing the user not found response.
     *
     * @var string
     */
    const INVALID_USER = PasswordBroker::INVALID_USER;

    /**
     * Constant representing an invalid token.
     *
     * @var string
     */
    const INVALID_TOKEN = PasswordBroker::INVALID_TOKEN;

    /**
     * Constant representing a throttled reset attempt.
     *
     * @var string
     */
    const RESET_THROTTLED = PasswordBroker::RESET_THROTTLED;

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'auth.password';
    }
}


text:
from .entity import Entity

class User(Entity):
    """PagerDuty user entity."""
    STR_OUTPUT_FIELDS = ('id', 'email',)
    EXCLUDE_FILTERS = TRANSLATE_QUERY_PARAM = ('email', 'name',)

    @property
    def email(self):
        return self['email']

    @classmethod
    def create(cls, data=None, api_key=None, add_headers=None, from_email=None,
               **kwargs):
        if add_headers is None:
            add_headers = {}

        if from_email is None:
            raise Exception('%s.create requires from_email keyword argument'
                            % (cls,))
        if from_email is not None:
            add_headers['From'] = from_email

        return getattr(Entity, 'create').im_func(
            cls,
            data=data,
            api_key=api_key,
            add_headers=add_headers
        )

    def contact_methods(self, **kwargs):
        """Get all contact methods for this user."""
        endpoint = '{0}/{1}/contact_methods'.format(
            self.endpoint,
            self['id'],
        )
        result = self.request('GET', endpoint=endpoint, query_params=kwargs)
        return result['contact_methods']

    def create_contact_method(self, data, **kwargs):
        """Create a contact method for this user."""
        data = {'contact_method': data, }
        endpoint = '{0}/{1}/contact_methods'.format(
            self.endpoint,
            self['id'],
        )
        result = self.request('POST', endpoint=endpoint, data=data,
                              query_params=kwargs)
        self._data['contact_methods'].append(result['contact_method'])
        return result

    def delete_contact_method(self, id, **kwargs):
        """Delete a contact method for this user."""
        endpoint = '{0}/{1}/contact_methods/{2}'.format(
            self.endpoint,
            self['id'],
            id,
        )
        return self.request('DELETE', endpoint=endpoint, query_params=kwargs)

    def get_contact_method(self, id, **kwargs):
        """Get a contact method for this user."""
        endpoint = '{0}/{1}/contact_methods/{2}'.format(
            self.endpoint,
            self['id'],
            id,
        )
        result = self.request('GET', endpoint=endpoint, query_params=kwargs)
        return result['contact_method']

    def notification_rules(self, **kwargs):
        """Get all notification rules for this user."""
        endpoint = '{0}/{1}/notification_rules'.format(
            self.endpoint,
            self['id'],
        )
        result = self.request('GET', endpoint=endpoint, query_params=kwargs)
        return result['notification_rules']

    def get_notification_rule(self, id, **kwargs):
        """Get a notification rule for this user."""
        endpoint = '{0}/{1}/notification_rules/{2}'.format(
            self.endpoint,
            self['id'],
            id,
        )
        result = self.request('GET', endpoint=endpoint, query_params=kwargs)
        return result['notification_rule']

    def create_notification_rule(self, data, **kwargs):
        """Create a notification rule for this user."""
        data = {'notification_rule': data, }
        endpoint = '{0}/{1}/notification_rules'.format(
            self.endpoint,
            self['id'],
        )
        result = self.request('POST', endpoint=endpoint, data=data,
                              query_params=kwargs)
        self._data['notification_rules'].append(result['notification_rule'])
        return result

    def delete_notification_rule(self, id, **kwargs):
        """Get a notification rule for this user."""
        endpoint = '{0}/{1}/notification_rules/{2}'.format(
            self.endpoint,
            self['id'],
            id,
        )
        return self.request('DELETE', endpoint=endpoint, query_params=kwargs)

    def update_contact_method(self, *args, **kwargs):
        """Please implement me."""
        raise NotImplemented

    def update_notification_rule(self, *args, **kwargs):
        """Please implement me."""
        raise NotImplemented

    def update(self, *args, **kwargs):
        """Update this team."""
        raise NotImplemented

redpajama_set_name: RedPajamaGithub


text:
namespace YoloCrawler.Entities
{
    using Fighting;

    public class Monster : Being, ICanAttack, ICanBeAttacked
    {
        const int MinHitpoints = 2;
        const int MaxHitpoints = 8;

        public Monster(string name, Position position)
        {
            Name = name;
            Position = position;
            Hitpoints = new YoloDice().RollForHitpoints(MinHitpoints, MaxHitpoints);
        }

        public void Take(Damage dmg)
        {
            Hitpoints -= dmg.Hitpoints;
        }

        public void Attack(ICanBeAttacked target)
        {
            target.Take(new Damage
            {
                Hitpoints = 1
            });
        }

        public void Move(Offset offset)
        {
            Position += offset;
        }
    }
}


text:
/* global alert, require */
require(['jquery', 'lib/knockout-3.1.0'], function($, ko) {
    'use strict';

    var MIN_PLAYER_COUNT = 2,
        MAX_PLAYER_COUNT = 2,
        IS_SPY = 0,
        IS_COUNTER_SPY = 1;

    var Events = {
        NEW_PLAYER: 'new_player',
        PLAYER_QUIT: 'player_quit',
        NEW_MASTER: 'new_master',
        PLAYER_ROLE_ASSIGNED: 'player_role_assigned',
        GAME_STARTED: 'game_started',
        GAME_ABORTED: 'game_aborted',
        LOST_CONNECTION: 'lost_connection'
    };

    // Using jQuery 1.9.1
    $('body').css('visibility', 'visible');
    $(document).ajaxError(function(event, jqxhr) {
        var response = JSON.parse(jqxhr.responseText);
        if(response.error) {
            alert(response.error);
        }
    });

    var game, playerList, wsController;

    function WebSocketController() {}
    WebSocketController.prototype = {
        connect: function() {
            this.ws = new WebSocket('ws://localhost:8888/socket');

            this.ws.onopen      = this.onOpen.bind(this);
            this.ws.onmessage   = this.onMessage.bind(this);
            this.ws.onclose     = this.onClose.bind(this);
            this.ws.onerror     = this.onError.bind(this);
        },

        send: function(message) {
            this.ws.send(JSON.stringify(message));
        },

        onOpen: function() {
            $(this).trigger('open');
        },

        onMessage: function(message) {
            var data  = JSON.parse(message.data),
                event = data.event;

            $(this).trigger(event, [data]);
        },
        onClose: function() {
            alert('Connection with server closed');
            document.reload();
        },
        onError: function() {
            alert('Error in server connection');
            document.reload();
        }
    };

    ko.bindingHandlers.fadeVisible = {
        init: function(element, valueAccessor) {
            // Start visible/invisible according to initial value
            var shouldDisplay = valueAccessor();
            $(element).toggle(shouldDisplay);
        },
        update: function(element, valueAccessor) {
            // On update, fade in/out
            var shouldDisplay = valueAccessor();
            return shouldDisplay ? $(element).fadeIn() : $(element).fadeOut();
        }
    };

    function Player(data) {
        this.name = ko.observable(data.name);
        this.score = ko.observable(data.score);
    }

    function PlayerListViewModel(webSocketController) {
        var self        = this,
            $ws         = $(webSocketController);
        self.players    = ko.observableArray([]);
        self.hasPlayers = ko.computed(this._hasPlayers, this);

        $ws.bind(Events.NEW_PLAYER,   this.onNewPlayer.bind(this));
        $ws.bind(Events.PLAYER_QUIT,  this.onPlayerQuit.bind(this));
        $ws.bind(Events.GAME_ABORTED, this.onGameAborted.bind(this));

        self.loadPlayers();
    }
    PlayerListViewModel.prototype = {
        _hasPlayers: function() {
            return this.players().length > 0;
        },

        sortPlayers: function(a, b) {
            return a.score() === b.score() ? (a.name() < b.name() ? -1 : 1) : (a.score() < b.score() ? -1 : 1);
        },

        count: function() {
            return this.players().length;
        },

        loadPlayers: function() {
            var self = this;

            $.getJSON('/players', function(allData) {
                $.each(allData, function(idx, playerData) {
                    self.addPlayer(playerData);
                });
            });
        },

        addPlayer: function(playerData) {
            this.players.push(new Player(playerData));
        },

        removePlayer: function(playerName) {
            this.players.remove(function(player) { return player.name() === playerName; });
        },

        onNewPlayer: function(event, data) {
            this.addPlayer(data.player);
        },

        onPlayerQuit: function(event, data) {
            this.removePlayer(data.player_name);
        },

        onGameAborted: function() {
            this.players([]);
        }
    };

    function PyLinq(playerList, webSocketController) {
        this.playerName         = ko.observable('');
        this.playerRole         = ko.observable(false);
        this.getPlayerRole      = ko.computed(this._getPlayerRole, this);
        this.playerSecretWord   = ko.observable(false);
        this.playerList         = playerList;

        this.isConnected        = ko.observable(false);
        this.hasJoined          = ko.observable(false);
        this.isMaster           = ko.observable(false);
        this.isGameStarted      = ko.observable(false);
        this.canStartGame       = ko.computed(this._canStartGame, this);

        this.wsController = webSocketController;

        $(webSocketController)
            .bind('open', this.onConnect.bind(this))
            .bind(Events.NEW_MASTER, this.onNewMaster.bind(this))
            .bind(Events.GAME_STARTED, this.onGameStarted.bind(this))
            .bind(Events.GAME_ABORTED, this.onGameAborted.bind(this))
            .bind(Events.LOST_CONNECTION, this.onLostConnection.bind(this))
            .bind(Events.PLAYER_ROLE_ASSIGNED, this.onRoleAssigned.bind(this));
    }
    PyLinq.prototype = {
        _canStartGame: function() {
            return this.isMaster() &&
                   !this.isGameStarted() &&
                   this.playerList.count() >= MIN_PLAYER_COUNT;
        },

        _getPlayerRole: function() {
            if (false === this.playerRole()) {
                return false;
            }

            return this.playerRole() === IS_SPY ? 'spy' : 'counter-spy';
        },

        onConnect: function() {
            this.isConnected(true);
        },

        onNewMaster: function(event, data) {
            this.isMaster(this.playerName() && data.player_name === this.playerName());
            if(this.isMaster()) {
                alert('You\'re the new master player. Only you can start the game.');
            }
        },

        onGameStarted: function() {
            this.isGameStarted(true);
            alert('The game has started');
        },

        onGameAborted: function() {
            this.isGameStarted(false);
            this.hasJoined(false);
            this.playerName('');
            this.isMaster(false);
            this.playerList().removeAll();

            alert('The game has been aborted');
        },

        onLostConnection: function() {
            alert('A player connection was lost.\
            Game will be aborted if connection is not resumed in 30s.');
        },

        join: function() {
            var self = this;

            $.post('/join', { player_name: this.playerName })
            .done(function(response) {
                if(!response.joined) {
                    return alert('Could not join game: ' + response.error || 'error unknown');
                }
                self.hasJoined(true);

                // Quit game when navigating away from the page
                $(window).on('beforeunload', self.onBeforeQuit.bind(self));
                $(window).on('unload', self.onQuitGame.bind(self));

                self.wsController.send({ playerName: self.playerName() });
            });
        },

        onRoleAssigned: function(event, data) {
            this.playerRole(data.role);
            this.playerSecretWord(data.secret_word);
            if(data.role === IS_SPY) {
                alert('You are a spy! Your secret word is "' + data.secret_word + "'.");
            }
        },

        startGame: function() {
            $.post('/start', { player_name: this.playerName })
            .done(function(response) {
                if(!response.started) {
                    return alert('Could not start game: ' + response.error || 'error unknown');
                }

            });
        },

        onBeforeQuit: function() {
            if(this.hasJoined() > 0) {
                var msg = ['Navigating away from this page will make you quit the game.'];
                if(this.isGameStarted()) {
                    msg.push(' Since the game has already started, quitting is going to abort it. This will put everybody on edge for the rest of the day.');
                }
                return msg.join('');
            }
        },

        onQuitGame: function() {
            $.ajax({
                url: '/quit',
                method: 'post',
                async: false,
                data: { player_name: this.playerName }
            });
        }
    };

    wsController = new WebSocketController();
    playerList = new PlayerListViewModel(wsController);
    game = new PyLinq(playerList, wsController);

    ko.applyBindings(game);
    wsController.connect();

    window.wsController = wsController;
});


text:
package ro.msg.learning.shop.handlers;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import ro.msg.learning.shop.exceptions.NoCustomerException;
import ro.msg.learning.shop.exceptions.NoSingleLocationFoundException;
import ro.msg.learning.shop.exceptions.ProductNotFoundException;
import ro.msg.learning.shop.exceptions.QuantityExceedsStockException;

/**
 * @author Zbiera Alexandru-Robert <Robert.Zbiera@msg.group>
 * Rest Controller Advice for handling the exceptions raised by the services
 */
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = NoSingleLocationFoundException.class)
    protected ResponseEntity<Object> noSingleLocationFoundHandler(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "No Single Location found ... " + ex.getMessage();
        return handleExceptionInternal(ex, bodyOfResponse,
            new HttpHeaders(), HttpStatus.CONFLICT, request);
    }

    @ExceptionHandler(value = ProductNotFoundException.class)
    protected ResponseEntity<Object> productNotFoundHandler(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "Product not found ... " + ex.getMessage();
        return handleExceptionInternal(ex, bodyOfResponse,
            new HttpHeaders(), HttpStatus.CONFLICT, request);
    }

    @ExceptionHandler(value = QuantityExceedsStockException.class)
    protected ResponseEntity<Object> quantityExceedsStockHandler(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "Quantity exceeds stock ... " + ex.getMessage();
        return handleExceptionInternal(ex, bodyOfResponse,
            new HttpHeaders(), HttpStatus.CONFLICT, request);
    }

    @ExceptionHandler(value = NoCustomerException.class)
    protected ResponseEntity<Object> noCustomerExceptionHandler(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "Customer does not exist ... \nMaybe you did not link a customer to your account ... " + ex.getMessage();
        return handleExceptionInternal(ex, bodyOfResponse,
            new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
}


text:
/**
 * The examples provided by Formidable Labs are for non-commercial testing and
 * evaluation purposes only. Formidable Labs reserves all rights not expressly
 * granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * FORMIDABLE LABS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

const express = require('express');
const proxy = require('express-http-proxy');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
import App from './app'; // Leave ESM import
const fs = require('fs');
const path = require('path');

const indexHTML = fs
  .readFileSync(path.resolve(__dirname, 'index.html'))
  .toString();
const app = express();
const host = 'localhost';
const port = 8000;

app.use('/app.js', proxy('localhost:8080', {forwardPath: () => '/app.js'}));

app.get('/', (req, res) => {
  const appHtml = ReactDOMServer.renderToString(
    <App radiumConfig={{userAgent: req.headers['user-agent']}} />
  );
  res.write(indexHTML.replace('<!-- {{app}} -->', appHtml));
  res.end();
});

app.listen(port, host, () => {
  // eslint-disable-next-line no-console
  console.log('Access the universal app at http://%s:%d', host, port);
});


text:
package com.hyrax.client.account.api.response;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class HyraxResponse<T> {

    private final ResponseStatus responseStatus;
    private final T payload;
    private final String reason;
}


text:
#import <Foundation/Foundation.h>

@class GCDAsyncSocket;
@class WebSocket;

#if TARGET_OS_IPHONE
  #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000 // iPhone 4.0
    #define IMPLEMENTED_PROTOCOLS <NSNetServiceDelegate>
  #else
    #define IMPLEMENTED_PROTOCOLS
  #endif
#else
  #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 // Mac OS X 10.6
    #define IMPLEMENTED_PROTOCOLS <NSNetServiceDelegate>
  #else
    #define IMPLEMENTED_PROTOCOLS
  #endif
#endif

@interface HTTPServer : NSObject IMPLEMENTED_PROTOCOLS
{
	// Underlying asynchronous TCP/IP socket
	GCDAsyncSocket *asyncSocket;

	// Dispatch queues
	dispatch_queue_t serverQueue;
	dispatch_queue_t connectionQueue;
	void *IsOnServerQueueKey;
	void *IsOnConnectionQueueKey;

	// HTTP server configuration
	NSString *documentRoot;
	Class connectionClass;
	NSString *interface;
	UInt16 port;

	// NSNetService and related variables
	NSNetService *netService;
	NSString *domain;
	NSString *type;
	NSString *name;
	NSString *publishedName;
	NSDictionary *txtRecordDictionary;

	// Connection management
	NSMutableArray *connections;
	NSMutableArray *webSockets;
	NSLock *connectionsLock;
	NSLock *webSocketsLock;

	BOOL isRunning;
}

@property (nonatomic, strong, readonly) GCDAsyncSocket *asyncSocket;

/**
 * Specifies the document root to serve files from.
 * For example, if you set this to "/Users/<your_username>/Sites",
 * then it will serve files out of the local Sites directory (including subdirectories).
 *
 * The default value is nil.
 * The default server configuration will not serve any files until this is set.
 *
 * If you change the documentRoot while the server is running,
 * the change will affect future incoming http connections.
**/
- (NSString *)documentRoot;
- (void)setDocumentRoot:(NSString *)value;

/**
 * The connection class is the class used to handle incoming HTTP connections.
 *
 * The default value is [HTTPConnection class].
 * You can override HTTPConnection, and then set this to [MyHTTPConnection class].
 *
 * If you change the connectionClass while the server is running,
 * the change will affect future incoming http connections.
**/
- (Class)connectionClass;
- (void)setConnectionClass:(Class)value;

/**
 * Set what interface you'd like the server to listen on.
 * By default this is nil, which causes the server to listen on all available interfaces like en1, wifi etc.
 *
 * The interface may be specified by name (e.g. "en1" or "lo0") or by IP address (e.g. "192.168.4.34").
 * You may also use the special strings "localhost" or "loopback" to specify that
 * the socket only accept connections from the local machine.
**/
- (NSString *)interface;
- (void)setInterface:(NSString *)value;

/**
 * The port number to run the HTTP server on.
 *
 * The default port number is zero, meaning the server will automatically use any available port.
 * This is the recommended port value, as it avoids possible port conflicts with other applications.
 * Technologies such as Bonjour can be used to allow other applications to automatically discover the port number.
 *
 * Note: As is common on most OS's, you need root privledges to bind to port numbers below 1024.
 *
 * You can change the port property while the server is running, but it won't affect the running server.
 * To actually change the port the server is listening for connections on you'll need to restart the server.
 *
 * The listeningPort method will always return the port number the running server is listening for connections on.
 * If the server is not running this method returns 0.
**/
- (UInt16)port;
- (UInt16)listeningPort;
- (void)setPort:(UInt16)value;

/**
 * Bonjour domain for publishing the service.
 * The default value is "local.".
 *
 * Note: Bonjour publishing requires you set a type.
 *
 * If you change the domain property after the bonjour service has already been published (server already started),
 * you'll need to invoke the republishBonjour method to update the broadcasted bonjour service.
**/
- (NSString *)domain;
- (void)setDomain:(NSString *)value;

/**
 * Bonjour name for publishing the service.
 * The default value is "".
 *
 * If using an empty string ("") for the service name when registering,
 * the system will automatically use the "Computer Name".
 * Using an empty string will also handle name conflicts
 * by automatically appending a digit to the end of the name.
 *
 * Note: Bonjour publishing requires you set a type.
 *
 * If you change the name after the bonjour service has already been published (server already started),
 * you'll need to invoke the republishBonjour method to update the broadcasted bonjour service.
 *
 * The publishedName method will always return the actual name that was published via the bonjour service.
 * If the service is not running this method returns nil.
**/
- (NSString *)name;
- (NSString *)publishedName;
- (void)setName:(NSString *)value;

/**
 * Bonjour type for publishing the service.
 * The default value is nil.
 * The service will not be published via bonjour unless the type is set.
 *
 * If you wish to publish the service as a traditional HTTP server, you should set the type to be "_http._tcp.".
 *
 * If you change the type after the bonjour service has already been published (server already started),
 * you'll need to invoke the republishBonjour method to update the broadcasted bonjour service.
**/
- (NSString *)type;
- (void)setType:(NSString *)value;

/**
 * Republishes the service via bonjour if the server is running.
 * If the service was not previously published, this method will publish it (if the server is running).
**/
- (void)republishBonjour;

/**
 *
**/
- (NSDictionary *)TXTRecordDictionary;
- (void)setTXTRecordDictionary:(NSDictionary *)dict;

/**
 * Attempts to starts the server on the configured port, interface, etc.
 *
 * If an error occurs, this method returns NO and sets the errPtr (if given).
 * Otherwise returns YES on success.
 *
 * Some examples of errors that might occur:
 * - You specified the server listen on a port which is already in use by another application.
 * - You specified the server listen on a port number below 1024, which requires root priviledges.
 *
 * Code Example:
 *
 * NSError *err = nil;
 * if (![httpServer start:&err])
 * {
 *     NSLog(@"Error starting http server: %@", err);
 * }
**/
- (BOOL)start:(NSError **)errPtr;

/**
 * Stops the server, preventing it from accepting any new connections.
 * You may specify whether or not you want to close the existing client connections.
 *
 * The default stop method (with no arguments) will close any existing connections. (It invokes [self stop:NO])
**/
- (void)stop;
- (void)stop:(BOOL)keepExistingConnections;

- (BOOL)isRunning;

- (void)addWebSocket:(WebSocket *)ws;

- (NSUInteger)numberOfHTTPConnections;
- (NSUInteger)numberOfWebSocketConnections;

@end


text:
/*
 * Variable.h
 *
 *  Created on: 2014
 *      Author: jc
 */
#pragma once

#include <Node/Node.hpp>

namespace GreenZone
{
	class Fragment;

	class Variable : public Node
	{
	public:
		virtual void render(Writer * stream, Context * context) const
		{
			ExpressionParser parser(context);
			json11::Json result = parser.parse(m_expression);
			switch (result.type())
			{
			case json11::Json::NUL:
				stream->write("null");
				break;
			case json11::Json::NUMBER:
				stream->write(dbl2str(result.number_value()));
				break;
			case json11::Json::STRING:
				stream->write(result.string_value());
				break;
			case json11::Json::BOOL:
				stream->write(result.bool_value() ? "true" : "false");
				break;
			case json11::Json::ARRAY:
			case json11::Json::OBJECT:
				stream->write(result.dump());
				break;
			}
		}

		virtual void processFragment(Fragment const * fragment)
		{
			m_expression = fragment->clean();
		}

		virtual std::string name() const
		{
			return "Variable";
		}

		virtual ~Variable()
		{}

	protected:
		std::string m_expression;
	};

} /* namespace RedZone */


text:
#include <iostream>
#include <seqan/graph_types.h>
#include <seqan/graph_algorithms.h>
#include <array>
#include <seqan/basic.h>

using namespace seqan;
using namespace std;

int main() {
	typedef unsigned int TCargo;
    typedef Graph<Directed<TCargo> > TGraph;
    typedef VertexDescriptor<TGraph>::Type TVertexDescriptor;
	/*
	TGraph graph;

	TVertexDescriptor vertZero = addVertex(graph);
	TVertexDescriptor vertOne = addVertex(graph);
    TVertexDescriptor vertTwo = addVertex(graph);
    TVertexDescriptor vertThree = addVertex(graph);
    TVertexDescriptor vertFour = addVertex(graph);
    TVertexDescriptor vertFive = addVertex(graph);
	TVertexDescriptor vertSix = addVertex(graph);
	TVertexDescriptor vertSeven = addVertex(graph);

	//(1,0), (0,4), (2,1), (4,1), (5,1), (6,2), (3,2), (2,3), (7,3), (5,4), (6,5), (5,6), (7,6), (7,7)
	TVertexDescriptor con []  = {1,0,0,4,2,1,4,1,5,1,6,2,3,2,2,3,7,3,5,4,6,5,5,6,7,6, 7,7};
	int i = 14;
	addEdges(graph, con, i);

	std::cout << graph << ::std::endl;
	*/
	typedef Graph<Hmm<> > THmmGraph;
	typedef VertexDescriptor<THmmGraph>::Type THmmVertexDescriptor;
	Dna a = 'A';
	Dna c = 'C';
	Dna g = 'G';
	Dna t = 'T';
	THmmGraph h;
	THmmVertexDescriptor exon =  addVertex(h);
	emissionProbability(h, exon, a) = 0.25;
	emissionProbability(h, exon, c) = 0.25;
	emissionProbability(h, exon, g) = 0.25;
	emissionProbability(h, exon, t) = 0.25;
	THmmVertexDescriptor splice = addVertex(h);
	emissionProbability(h, splice, a) = 0.05;
	emissionProbability(h, splice, c) = 0.0;
	emissionProbability(h, splice, g) = 0.95;
	emissionProbability(h, splice, t) = 0.0;
	THmmVertexDescriptor intron = addVertex(h);
	emissionProbability(h, intron, a) = 0.4;
	emissionProbability(h, intron, c) = 0.1;
	emissionProbability(h, intron, g) = 0.1;
	emissionProbability(h, intron, t) = 0.4;
	THmmVertexDescriptor start = addVertex(h);
	assignBeginState(h, start);
	THmmVertexDescriptor end = addVertex(h);
	assignEndState(h, end);
	addEdge(h, start, exon, 1);
	addEdge(h, exon, exon, 0.9);
	addEdge(h, intron, intron, 0.9);
	addEdge(h, exon, splice, 0.1);
	addEdge(h, splice, intron, 0.1);
	addEdge(h, intron, end, 1);

	std::cout << h << ::std::endl;

	return 0;
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2012 Worthington Kilbourne Robot Club. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package us.oh.k12.wkw.robot.subsystem;

import us.oh.k12.wkw.robot.util.WkwDashboard;
import us.oh.k12.wkw.robot.util.WkwPrefs;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.util.AllocationException;

/**
 * Represents the shooter plunger.
 */
public abstract class ShooterPlunger extends ShooterAngle {

	// the spike relay (forward and reverse motor controller)
	private Relay plungerMotorRelay;
	// switch that tells us when to stop plunger motor
	private DigitalInput plungerMotorSwitch;
	// after plunger motor starts rotating,
	// the plungerMotorSwitch will close.
	private boolean haveSeenSwitchDown = false;
	// is plunger reset - so the next ball will drop in the shooter
	private boolean plungerIsReady;
	// how many times have we fired the plunger
	private int plungerFireCount = 0;

	private boolean plungerMotorSwitchState = false;

	// private double delay = -1;

	/**
	 * Null constructor - not normally used.
	 */
	protected ShooterPlunger() {
		this("ShooterPlunger");
	}

	/**
	 * The default constructor with system name.
	 *
	 * @param pName
	 *            system name.
	 */
	protected ShooterPlunger(final String pName) {

		super(pName);

		try {

			// plunger motor relay
			this.plungerMotorRelay = new Relay(WkwPrefs.getShooterPlungerControllerChannel(),
					Relay.Direction.kReverse);

			// setup the ball plunger relay.
			this.plungerMotorSwitch = new DigitalInput(WkwPrefs.getShooterPlungerSwitchChannel());

			this.haveSeenSwitchDown = false;
			this.setPlungerIsReady(true);
			this.plungerFireCount = 0;

		} catch (AllocationException anAloEx) {
			this.error("ShooterPlunger()", anAloEx);
		} catch (Exception anEx) {
			this.error("ShooterPlunger()", anEx);
		}

	}

	public void updateStatus() {

		if (null != this.plungerMotorSwitch) {
			if (this.plungerMotorSwitchState != this.plungerMotorSwitch.get()) {
				this.plungerMotorSwitchState = this.plungerMotorSwitch.get();
				WkwDashboard.setShooterPlungerSwitch(this.plungerMotorSwitchState);
			}
		}

		super.updateStatus();

	}

	private void setPlungerIsReady(final boolean pIsReady) {
		this.plungerIsReady = pIsReady;
		WkwDashboard.setShooterPlungerReady(this.plungerIsReady);
	}

	public void initFiringCycle() {
		this.haveSeenSwitchDown = false;
	}

	/**
	 * Fire the ball plunger.
	 */
	public void startPlungerMotor() {

		try {

			// make sure we have the plunger object.

			if (null != this.plungerMotorRelay) {

				this.debug("startPlungerMotor()", "Called.");

				this.plungerMotorRelay.set(Relay.Value.kOn);

				this.setPlungerIsReady(false);
				// this.delay = -1;
				this.plungerFireCount++;
				WkwDashboard.setShooterTotalFires(this.getPlungerFireCount());
			}

		} catch (Exception anEx) {
			this.error("startPlungerMotor()", anEx);
		}
	}

	public void stopPlungerMotor() {

		try {

			this.debug("firePlunger()", "Called.");

			this.plungerMotorRelay.set(Relay.Value.kOff);

			this.setPlungerIsReady(true);

		} catch (Exception anEx) {
			this.error("stopPlungerMotor()", anEx);
		}
	}

	public boolean isStopMotor() {

		boolean isStopMotor = false;

		// if (this.delay > 0) {

		// if (--this.delay <= 0) {
		// isStopMotor = true;
		// this.delay = -1;
		// }

		// } else {

		// this.debug("isStopMotor()",
		// "this.plungerMotorSwitch.get() = " + this.plungerMotorSwitch.get());
		if (this.plungerMotorSwitch.get()) {
			this.haveSeenSwitchDown = true;
			// this.debug("isStopMotor()", "this.haveSeenSwitchDown = true");
		}
		// this.haveSeenSwitchDown && !4

		isStopMotor = !this.plungerMotorSwitch.get() && this.haveSeenSwitchDown;

		this.debug("isStopMotor()", "isStopMotor=" + isStopMotor + ".");

		if (isStopMotor) { // && (this.delay < 0)
			// this.delay = 31;
			// isStopMotor = true;
			this.stopPlungerMotor();
		}

		// }

		// this.debug("isStopMotor()", "haveSeenSwitchDown=" + this.haveSeenSwitchDown
		// + ", isStopMotor=" + isStopMotor + ", delay=" + this.delay + ".");

		return isStopMotor;
	}

	/**
	 * Is the plunger reset to the not fire position?
	 *
	 * @return true if in position to fire.
	 */
	public boolean isPlungerReady() {
		return (null == this.plungerMotorRelay ? false : this.plungerIsReady);
	}

	/*
	public boolean selfTestInInitalState() {
		boolean isOk = true;

		isOk = super.selfTestInInitalState();

		if (this.isPlungerReady()) {

			this.reportSelfTestState(ShooterSystem.SYSTEM_NAME, "Ball Plunger", "Ready", true,
					"Launching system ball plunger is ready.");

		} else {

			isOk = false;
			this.reportSelfTestState(ShooterSystem.SYSTEM_NAME, "Ball Plunger", "Not Ready", false,
					"Launching system ball plunger is not ready.");

		}

		return isOk;
	}
	*/

	public int getPlungerFireCount() {
		return this.plungerFireCount;
	}

}


text:
module Spree
  module Admin
    class ZipCodesController < ResourceController
      def collection
        super.order(:value)
      end
    end
  end
end


text:
namespace thewizardplusplus {
namespace wizard_basic_2 {
namespace framework {
namespace utils {

class Converter {
public:
	template<typename Type>
	static std::string toString(Type value);
};

template<typename Type>
std::string Converter::toString(Type value) {
	std::ostringstream out;
	out << value;

	return out.str();
}

}
}
}
}
#endif


text:
package org.frekele.elasticsearch.mapping.entities.generic;

import org.frekele.elasticsearch.mapping.annotations.ElasticBinaryField;
import org.frekele.elasticsearch.mapping.annotations.ElasticBooleanField;
import org.frekele.elasticsearch.mapping.annotations.ElasticByteField;
import org.frekele.elasticsearch.mapping.annotations.ElasticCompletionField;
import org.frekele.elasticsearch.mapping.annotations.ElasticCustomJsonField;
import org.frekele.elasticsearch.mapping.annotations.ElasticDateField;
import org.frekele.elasticsearch.mapping.annotations.ElasticDateRangeField;
import org.frekele.elasticsearch.mapping.annotations.ElasticDocument;
import org.frekele.elasticsearch.mapping.annotations.ElasticDoubleField;
import org.frekele.elasticsearch.mapping.annotations.ElasticDoubleRangeField;
import org.frekele.elasticsearch.mapping.annotations.ElasticFloatField;
import org.frekele.elasticsearch.mapping.annotations.ElasticFloatRangeField;
import org.frekele.elasticsearch.mapping.annotations.ElasticGeoPointField;
import org.frekele.elasticsearch.mapping.annotations.ElasticGeoShapeField;
import org.frekele.elasticsearch.mapping.annotations.ElasticHalfFloatField;
import org.frekele.elasticsearch.mapping.annotations.ElasticIntegerField;
import org.frekele.elasticsearch.mapping.annotations.ElasticIntegerRangeField;
import org.frekele.elasticsearch.mapping.annotations.ElasticIpField;
import org.frekele.elasticsearch.mapping.annotations.ElasticIpRangeField;
import org.frekele.elasticsearch.mapping.annotations.ElasticKeywordField;
import org.frekele.elasticsearch.mapping.annotations.ElasticLongField;
import org.frekele.elasticsearch.mapping.annotations.ElasticLongRangeField;
import org.frekele.elasticsearch.mapping.annotations.ElasticNestedField;
import org.frekele.elasticsearch.mapping.annotations.ElasticObjectField;
import org.frekele.elasticsearch.mapping.annotations.ElasticPercolatorField;
import org.frekele.elasticsearch.mapping.annotations.ElasticScaledFloatField;
import org.frekele.elasticsearch.mapping.annotations.ElasticShortField;
import org.frekele.elasticsearch.mapping.annotations.ElasticTextField;
import org.frekele.elasticsearch.mapping.annotations.ElasticTokenCountField;
import org.frekele.elasticsearch.mapping.annotations.values.BoolValue;
import org.frekele.elasticsearch.mapping.annotations.values.FielddataFrequencyFilterValue;
import org.frekele.elasticsearch.mapping.annotations.values.FloatValue;
import org.frekele.elasticsearch.mapping.annotations.values.IntValue;

import java.util.Date;

@ElasticDocument("full_two")
public class FullDocumentTwoEntity {

    @ElasticBinaryField(
        suffixName = "binary",
        docValues = @BoolValue(true),
        store = @BoolValue(true))
    private String binaryValue;

    @ElasticBooleanField(
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true))
    private Boolean booleanValue;

    @ElasticByteField(
        suffixName = "byte",
        coerce = @BoolValue(true),
        boost = @FloatValue(0.2f),
        docValues = @BoolValue(true),
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private Byte byteValue;

    @ElasticCompletionField(
        suffixName = "completion",
        analyzer = "myAnalyzer",
        searchAnalyzer = "mySearchAnalyzer",
        preserveSeparators = @BoolValue(true),
        preservePositionIncrements = @BoolValue(true),
        maxInputLength = @IntValue(50)
    )
    private String completionValue;

    @ElasticDateField(
        suffixName = "date",
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        format = "basic_date_time",
        locale = "en-US",
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private Date dateValue;

    @ElasticDateRangeField(
        suffixName = "dateRange",
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        format = "basic_date_time",
        locale = "en-US",
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private Date dateRangeValue;

    @ElasticDoubleField(
        suffixName = "double",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private Double doubleValue;

    @ElasticDoubleRangeField(
        suffixName = "doubleRange",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        store = @BoolValue(true)
    )
    private Double doubleRangeValue;

    @ElasticFloatField(
        suffixName = "float",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private Float floatValue;

    @ElasticFloatRangeField(
        suffixName = "floatRange",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        store = @BoolValue(true)
    )
    private Float floatRangeValue;

    @ElasticGeoPointField(
        suffixName = "geoPoint",
        ignoreMalformed = @BoolValue(true)
    )
    private String geoPointValue;

    @ElasticGeoShapeField(
        suffixName = "geoShape",
        tree = "geohash",
        precision = "kilometers",
        treeLevels = "50m",
        strategy = "recursive",
        distanceErrorPct = @FloatValue(0.025f),
        orientation = "ccw",
        pointsOnly = @BoolValue(false)
    )
    private String geoShapeValue;

    @ElasticHalfFloatField(
        suffixName = "halfFloat",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private Float halfFloatValue;

    @ElasticIntegerField(
        suffixName = "integer",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private Integer integerValue;

    @ElasticIntegerRangeField(
        suffixName = "integerRange",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        store = @BoolValue(true)
    )
    private Integer integerRangeValue;

    @ElasticIpField(
        suffixName = "ip",
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private String ipValue;

    @ElasticIpRangeField(
        suffixName = "ipRange",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        store = @BoolValue(true)
    )
    private String ipRangeValue;

    @ElasticKeywordField(
        suffixName = "keyword",
        analyzer = "myAnalyzer",
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        eagerGlobalOrdinals = @BoolValue(true),
        ignoreAbove = @IntValue(350),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        indexOptions = "docs",
        norms = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true),
        similarity = "BM25",
        normalizer = "my_normalizer"
    )
    private String keywordValue;

    @ElasticLongField(
        suffixName = "long",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private Long longValue;

    @ElasticLongRangeField(
        suffixName = "longRange",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        store = @BoolValue(true)
    )
    private Long longRangeValue;

    @ElasticPercolatorField(
        suffixName = "percolator"
    )
    private String percolatorValue;

    @ElasticScaledFloatField(
        suffixName = "scaledFloat",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true),
        scalingFactor = @IntValue(100)
    )
    private Float scaledFloatValue;

    @ElasticShortField(
        suffixName = "short",
        coerce = @BoolValue(true),
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        ignoreMalformed = @BoolValue(true),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private Short shortValue;

    @ElasticTextField(
        suffixName = "text",
        analyzer = "myAnalyzer",
        boost = @FloatValue(1),
        eagerGlobalOrdinals = @BoolValue(true),
        fielddata = @BoolValue(true),
        fielddataFrequencyFilter = @FielddataFrequencyFilterValue(
            min = @FloatValue(0.001f),
            max = @FloatValue(0.1f),
            minSegmentSize = @IntValue(500)
        ),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        indexOptions = "",
        norms = @BoolValue(true),
        positionIncrementGap = @IntValue(100),
        store = @BoolValue(true),
        searchAnalyzer = "mySearchAnalyzer",
        searchQuoteAnalyzer = "my_analyzer",
        similarity = "BM25",
        termVector = "no",
        copyTo = {"anotherField"}
    )
    private String textValue;

    @ElasticTokenCountField(
        suffixName = "tokenCount",
        analyzer = "myAnalyzer",
        enablePositionIncrements = @BoolValue(true),
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        index = @BoolValue(true),
        includeInAll = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true)
    )
    private String tokenCountValue;

    @ElasticNestedField(
        dynamic = @BoolValue(true),
        includeInAll = @BoolValue(true)
    )
    private InnerDocumentEntity nestedValue;

    @ElasticObjectField(
        dynamic = @BoolValue(true),
        enabledJson = @BoolValue(true),
        includeInAll = @BoolValue(true)
    )
    private InnerDocumentEntity objectValue;

    @ElasticCustomJsonField(
        path = "/custom/mapping/test-custom-field.json",
        classLoader = ClassLoader.class)
    private String customValue;

    @ElasticTextField(
        suffixName = "text",
        analyzer = "myAnalyzer",
        boost = @FloatValue(1),
        eagerGlobalOrdinals = @BoolValue(true),
        fielddata = @BoolValue(true),
        fielddataFrequencyFilter = @FielddataFrequencyFilterValue(
            min = @FloatValue(0.001f),
            max = @FloatValue(0.1f),
            minSegmentSize = @IntValue(500)
        ),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        indexOptions = "",
        norms = @BoolValue(true),
        positionIncrementGap = @IntValue(100),
        store = @BoolValue(true),
        searchAnalyzer = "mySearchAnalyzer",
        searchQuoteAnalyzer = "my_analyzer",
        similarity = "BM25",
        termVector = "no",
        copyTo = {"anotherField"}
    )
    @ElasticKeywordField(
        suffixName = "keyword",
        analyzer = "myAnalyzer",
        boost = @FloatValue(1),
        docValues = @BoolValue(true),
        eagerGlobalOrdinals = @BoolValue(true),
        ignoreAbove = @IntValue(350),
        includeInAll = @BoolValue(true),
        index = @BoolValue(true),
        indexOptions = "docs",
        norms = @BoolValue(true),
        nullValue = "NULL",
        store = @BoolValue(true),
        similarity = "BM25",
        normalizer = "my_normalizer"
    )
    @ElasticCompletionField(
        suffixName = "completion",
        analyzer = "myAnalyzer",
        searchAnalyzer = "mySearchAnalyzer",
        preserveSeparators = @BoolValue(true),
        preservePositionIncrements = @BoolValue(true),
        maxInputLength = @IntValue(50)
    )
    private String multiFieldValue;

    public FullDocumentTwoEntity() {
    }
}


text:
<?php

return array(
    'drivers' => array(
        'c5_pdo_mysql' => '\Concrete\Core\Database\Driver\PDOMySqlConcrete5\Driver',
    ),

    /*
     * The location of the doctrine Proxy Classes
     */
    'proxy_classes' => DIR_APPLICATION . '/config/doctrine/proxies',

    /*
     * Paths to exclude from the doctrine proxy classes
     */
    'proxy_exclusions' => array(
        DIR_BASE_CORE . '/' . DIRNAME_CLASSES . '/Support/',
    ),
);


text:
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError

from collections import defaultdict
from datetime import datetime, timedelta
import json
from urllib.request import urlopen

from proposal.models import Importer, get_importer_schema

from jsonschema import Draft4Validator

def schema_path_str(path):
    return "".join(f".{c}" if isinstance(c, str) else f"[{c}]" for c in path)

class Command(BaseCommand):
    help = "Validate that the importers conform to the JSON schema"

    def handle(self, *args, **options):
        err = lambda m: self.stderr.write(self.style.ERROR(m) + "\n")
        succ = lambda m: self.stdout.write(self.style.SUCCESS(m) + "\n")
        when = datetime.now() - timedelta(days=30)
        validator = Draft4Validator(get_importer_schema())

        for importer in Importer.objects.all():
            errors = defaultdict(list)
            for error in validator.iter_errors(importer.updated_since(when)):
                errors[schema_path_str(error.absolute_schema_path)].append(error)

            if errors:
                err(f"{len(errors)} error(s) in {importer}:")
                for path, errs in errors.items():
                    error = errs[0]
                    repeats = f" ({len(errs)} repeats)" if len(errs) > 1 else ""
                    err(f"at {path}{repeats}:\n{error.message}\n")
            else:
                succ(f"{importer} validated successfully!")


text:
https://github.com/ring-clojure/ring/

## Usage

https://github.com/ring-clojure/ring/wiki

lein new hello-world
cd hello-world
lein repl

1.core

(use 'hello-world.core)

2.test

(use 'hello-world.test)

or

lein run -m hello-world.core


text:
<?xml version="1.0"?>

<metadata
    xmlns="http://example.org/myapp/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://purl.org/dc/elements/1.1/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:dcterms="http://purl.org/dc/terms/">

	<dc:coverage>Democratic Republic of the Congo</dc:coverage>
	<dc:creator>Oth, Adrien</dc:creator>
	<dc:identifier>Kivu Seismological Network (KivuSnet)</dc:identifier>
	<dc:publisher>Deutsches GeoForschungsZentrum GFZ</dc:publisher>
	<dc:subject>Broadband seismic waveforms</dc:subject>
	<dcterms:created>2014-04-10</dcterms:created>
	<dcterms:spatial>-3.4 28.5 -1.2 30.0</dcterms:spatial>
</metadata>


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

using System.IO;

namespace WOEmu.Terrain
{
    public static class Map
    {
        public static void initMap()
        {
            if (!File.Exists("maps/MAPS.TXT"))
            {
                throw new Exception("Unable to find MAPS.TXT file!");
            }

            FileStream fs = File.Open("maps/MAPS.TXT", FileMode.Open);
            StreamReader reader = new StreamReader(fs);

            int xSize = int.Parse(reader.ReadLine());
            int ySize = int.Parse(reader.ReadLine());

            WO.Core.Logger.Logger.printInfo("Map size: " + xSize + ", " + ySize);

            System.Console.Write("Loading map: ");
            mapTerrain = new Terrain[xSize][];

            for (int x = 0; x < xSize; x++)
            {
                mapTerrain[x] = new Terrain[ySize];
                for (int y = 0; y < ySize; y++)
                {
                    mapTerrain[x][y] = HeightMapLoader.Load("maps/H" + x + "-" + y + ".bmp", (short)(x * 64), (short)(y * 64));
                    TileMapLoader.Load(mapTerrain[x][y], (short)x, (short)y);
                    System.Console.Write(".");
                }
            }

            System.Console.WriteLine("DONE!");

            mapX = xSize;
            mapY = ySize;
        }

        public static void sendAll(Client c)
        {
            for(int x=0;x<mapX;x++)
                for (int y = 0; y < mapY; y++)
                {
                    Packets.TerrainPacket.SendTo(c, mapTerrain[x][y]);
                }
        }

        public static int mapX;
        public static int mapY;
        public static Terrain[][] mapTerrain;
    }
}


text:
#include "catch.hpp"

#include <jemallocator/jemallocator.hpp>

namespace je = jemallocator;
namespace jepolicy = jemallocator::jepolicy;

TEST_CASE("jemallocator behaves as a standard allocator", "[basic]") {
	SECTION("constructor") {
		je::jemallocator<int, jepolicy::empty::policy> test_1;

		SECTION("copy construct from same type") {
			je::jemallocator<int, jepolicy::empty::policy> test_2(test_1);
		}
		SECTION("copy construct from different type") {
			je::jemallocator<char, jepolicy::empty::policy> test_2(test_1);
		}
	}
	SECTION("allocation and deallocation") {
		je::jemallocator<int, jepolicy::empty::policy> alloc;

		SECTION("allocate and deallocate") {
			int* ptr = alloc.allocate(1);
			REQUIRE(ptr != nullptr);

			SECTION("address") {
				REQUIRE(alloc.address(*ptr) == ptr);
			}
			SECTION("construct and destroy same type") {
				alloc.construct(&ptr[0], 1337);
				REQUIRE(ptr[0] == 1337);
				alloc.destroy(&ptr[0]);
			}
			SECTION("construct and destroy different type") {
				alloc.construct((char*)ptr, 'c');
				REQUIRE((char)*ptr == 'c');
				alloc.destroy((char*)ptr);
			}
			alloc.deallocate(ptr, 1);
		}
		SECTION("max size") {
			REQUIRE(alloc.max_size() == (size_t(0) - size_t(1)) / sizeof(int));
		}
	}
	SECTION("equality") {
		je::jemallocator<int, jepolicy::empty::policy> test_1;

		SECTION("instances should be interchangeable") {
			je::jemallocator<char, jepolicy::empty::policy> test_2;
			REQUIRE(test_1 == test_2);
		}
		SECTION("specialisations should be interchangeable") {
			je::jemallocator<long, jepolicy::arena<0>::policy> test_2;
			REQUIRE(test_1 == test_2);
		}
	}
}


text:
#pragma once

#include <map>
#include <memory>

#include "modules/perception/base/blob.h"
#include "modules/perception/base/box.h"

namespace apollo {
namespace perception {
namespace base {

enum class Color {
  NONE = 0x00,
  GRAY = 0x01,
  RGB = 0x02,
  BGR = 0x03,
};

const std::map<Color, int> kChannelsMap{
    {Color::GRAY, 1}, {Color::RGB, 3}, {Color::BGR, 3}};

/**
 * @brief A wrapper around Blob holders serving as the basic
 *        computational unit for images.
 *
 * TODO(dox): more thorough description.
 */
class Image8U {
 public:
  Image8U()
      : rows_(0),
        cols_(0),
        type_(Color::NONE),
        channels_(0),
        width_step_(0),
        blob_(nullptr),
        offset_(0) {}

  Image8U(int rows, int cols, Color type, std::shared_ptr<Blob<uint8_t>> blob,
          int offset = 0)
      : rows_(rows), cols_(cols), type_(type), blob_(blob), offset_(offset) {
    channels_ = kChannelsMap.at(type);
    CHECK_EQ(blob_->num_axes(), 3);
    CHECK_EQ(blob_->shape(2), channels_);
    CHECK_LE(offset_ + blob_->offset({rows - 1, cols - 1, channels_ - 1}),
             blob_->count());
    width_step_ = blob_->offset({1, 0, 0}) * static_cast<int>(sizeof(uint8_t));
  }

  Image8U(int rows, int cols, Color type)
      : rows_(rows), cols_(cols), type_(type), offset_(0) {
    channels_ = kChannelsMap.at(type);
    blob_.reset(new Blob<uint8_t>({rows_, cols_, channels_}));
    width_step_ = blob_->offset({1, 0, 0}) * static_cast<int>(sizeof(uint8_t));
  }

  Image8U(const Image8U &src)
      : rows_(src.rows_),
        cols_(src.cols_),
        type_(src.type_),
        channels_(src.channels_),
        width_step_(src.width_step_),
        blob_(src.blob_),
        offset_(src.offset_) {}

  Image8U &operator=(const Image8U &src) {
    this->rows_ = src.rows_;
    this->cols_ = src.cols_;
    this->type_ = src.type_;
    this->channels_ = src.channels_;
    this->width_step_ = src.width_step_;
    this->blob_ = src.blob_;
    this->offset_ = src.offset_;
    return *this;
  }

  ~Image8U() {}

  uint8_t *mutable_cpu_data() { return mutable_cpu_ptr(0); }

  uint8_t *mutable_gpu_data() { return mutable_gpu_ptr(0); }

  const uint8_t *cpu_data() const { return cpu_ptr(0); }

  const uint8_t *gpu_data() const { return gpu_ptr(0); }

  const uint8_t *cpu_ptr(int row = 0) const {
    return blob_->cpu_data() + blob_->offset({row, 0, 0}) + offset_;
  }

  const uint8_t *gpu_ptr(int row = 0) const {
    return blob_->gpu_data() + blob_->offset({row, 0, 0}) + offset_;
  }

  uint8_t *mutable_cpu_ptr(int row = 0) {
    return blob_->mutable_cpu_data() + blob_->offset({row, 0, 0}) + offset_;
  }

  uint8_t *mutable_gpu_ptr(int row = 0) {
    return blob_->mutable_gpu_data() + blob_->offset({row, 0, 0}) + offset_;
  }

  Color type() const { return type_; }
  int rows() const { return rows_; }
  int cols() const { return cols_; }
  int channels() const { return channels_; }
  int width_step() const { return width_step_; }
  // @brief: returns the total number of pixels.
  int total() const { return rows_ * cols_ * channels_; }

  Image8U operator()(const Rect<int> &roi) {
    int offset = offset_ + blob_->offset({roi.y, roi.x, 0});
    // return Image8U(roi.height, roi.width, type_, blob_, offset);
    return Image8U(roi.height, roi.width, type_, blob_, offset);
  }

  std::shared_ptr<Blob<uint8_t>> blob() { return blob_; }

  // DONOT return `std::shared_ptr<const Blob<uint8_t>> &` or `const std::... &`
  std::shared_ptr<const Blob<uint8_t>> blob() const { return blob_; }

 protected:
  int rows_;
  int cols_;
  Color type_;
  int channels_;
  int width_step_;
  std::shared_ptr<Blob<uint8_t>> blob_;
  int offset_;
};  // class Image8U

typedef std::shared_ptr<Image8U> Image8UPtr;
typedef std::shared_ptr<const Image8U> Image8UConstPtr;

}  // namespace base
}  // namespace perception
}  // namespace apollo


text:
package models

//User : For /api/users
type User struct {
	Username string `json:"username"`
	RealName string `json:"realname"`
	Password string `json:"password"`
	Email    string `json:"email"`
	Comment  string `json:"comment"`
}

//ExistingUser : For GET /api/users
type ExistingUser struct {
	User
	ID int `json:"user_id"`
}


text:
angular.module('orderCloud')
    .factory('ocAddressSelect', OrderCloudAddressSelectService)
;

function OrderCloudAddressSelectService($uibModal, OrderCloudSDK) {
    var service = {
        Open: _open
    };

    function _open(type) {
        return $uibModal.open({
            templateUrl: 'checkout/templates/addressSelect.modal.html',
            controller: 'AddressSelectCtrl',
            controllerAs: 'addressSelect',
            backdrop: 'static',
            size: 'md',
            resolve: {
                Addresses: function(OrderCloudSDK) {
                    var options = {
                        page: 1,
                        pageSize: 100
                    };

                    if (type == 'shipping') {
                        options.filters = {Shipping: true};
                    } else if (type == 'billing') {
                        options.filters = {Billing: true};
                    }

                    return OrderCloudSDK.Me.ListAddresses(options);
                }
            }
        }).result;
    }

    return service;
}


text:
DEBUG = False

# Number of players in the game. Should always be greater than or equal to one.
NUM_PLAYERS = 1


text:
package com.example.radiobutton_01;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MyActivity extends Activity {
    private RadioGroup rg;
    private Button btn;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        rg = (RadioGroup)findViewById(R.id.rg);
        btn = (Button)findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int len = rg.getChildCount();
                String msg = "";
                for(int i=0;i<len;i++) {
                    RadioButton rb = (RadioButton)rg.getChildAt(i);
                    if(rb.isChecked()) {
                        msg = rb.getText().toString();
                        break;
                    }
                }

                Toast.makeText(MyActivity.this,msg,Toast.LENGTH_SHORT).show();
            }
        });
    }
}


text:
<?php

namespace NelmioApiDocBundle\Tests\Command;

use Nelmio\ApiDocBundle\Tests\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\ApplicationTester;
use Symfony\Component\PropertyAccess\PropertyAccess;

class DumpCommandTest extends WebTestCase
{
    /**
     * @dataProvider viewProvider
     *
     * @param string $view                 Command view option value
     * @param array  $expectedMethodsCount Expected resource methods count
     * @param array  $expectedMethodValues Expected resource method values
     */
    public function testDumpWithViewOption($view, array $expectedMethodsCount, array $expectedMethodValues)
    {
        $this->getContainer();

        $application = new Application(static::$kernel);
        $application->setCatchExceptions(false);
        $application->setAutoExit(false);

        $tester = new ApplicationTester($application);

        $input = array(
            'command' => 'api:doc:dump',
            '--view' => $view,
            '--format' => 'json',
        );
        $tester->run($input);

        $display = $tester->getDisplay();

        $this->assertJson($display);

        $json = json_decode($display);

        $accessor = PropertyAccess::createPropertyAccessor();

        foreach ($expectedMethodsCount as $propertyPath => $expectedCount) {
            $this->assertCount($expectedCount, $accessor->getValue($json, $propertyPath));
        }

        foreach ($expectedMethodValues as $propertyPath => $expectedValue) {
            $this->assertEquals($expectedValue, $accessor->getValue($json, $propertyPath));
        }
    }

    /**
     * @return array
     */
    public static function viewProvider()
    {
        return array(
            'test' => array(
                'test',
                array(
                    '/api/resources' => 1,
                ),
                array(
                    '/api/resources[0].method' => 'GET',
                    '/api/resources[0].uri' => '/api/resources.{_format}',
                )
            ),
            'premium' => array(
                'premium',
                array(
                    '/api/resources' => 2,
                ),
                array(
                    '/api/resources[0].method' => 'GET',
                    '/api/resources[0].uri' => '/api/resources.{_format}',
                    '/api/resources[1].method' => 'POST',
                    '/api/resources[1].uri' => '/api/resources.{_format}',
                )
            ),
            'default' => array(
                'default',
                array(
                    '/api/resources' => 4,
                ),
                array(
                    '/api/resources[0].method' => 'GET',
                    '/api/resources[0].uri' => '/api/resources.{_format}',
                    '/api/resources[1].method' => 'POST',
                    '/api/resources[1].uri' => '/api/resources.{_format}',
                    '/api/resources[2].method' => 'DELETE',
                    '/api/resources[2].uri' => '/api/resources/{id}.{_format}',
                    '/api/resources[3].method' => 'GET',
                    '/api/resources[3].uri' => '/api/resources/{id}.{_format}',
                )
            ),
        );
    }
}


text:
import React from 'react'
import Snippet from '../../modules/Snippet'
import { Alert } from 'react-ions/lib/components/Alerts'
import buttonExampleSnippet from '!raw!./Buttons/ExampleButtonDefault'
import inputExampleSnippet from '!raw!./Input/ExampleInputOptClass'
import snippetStyles from 'private/css/snippet'
import styles from 'private/css/content'

const fontCss = 'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"'

const ComponentsPage = () => (

Installation, Prerequisites and Basic Usage

React{ions} is a suite of React components that implement Ambassador's Design and UX patterns. They are designed to be re-usable and composable across large-scale web applications. They are powered by CSS Modules and integrate with your webpack workflow, or any other module bundler.

Installation

        <Snippet markup='npm install --save react-ions' />

Prerequisites

React{ions} currently requires React 15.1+

We use CSS Modules by default to import stylesheets written in SASS. In case you want to import the components already bundled with CSS, your module bundler should be able to require these SASS modules.

To allow your app to render SCSS and import CSS into JavaScript, you'll need the following: node-sass sass-loader & style-loader

Basic Usage

In this minimal example, we import a Button with styles already bundled:

        <Snippet markup={buttonExampleSnippet} />
        <Alert type="info" optClass={styles['alert-override']}>If you are not seeing any styles when you load a component, please make sure your project configuration (Webpack, etc.) is using CSS modules to process SASS.</Alert>

Example Webpack Config

Here is an example Rect{ions} Webpack app to get you started.

Customizing components

Each React{ion} component exposes an optClass prop, to enable style overrides.

        <Snippet markup={inputExampleSnippet} />

You can now override Input styles with the .input-overrides class.

Fonts

This site and our components are designed to use Promima Nova, which we own under license.

If you do not own Proxima Nova, the font-family will render the following:

        <Snippet markup={fontCss} />

)

export default ComponentsPage


text:
layout: default
title: WAGG News – About
---

About

World Aggregate News, or just WAGG News for short, was born out of the idea that everyone should be able to access reliable news that they care about, without having to sift through long articles. We collect news from hundreds of sources across the internet and around the world and compress their stories into bulletins under 140 characters. Our sources range from wire services like AP, Reuters, and AFP, to news organizations like NBC, BBC, CBC, and ABC, to people on the ground where news is breaking and ongoing.

We collect news from everywhere on the internet; Twitter, Facebook, news articles, anywhere. We also gather media from people on the ground as events occur with services like Vine and Instagram.

We don't believe it is fair to take credit for the work of other organizations, and for that reason, all the news and media we share is attributed, unless it is exclusively ours. We also believe it's unreasonable to be biased, and as such we pride ourselves on showing all the sides of a story as much possible.

Team

Braeden Mayer: Managing Editor, Co-founder, Canada Correspondent

Kashif Osman: Managing Editor, Co-founder, United States Correspondent

Rory Tait: Social News Editor, Australia Correspondent

Adam Lewes: Social News Editor, Britain Correspondent, Gif-Maker-in-Chief

We are looking for Social News Editors. Apply here.


text:
/** \file
 * \brief
 * Headerfile for nicdrv.c
 */

#ifndef _nicdrvh_
#define _nicdrvh_

#ifdef __cplusplus
extern "C"
{
#endif

#include <pthread.h>

/** pointer structure to Tx and Rx stacks */
typedef struct
{
   /** socket connection used */
   int         *sock;
   /** tx buffer */
   ec_bufT     (*txbuf)[EC_MAXBUF];
   /** tx buffer lengths */
   int         (*txbuflength)[EC_MAXBUF];
   /** temporary receive buffer */
   ec_bufT     *tempbuf;
   /** rx buffers */
   ec_bufT     (*rxbuf)[EC_MAXBUF];
   /** rx buffer status fields */
   int         (*rxbufstat)[EC_MAXBUF];
   /** received MAC source address (middle word) */
   int         (*rxsa)[EC_MAXBUF];
} ec_stackT;

/** pointer structure to buffers for redundant port */
typedef struct
{
   ec_stackT   stack;
   int         sockhandle;
   /** rx buffers */
   ec_bufT rxbuf[EC_MAXBUF];
   /** rx buffer status */
   int rxbufstat[EC_MAXBUF];
   /** rx MAC source address */
   int rxsa[EC_MAXBUF];
   /** temporary rx buffer */
   ec_bufT tempinbuf;
} ecx_redportt;

/** pointer structure to buffers, vars and mutexes for port instantiation */
typedef struct
{
   ec_stackT   stack;
   int         sockhandle;
   /** rx buffers */
   ec_bufT rxbuf[EC_MAXBUF];
   /** rx buffer status */
   int rxbufstat[EC_MAXBUF];
   /** rx MAC source address */
   int rxsa[EC_MAXBUF];
   /** temporary rx buffer */
   ec_bufT tempinbuf;
   /** temporary rx buffer status */
   int tempinbufs;
   /** transmit buffers */
   ec_bufT txbuf[EC_MAXBUF];
   /** transmit buffer lenghts */
   int txbuflength[EC_MAXBUF];
   /** temporary tx buffer */
   ec_bufT txbuf2;
   /** temporary tx buffer length */
   int txbuflength2;
   /** last used frame index */
   int lastidx;
   /** current redundancy state */
   int redstate;
   /** pointer to redundancy port and buffers */
   ecx_redportt *redport;
   pthread_mutex_t getindex_mutex;
   pthread_mutex_t tx_mutex;
   pthread_mutex_t rx_mutex;
} ecx_portt;

extern const uint16 priMAC[3];
extern const uint16 secMAC[3];

#ifdef EC_VER1
extern ecx_portt     ecx_port;
extern ecx_redportt  ecx_redport;

int ec_setupnic(const char * ifname, int secondary);
int ec_closenic(void);
void ec_setbufstat(int idx, int bufstat);
int ec_getindex(void);
int ec_outframe(int idx, int sock);
int ec_outframe_red(int idx);
int ec_waitinframe(int idx, int timeout);
int ec_srconfirm(int idx,int timeout);
#endif

void ec_setupheader(void *p);
int ecx_setupnic(ecx_portt *port, const char * ifname, int secondary);
int ecx_closenic(ecx_portt *port);
void ecx_setbufstat(ecx_portt *port, int idx, int bufstat);
int ecx_getindex(ecx_portt *port);
int ecx_outframe(ecx_portt *port, int idx, int sock);
int ecx_outframe_red(ecx_portt *port, int idx);
int ecx_waitinframe(ecx_portt *port, int idx, int timeout);
int ecx_srconfirm(ecx_portt *port, int idx,int timeout);

#ifdef __cplusplus
}
#endif

#endif


text:
.. _reconstruction:

object_recognition_reconstruction: 3D Object Reconstruction
###########################################################

``Reconstruction`` provides a utility to create a 3d reconstruction of an object. For now, it creates an approximate untextured mesh from captured data, that is good enough for grasping. The algorithm simply merges the depth imags from several views and smoothes them a bit. Nothing smarted is done.

Install dependencies
********************

First install meshlab as it is used to go from the aggregation of depth maps to a mesh:

   .. code-block:: sh

      sudo apt-get install meshlab

Command Line
************

From the command line, you want to execute the following command to compute all meshes and commit them to the local DB:

.. toggle_table::
    :arg1: Non-ROS
    :arg2: ROS

.. toggle:: Non-ROS

   .. code-block:: sh

      ./apps/mesh_object --all --visualize --commit

.. toggle:: ROS

   .. code-block:: sh

      rosrun object_recognition_reconstruction mesh_object --all --visualize --commit

Or tune your parameters using the appropriate command line arguments:

.. program-output:: ../../apps/mesh_object --help
    :prompt:
    :in_srcdir:

Web Interface
*************

Reconstruction also provides a web interface to visualize the different meshes. In your build folder, just run:

.. code-block:: sh

    make or_web_ui

You can then visualize the meshes here: `http://localhost:5984/or_web_ui/_design/viewer/index.html <http://localhost:5984/or_web_ui/_design/viewer/index.html>`_

Tips
****

To create a textured mesh from a colored point cloud in meshlab: http://www.youtube.com/watch?v=JzmODsVQV7w


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Module chef_keygen_cache</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc">

Overview

Module chef_keygen_cache

Description

Function Index

Function Details

chef_keygen_cache Precreates RSA key pairs and servers them when you ask.

Behaviours: <tt>gen_server</tt>.

Description

chef_keygen_cache Precreates RSA key pairs and servers them when you ask.

chef_keygen_cache is a gen_server that keeps a configurable number of RSA key pairs on
  hand for fast delivery. You can configure how many workers are used to replinish the key
  cache when it drops below the desired size. If you request a key when the cache is empty,
  the atom keygen_timeout is returned immediately.

  You can control the behavior of the key cache using the following app config keys:

keygen_cache_size: The number of keys to store in the cache

keygen_start_size: The number of keys that must be available in the cache before
  completing startup and accepting requests. Cache startup blocks until keygen_start_size
  keys are available in the cache.

keygen_timeout: Time allowed for the external key generation command (openssl). A
  timeout atom is returned if the command takes longer than Timeout milliseconds. This
  value is also used to bound the time allowed for the cache gen_server to respond to key
  request calls

keygen_cache_workers: The number of workers available to generate key pairs. This
  should never be larger than the number of logical CPUs. Defaults to larger of 1 and half
  the number of logical processors as reported by erlang:system_info(logical_processors)

keygen_size: Size in bits of the RSA keys to generate. Defaults to 2048. Mostly used
  to speed up testing.

Function Index

code_change/3

get_key_pair/0	Retrieve an RSA key pair from the cache.

handle_call/3

handle_cast/2

handle_info/2

init/1

start_link/0

status/0	Return a proplist of status information about the state of the key cache.

stop/0

terminate/2

update_config/0	Instruct the cache to reread app config values.

Function Details

code_change/3

<tt>code_change(OldVsn, State, Extra) -> any()</tt>

get_key_pair/0

<tt>get_key_pair() -> {PublicKey::binary(), PrivateKey::binary()} | keygen_timeout</tt>

Retrieve an RSA key pair from the cache.

  The return value is a tuple of the form {PublicKey, PrivateKey} where each element is a
  binary containing the PEM encoded key. If no keys are available in the cache or if the
  cache takes longer than the timeout value specified in app config {chef_authn,
  kegen_timeout, Timeout}, then the atom keygen_timeout is returned.

handle_call/3

<tt>handle_call(Request, From, State) -> any()</tt>

handle_cast/2

<tt>handle_cast(Request, State) -> any()</tt>

handle_info/2

<tt>handle_info(Key_pair, State) -> any()</tt>

init/1

<tt>init(X1) -> any()</tt>

start_link/0

<tt>start_link() -> any()</tt>

status/0

<tt>status() -> [{atom(), term()}]</tt>

Return a proplist of status information about the state of the key cache.

stop/0

<tt>stop() -> any()</tt>

terminate/2

<tt>terminate(Reason, State) -> any()</tt>

update_config/0

<tt>update_config() -> ok</tt>

Instruct the cache to reread app config values.

Overview

Generated by EDoc, Jul 9 2014, 00:12:49.


text:
package com.bsu.sed.service.process;

import com.bsu.sed.model.SystemAttributeKey;
import com.bsu.sed.model.persistent.Content;
import com.bsu.sed.model.persistent.News;
import com.bsu.sed.model.persistent.NewsUrl;
import com.bsu.sed.parser.RssParser;
import com.bsu.sed.service.MailService;
import com.bsu.sed.service.SystemAttributeService;
import com.bsu.sed.service.UserService;
import com.bsu.sed.service.builder.MailBuilder;
import com.bsu.sed.service.news.NewsService;
import com.bsu.sed.service.news.NewsUrlService;
import com.bsu.sed.utils.ParseUtils;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.FeedException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.InterruptableJob;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.UnableToInterruptJobException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author gbondarchuk
 */
@Component
public class NewsUpdateProcess extends ProcessExecutor {

    private static final Log log = LogFactory.getLog(NewsUpdateProcess.class);

    @Autowired
    private NewsUrlService newsUrlService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private UserService userService;
    @Autowired
    private SystemAttributeService systemAttributeService;
    @Autowired
    private MailService mailService;

    @Override
    protected void execute() throws InterruptedException {
        log.info("New Update Process started.");
        int count = 0;
        List<News> allNews = new ArrayList<>();
        int newShowingDays = systemAttributeService.getInt(SystemAttributeKey.NEWS_SHOWING_PERIOD);
        Date from = DateUtils.addDays(new Date(), -newShowingDays);
        List<NewsUrl> urls = newsUrlService.getEnabled();
        for (NewsUrl url : urls) {
            try {
                log.info("Retrieving news from " + url.getUrl());
                SyndFeed feed = RssParser.parse(url.getUrl());
                List<News> news = findNews(feed, ParseUtils.split(url.getSearchWords()), from);
                allNews.addAll(news);

                newsService.create(news);

                int size = news.size();
                count += size;
                log.info("Retrieved " + size + " news from " + url.getUrl());
                url.setLastSearch(new Date());
                newsUrlService.update(url);
            } catch (RuntimeException | IOException | FeedException e) {
                log.error(e.getMessage(), e);
            }
        }
        log.info("New Update Process finished. " + count + " news were uploaded from " + from);

        if (CollectionUtils.isNotEmpty(allNews)) {
            List<String> subscribers = userService.getNewsSubscribers();

            mailService.sendNewsToSubscribers(allNews, subscribers);
        }
    }

    private List<News> findNews(SyndFeed feed, List<String> searchWords, Date from) {
        if (feed == null) {
            return new ArrayList<>();
        }
        List<News> newsList = new ArrayList<>();
        for (Object object : feed.getEntries()) {
            SyndEntry entry = (SyndEntry) object;
            if (isSuitable(entry, searchWords, from)) {
                News news = convert(entry);
                newsList.add(news);
            }
        }
        return newsList;
    }

    private boolean isSuitable(SyndEntry entry, List<String> searchWords, Date from) {
        Date publishedDate = entry.getPublishedDate();
        if (publishedDate == null) {
            return false;
        }
        if (publishedDate.before(from)) {
            return false;
        }

        String text = entry.getTitle();
        if (newsService.exists(text)) {
            return false;
        }

        SyndContent syndContent = entry.getDescription();
        String description = syndContent.getValue();

        return meets(text, searchWords) || meets(description, searchWords);
    }

    private News convert(SyndEntry entry) {
        News news = new News();
        news.setCreator(userService.getSystem());

        Content content = new Content();
        content.setName(entry.getTitle());
        String title = entry.getTitle();
        content.setName(title);

        SyndContent syndContent = entry.getDescription();
        String description = syndContent.getValue();
        news.setSimpleText(description);

        Date publishedDate = entry.getPublishedDate();
        news.setCreatedDate(publishedDate);

        List enclosures = entry.getEnclosures();
        List<String> imageUrls = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(enclosures)) {
            for (Object value : enclosures) {
                SyndEnclosure enclosure = (SyndEnclosure) value;
                imageUrls.add(enclosure.getUrl());
            }
            news.setPhoto(StringUtils.join(imageUrls, ","));
        }

        List syndCategories = entry.getCategories();
        if (CollectionUtils.isNotEmpty(syndCategories)) {
            SyndCategory syndCategory = (SyndCategory) syndCategories.get(0);
            String category = syndCategory.getName();
            news.setCategory(category);
        }

        String link = "";
        if (StringUtils.isNotBlank(entry.getLink())) {
            link = createHtmlLink(entry.getLink());
        }

        if (StringUtils.isNotBlank(news.getPhoto())) {
            content.setContent(link.getBytes(Charset.forName("UTF-8")));
        } else {
            content.setContent((description + " " + link).getBytes(Charset.forName("UTF-8")));
        }

        news.setContent(content);
        return news;
    }

    private boolean meets(String text, List<String> searchWords) {
        for (String word : searchWords) {
            if (text.toLowerCase().contains(word.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    private String createHtmlLink(String url) {
        return "" + url + "";
    }
}


text:
package com.appnexus.opensdk.transitionanimation;

import android.view.animation.Animation;

public interface Transition {
    /**
     * Get the in animation for a view animator
     *
     * @return animation
     */
    public Animation getInAnimation();

    /**
     * Get the out animation for a view animator
     *
     * @return animation
     */
    public Animation getOutAnimation();
}


text:
class CreateQuizQuestionAnswers < ActiveRecord::Migration
  def self.up
    create_table :quiz_question_answers do |t|
      t.column :quiz_question_id, :integer, :null => false
      t.column :position, :integer
      t.column :answer_text, :text
      t.column :correct, :boolean, :null => false, :default => false

      t.timestamps
    end
  end

  def self.down
    drop_table :quiz_question_answers
  end
end


text:
Filter by library:

        <select class="w-50-ns" id="search-library" name="library">
            <option></option>
            <option>Aldeburgh Library</option>
            <option>Beccles Library</option></option>
            <option>Brandon Library</option>
            <option>Broomhill Library</option>
            <option>Bungay Community Library</option>
            <option>Bury St Edmunds Library</option>
            <option>Capel St Mary Library</option>
            <option>Chantry Library</option>
            <option>Clare Library</option>
            <option>Debenham Library</option>
            <option>Elmswell Library</option>
            <option>Eye Library</option>
            <option>Felixstowe Library</option>
            <option>Framlingham Library</option>
            <option>Gainsborough Community Library</option>
            <option>Glemsford Library</option>
            <option>Great Cornard Library</option>
            <option>Hadleigh Library</option>
            <option>Halesworth Library</option>
            <option>Haverhill Library</option>
            <option>Ipswich County Library</option>
            <option>Ixworth Library</option>
            <option>Kedington Library</option>
            <option>Kesgrave Library</option>
            <option>Kessingland Library</option>
            <option>Lakenheath Library</option>
            <option>Lavenham Library</option>
            <option>Leiston Library</option>
            <option>Long Melford Library</option>
            <option>Lowestoft Library</option>
            <option>Mildenhall Library</option>
            <option>Needham Market Library</option>
            <option>Newmarket Library</option>
            <option>Oulton Broad Library</option>
            <option>Rosehill Library</option>
            <option>Rushmere (Suffolk Libraries Local)</option>
            <option>Saxmundham Library</option>
            <option>Shotley (Suffolk Libraries Local)</option>
            <option>Southwold Library</option>
            <option>Stoke Library</option>
            <option>Stowmarket Library</option>
            <option>Stradbroke Library</option>
            <option>Sudbury Library</option>
            <option>Thurston Library</option>
            <option>Wickham Market Library</option>
            <option>Woodbridge Library</option>
        </select>


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * The Date.prototype property "getUTCMonth" has { DontEnum } attributes
 *
 * @path ch15/15.9/15.9.5/15.9.5.13/S15.9.5.13_A1_T3.js
 * @description Checking DontEnum attribute
 */

if (Date.prototype.propertyIsEnumerable('getUTCMonth')) {
  $ERROR('#1: The Date.prototype.getUTCMonth property has the attribute DontEnum');
}

for(x in Date.prototype) {
  if(x === "getUTCMonth") {
    $ERROR('#2: The Date.prototype.getUTCMonth has the attribute DontEnum');
  }
}


text:
namespace aikido {
namespace planner {
namespace kunzretimer {

constexpr double DEFAULT_MAX_DEVIATION = 1e-2;
constexpr double DEFAULT_TIME_STEP = 0.1;

/// Computes the time-optimal timing of a trajectory consisting of a sequence
/// Geodesic interpolations between states under velocity and acceleration
/// bounds. The output is a parabolic spline, encoded in cubic polynomials.
/// It firstly preprocesses a non-differentiable path to a differentiable one
/// by adding circular blends; and then \b exactly follows the preprocessed
/// path.
///
/// The output trajectory consists of a sequence of trapezoidal velocity
/// profiles that implement bang-bang control. This function curently only
/// supports \c RealVector, \c SO2, and compound state spaces of those types.
/// Additionally, this function requires that \c inputTrajectory to be
/// interpolated using a \c GeodesicInterpolator.
///
/// \param[in] inputTrajectory Input piecewise Geodesic trajectory
/// \param[in] maxVelocity Maximum velocity for each dimension
/// \param[in] maxAcceleration Maximum acceleration for each dimension
/// \param[in] maxDeviation Maximum deviation from a waypoint in doing circular
/// blending around the waypoint
/// \param[in] timeStep Time step in following the path
/// \return Time optimal trajectory that satisfies velocity and acceleration
/// constraints
std::unique_ptr<aikido::trajectory::Spline> computeKunzTiming(
    const aikido::trajectory::Interpolated& inputTrajectory,
    const Eigen::VectorXd& maxVelocity,
    const Eigen::VectorXd& maxAcceleration,
    double maxDeviation = DEFAULT_MAX_DEVIATION,
    double timeStep = DEFAULT_TIME_STEP);

/// Class for performing time-optimal trajectory retiming following subject to
/// velocity and acceleration limits.
class KunzRetimer : public aikido::planner::TrajectoryPostProcessor
{
public:
  /// Kunz postprocessor parameters.
  struct Params
  {
    /// \param[in] _maxDeviation Maximum deviation in circular blending (in
    /// configuration space).
    /// \param[in] _timeStep Time step in following the path (in seconds).
    Params(
        double _maxDeviation = DEFAULT_MAX_DEVIATION,
        double _timeStep = DEFAULT_TIME_STEP)
      : mMaxDeviation(_maxDeviation), mTimeStep(_timeStep)
    {
      // Do nothing.
    }

    double mMaxDeviation;
    double mTimeStep;
  };

  /// \param[in] velocityLimits Maximum velocity for each dimension.
  /// \param[in] accelerationLimits Maximum acceleration for each dimension.
  /// \param[in] maxDeviation Maximum deviation in circular blending (in
  /// configuration space).
  /// \param[in] timeStep Time step in following the path (in seconds).
  KunzRetimer(
      const Eigen::VectorXd& velocityLimits,
      const Eigen::VectorXd& accelerationLimits,
      double maxDeviation = DEFAULT_MAX_DEVIATION,
      double timeStep = DEFAULT_TIME_STEP);

  /// \param[in] velocityLimits Maximum velocity for each dimension.
  /// \param[in] accelerationLimits Maximum acceleration for each dimension.
  /// \param[in] params Postprocessor parameters.
  KunzRetimer(
      const Eigen::VectorXd& velocityLimits,
      const Eigen::VectorXd& accelerationLimits,
      const Params& params);

  /// Performs parabolic retiming on an input trajectory.
  /// \copydoc TrajectoryPostProcessor::postprocess
  std::unique_ptr<aikido::trajectory::Spline> postprocess(
      const aikido::trajectory::Interpolated& inputTraj,
      const aikido::common::RNG& rng,
      const aikido::constraint::TestablePtr& constraint = nullptr) override;

  /// Performs parabolic retiming on an input *spline* trajectory.
  /// \copydoc TrajectoryPostProcessor::postprocess
  std::unique_ptr<aikido::trajectory::Spline> postprocess(
      const aikido::trajectory::Spline& inputTraj,
      const aikido::common::RNG& rng,
      const aikido::constraint::TestablePtr& constraint = nullptr) override;

  /// Returns the velocity limits of the dimensions
  const Eigen::VectorXd& getVelocityLimits() const;

  /// Returns the acceleration limits of the dimensions
  const Eigen::VectorXd& getAccelerationLimits() const;

  /// Sets the velocity limits of the dimensions
  void setVelocityLimits(const Eigen::VectorXd& velocityLimits);

  /// Sets the acceleration limits of the dimensions
  void setAccelerationLimits(const Eigen::VectorXd& accelerationLimits);

  /// Returns the time step in following a path
  double getTimeStep() const;

  /// Sets the time step in following a path
  void setTimeStep(double timeStep);

  /// Returns the max deviation of circular blending
  double getMaxDeviation() const;

  /// Sets the max deviation of circular blending
  void setMaxDeviation(double maxDeviation);

private:
  /// Set to the value of \c velocityLimits.
  Eigen::VectorXd mVelocityLimits;

  /// Set to the value of \c accelerationLimits.
  Eigen::VectorXd mAccelerationLimits;

  /// Set to the value of \c maxDeviation
  double mMaxDeviation;

  /// Set to the value of \c timeStep
  double mTimeStep;
};

} // namespace kunzretimer
} // namespace planner
} // namespace aikido

#endif // ifndef AIKIDO_PLANNER_KUNZRETIMER_KUNZRETIMER_HPP_


text:
package owltools.ontologyrelease.gui;

import java.io.File;

import org.apache.commons.io.FileUtils;

import owltools.ontologyrelease.OboOntologyReleaseRunnerGui;
import owltools.ontologyrelease.OortConfiguration;

/**
 * Parameters for {@link OboOntologyReleaseRunnerGui} with
 * different default values.
 */
public class OortGuiConfiguration extends OortConfiguration {

	public OortGuiConfiguration() {
		super();
		// set values which are different from CLI default setting
		setAsserted(true);
		setSimple(true);
		setExpandXrefs(false);
		setBase(new File(FileUtils.getUserDirectory(),"OORT"));
		setRecreateMireot(false);
	}
}


text:
@interface BeeUITemplatePackage()
{
	NSString *		_packageName;
	NSString *		_packagePath;
	NSDictionary *	_packageContent;
}
@end

#pragma mark -

@implementation BeeUITemplatePackage

@synthesize packagePath = _packagePath;
@synthesize packageContent = _packageContent;

@dynamic name;
@dynamic description;
@dynamic version;
@dynamic homepage;
@dynamic author;
@dynamic templates;
@dynamic licenses;

- (id)init
{
	self = [super init];
	if ( self )
	{

	}
	return self;
}

- (void)dealloc
{
	self.packagePath = nil;
	self.packageContent = nil;

	[super dealloc];
}

+ (BeeUITemplatePackage *)fromDirectory:(NSString *)fileName
{
	BOOL isDirectory = NO;
	BOOL fileExists = NO;

	fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fileName isDirectory:&isDirectory];
	if ( NO == fileExists )
	{
//		WARN( @"'%@' not exists", fileName );
		return nil;
	}

	if ( isDirectory )
	{
		fileName = [fileName stringByAppendingPathComponent:@"/package.json"];
	}

	return [self fromFile:fileName];
}

+ (BeeUITemplatePackage *)fromFile:(NSString *)fileName
{
	NSString * fileContent = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:NULL];
	if ( nil == fileContent )
	{
		WARN( @"Failed to load package '%@'", fileName );
		return nil;
	}

	NSDictionary * dict = [fileContent objectFromJSONString];
	if ( nil == dict || NO == [dict isKindOfClass:[NSDictionary class]] )
	{
		WARN( @"Failed to load package '%@'", fileName );
		return nil;
	}

	BeeUITemplatePackage * package = [[[BeeUITemplatePackage alloc] init] autorelease];
	if ( package )
	{
		package.packagePath = [fileName stringByDeletingLastPathComponent];
		package.packageContent = dict;

		INFO( @"'%@' loaded\n%@", fileName, package.packageContent );
	}
	return package;
}

- (NSString *)name
{
	return [self.packageContent objectForKey:@"name"];
}

- (NSString *)description
{
	return [self.packageContent objectForKey:@"description"];
}

- (NSString *)version
{
	return [self.packageContent objectForKey:@"version"];
}

- (NSString *)author
{
	return [self.packageContent objectForKey:@"author"];
}

- (NSString *)homepage
{
	return [self.packageContent objectForKey:@"homepage"];
}

- (NSArray *)templates
{
	return [self.packageContent objectForKey:@"templates"];
}

- (NSDictionary *)licenses
{
	return [self.packageContent objectForKey:@"licenses"];
}

- (NSString *)templateFilePath:(NSString *)fileName
{
	if ( nil == fileName )
		return nil;

	for ( NSString * templatePath in self.templates )
	{
		if ( [templatePath hasSuffix:fileName] )
			return templatePath;
	}

	return nil;
}

@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
using BeyondEarthApp.Web.Api.Models;

namespace BeyondEarthApp.Web.Api.LinkServices
{
    public interface IGameLinkService
    {
        void AddLinks(Game game);

        void AddLinksToChildren(Game game);
    }
}


text:
![Build Status](https://travis-ci.org/nbaksalyar/rust-websocket-essentials.svg?branch=master)

*Work-in-progress, please don't use this in production.*

A library with purpose to help in writing WebSocket code in Rust.

## License

Licensed under either of

 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.


text:
/*
 * structure.c
 *
 * RO_CSIO_TA0_RTC_Five_Buttons example for Gradon
 * Touch the five elements to turn on/off the center button LED
 * RO method capactiance measurement using Cap sense IO, TimerA0, and RTC
 *
 * Users can define by themselves which measuring method is used
 * All the parameters like threshold are all configured based on specific
 * Wolverine Launchpad and Boostpack, which may be modified according to user's
 * own applications.
 *
 * Revised by Eric Fu on May 2nd
 */

#include "structure.h"

// Middle Element (P1.3)
const struct Element middle_element =
{
    .inputBits = CAPSIOPOSEL0 + CAPSIOPISEL1 + CAPSIOPISEL0,  // select 1.4

    /* When using an abstracted function to measure the element
     * the 100*(maxResponse - threshold) < 0xFFFF
     * ie maxResponse - threshold < 655
     */

    .maxResponse = 100+655,
    .threshold = 100
};

const struct Element up_element =
{
    .inputBits = CAPSIOPOSEL0 + CAPSIOPISEL2,  // select 1.4

    /* When using an abstracted function to measure the element
     * the 100*(maxResponse - threshold) < 0xFFFF
     * ie maxResponse - threshold < 655
     */

    .maxResponse = 50+655,
    .threshold = 50
};

const struct Element right_element =
{
    .inputBits = CAPSIOPOSEL0 + CAPSIOPISEL2 + CAPSIOPISEL0,  // select 1.5

    /* When using an abstracted function to measure the element
     * the 100*(maxResponse - threshold) < 0xFFFF
     * ie maxResponse - threshold < 655
     */

    .maxResponse = 100+655,
    .threshold = 100
};

const struct Element down_element =
{
    .inputBits = CAPSIOPOSEL3 + CAPSIOPISEL1 + CAPSIOPISEL0,  // select 8.3

    /* When using an abstracted function to measure the element
     * the 100*(maxResponse - threshold) < 0xFFFF
     * ie maxResponse - threshold < 655
     */

    .maxResponse = 100+655,
    .threshold = 100
};

const struct Element left_element =
{
    .inputBits = CAPSIOPOSEL3 + CAPSIOPISEL1,  // select 8.2

    /* When using an abstracted function to measure the element
     * the 100*(maxResponse - threshold) < 0xFFFF
     * ie maxResponse - threshold < 655
     */

    .maxResponse = 100+655,
    .threshold = 100
};

// One Button Sensor
const struct Sensor one_button =
{

	/****** For RO_CSIO_TA0_RTC **************/
    .halDefinition = RO_CSIO_TA0_RTC,
	.inputCapsioctlRegister = (uint16_t *)&CAPSIO0CTL,
	.numElements = 5,
	.baseOffset = 0,
	// Pointer to elements
	.arrayPtr[0] = &middle_element,  		// point to middle element
	.arrayPtr[1] = &up_element,  		// point to up element
	.arrayPtr[2] = &right_element,  		// point to right element
	.arrayPtr[3] = &down_element,  		// point to down element
	.arrayPtr[4] = &left_element,  		// point to left element

	// Timer Information, which determine the Gate Time
	.measGateSource= GATE_RTC_SMCLK,     // Clock source for RTC
	.sourceScale = RTC_DIV_10,
	.accumulationCycles= 1024

};