text:
void raise_index_error(i64 idx);
void raise_over_free_error();

redpajama_set_name: RedPajamaGithub


text:
package net.jp2p.container.properties;

import net.jp2p.container.utils.StringStyler;

public interface IJp2pDirectives{

	/**
	 * Directives give additional clues on how to create the component
	 * @author Kees
	 *
	 */
	public enum Directives implements IJp2pDirectives{
		XMLNS_1XS,
		SCHEMA_LOCATION,
		ID,
		NAME,
		ENABLED,
		CLASS,
		TYPE,
		FILE,
		VISIBLE,
		AUTO_START,
		CONTEXT,
		CLEAR,
		WAIT_FOR,
		DEVELOP_MODE,
		VERSION,
		CREATE;

		@Override
		public String toString() {
			return StringStyler.prettyString( super.toString() );
		}

		public static boolean isDirective( String str ){
			str = StringStyler.styleToEnum(str);
			if(( str == null ) || ( str.length() == 0 ))
				return false;
			for( Directives comp: values()){
				if( comp.name().equals( str.toUpperCase() ))
					return true;
			}
			return false;
		}
	}

	/**
	 * The types of services that are available
	 * @author Kees
	 *
	 */
	public enum Contexts{
		JXTA,
		PLATFORM,
		JP2P,
		CHAUPAL;

		public static boolean isValidContext( String str ){
			str = StringStyler.styleToEnum(str);
			if(( str == null ) || ( str.length() == 0 ))
				return false;
			for( Contexts context: values()){
				if( context.name().equals( str.toUpperCase() ))
					return true;
			}
			return false;
		}

		@Override
		public String toString() {
			return StringStyler.prettyString( super.toString() );
		}
	}

	/**
	 * Developer modes tell the system in which state they are
	 * @author Kees
	 *
	 */
	public enum DeveloperModes{
		DEBUG,
		PRODUCTION,
		ANY;

		@Override
		public String toString() {
			return StringStyler.prettyString( super.toString() );
		}
	}

	public String name();
}


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yii message' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
return [
    'Add course' => 'Ajouter un parcours',
    'Add match' => 'Ajouter un match',
    'Add points' => 'Ajouter des classements par points',
    'Add tees set' => 'Ajouter un jeu de tees',
    'Add tournament' => 'Ajouter un tournois',
    'Add {0, number} points' => 'Ajouter {0, number} points',
    'Applies To' => "S'applique à",
    'Approach' => 'Approche',
    'Are you sure you want to delete this item?' => 'Etes-vous sûr de vouloir supprimer cet élément?',
    'Competition' => 'Compétition',
    'Competition Rules' => 'Règles de compétition',
    'Competition Type' => 'Type de compétition',
    'Competitions' => 'Compétitions',
    'Copy tees set from' => 'Copier le jeu de tees de...',
    'Course Id' => 'Parcours',
    'Course Name' => 'Nom du parcours',
    'Course' => 'Parcours',
    'Courses' => 'Parcours',
    'Create holes' => 'Créer des trous',
    'Create {modelClass}' => '',
    'Create' => 'Créer',
    'Created At' => 'Créé le',
    'Updated At' => 'Dernière mise à jour le',
    'Delete' => 'Supprimer',
    'Description' => 'Description',
    'Drive' => 'Départ',
    'Email' => 'eMail',
    'Entry Level' => "Niveau d'entrée",
    'Facilities' => 'Parcours de golf',
    'Facility Id' => 'Club',
    'Facility Name' => 'Nom du club',
    'Facility' => 'Club',
    'LADY' => 'Femme',
    'Flight' => 'Flight',
    'Flights' => 'Flights',
    'Golf Courses' => 'Parcours de golf',
    'Golfer' => 'Golfeur',
    'Golfers' => 'Golfeurs',
    'Hand' => 'Dextérité',
    'Handicap' => 'Handicap',
    'Hole' => 'Trou',
    'Hole Id' => 'Trou',
    'Holes' => 'Trous',
    'Homecourse' => 'Golf principal',
    'ID' => 'Identifiant',
    'Id' => 'Identifiant',
    'Imperial' => 'Impérial',
    'imperial' => 'Impérial',
    'imperial_shirt_units' => 'ft.',
    'imperial_med_units' => 'yds.',
    'left' => 'Gaucher',
    'Length' => 'Longueur',
    'Limit Date for Registration' => 'Date limite pour les inscriptions',
    'Limit Date' => 'Date limite',
    'GENTLEMAN' => 'Homme',
    'Match' => 'Match',
    'Match Name' => 'Nom du match',
    'Match Rules Id' => 'Règles de match',
    'Match Start Date' => 'Date',
    'Match' => 'Match',
    'Matches' => 'Matches',
    'Metric' => 'Métrique',
    'metric' => 'Métrique',
    'metric_short_units' => 'cm.',
    'metric_med_units' => 'm.',
    'Name' => 'Nom',
    'Note' => 'Note',
    'Number of Holes' => 'Nombre de trous',
    'Par' => 'Par',
    'Penalty' => 'Pénalité',
    'Phone' => 'Téléphone',
    'Points' => 'Points',
    'Position' => 'Position',
    'Putt' => 'Putt',
    'Putts' => 'Putts',
    'Registered At' => 'Inscrit le',
    'Registrations' => 'Inscriptions',
    'Regulation' => 'Régulation',
    'Reset' => 'Reset?',
    'right' => 'Droitier',
    'Rules For' => 'Règles pour',
    'Rules' => 'Règles',
    'Rules Id' => 'Règles',
    'Rules' => 'Règles',
    'Sand' => 'Sable',
    'Score' => 'Score',
    'Scorecard' => 'Carte de score',
    'Scorecards' => 'Carte de score',
    'Scores' => 'Scores',
    'Search' => 'Recherche',
    'Season Id' => 'Saison',
    'Season' => 'Saison',
    'Seasons' => 'Saisons',
    'gender' => 'Sexe',
    'Status' => 'Etat',
    'Start Date' => 'Date de début',
    'Stroke Index' => 'Stroke Index',
    'Tees Color' => 'Couleur des tees',
    'Tees Id' => 'Tees',
    'Tees Set Name' => 'Nom du jeu de tees',
    'Tees' => 'Tees',
    'Tournament Id' => 'Tournoi',
    'Tournament Name' => 'Nom du tournoi',
    'Tournament' => 'Tournoi',
    'Tournaments' => 'Tournois',
    'Units' => "Système d'unité",
    'Units' => "Système d'unités",
    'Update {modelClass}: ' => '',
    'Update' => 'Mise à jour',
    'User' => 'Utilisateur',
    'Website' => 'Site internet',
    'View all registrations' => 'Voir toutes les inscriptions',

    /* lookups */
    'MATCH' => 'Match',
    'TOURNAMENT' => 'Tournois',
    'SEASON' => 'Saison',

    'UNREGISTERED'=> 'Non inscrit',
    'REGISTERED'=> 'Inscrit',
    'REJECTED'=> 'Refusé',
    'PENDING'=> 'En attente',
    'CONFIRMED'=> 'Confirmé',
    'CANCELLED'=> 'Annulé',
    'FORFEIT'=> 'Forfait',
    'MISSEDCUT'=> 'Manqué cut',
    'ELIMINATED'=> 'Eliminé',
    'DISQUALIFIED'=> 'Disqualifié',
    'WITHDRAWN'=> 'Retrait',
    'QUALIFIED'=> 'Qualifié',

    /* résultats et erreurs */
    'Update Holes' => 'Mise à jour des trous',
    'Update Points' => 'Mise à jour des points',
    'Update Positions' => 'Mise à jour du classement',
    "Processed {0} records successfully." => "Traité {0} enregistrements avec succès.",

    /* tees colors */
    'Black' => 'Noirs',
    'Blue' => 'Bleus',
    'Gold' => 'Dorés',
    'Orange' => 'Oranges',
    'Pink' => 'Roses',
    'Red' => 'Rouges',
    'Silver' => 'Argentés',
    'White' => 'Blancs',
    'Yellow' => 'Jaunes',

    /* internal menus */
    'Calendar' => 'Calendrier',
    'Competition Rules' => 'Règles de compétition',
    'Competitions' => 'Compétitions',
    'Competitions' => 'Compétitions',
    'Courses' => 'Parcours',
    'Flights' => 'Flights',
    'Golf Courses' => 'Parcours de golf',
    'Golf League' => 'Ligue de Golf',
    'Golfers' => 'Golfeurs',
    'Golfers' => 'Golfeurs',
    'Managing' => 'Gestion',
    'Planning' => '',
    'Registrations' => 'Inscriptions',
    'Rules' => 'Règles',
    'Scorecards' => 'Cartes de score',
    'Scores' => 'Scores',
    'Scoring' => 'Résultats',

    /* site-wide menus */
    'Application' => 'Application',
    'Login' => 'Connexion',
    'Logout' => 'Déconnexion',
    'Roles and Privs' => 'Rôles et privs.',
    'Site' => 'Accueil',
    'Users' => 'Utilisateurs',

    /* Ending string (control) */
    'Golf League' => 'Ligue de golf'
];


text:
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

define(['jquery'], function($) {
    var SELECTORS = {
        STATE_NONE: '[data-state="none"]',
        STATE_BOTH: '[data-state="both"]',
        STATE_LOGGED_IN: '[data-state="loggedin"]',
        STATE_LOGGED_OFF: '[data-state="loggedoff"]',
    };

    /**
     * Constructor for the notification processor.
     *
     * @param {object} element jQuery object root element of the processor
     */
    var NotificationProcessor = function(element) {
        this.root = $(element);
    };

    /**
     * Get the processor name.
     *
     * @method getName
     * @return {string}
     */
    NotificationProcessor.prototype.getName = function() {
        return this.root.attr('data-processor-name');
    };

    /**
     * Check if the processor is enabled when the user is logged in.
     *
     * @method isLoggedInEnabled
     * @return {bool}
     */
    NotificationProcessor.prototype.isLoggedInEnabled = function() {
        var none = this.root.find(SELECTORS.STATE_NONE).find('input');

        if (none.prop('checked')) {
            return false;
        }

        var both = this.root.find(SELECTORS.STATE_BOTH).find('input');
        var loggedIn = this.root.find(SELECTORS.STATE_LOGGED_IN).find('input');

        return loggedIn.prop('checked') || both.prop('checked');
    };

    /**
     * Check if the processor is enabled when the user is logged out.
     *
     * @method isLoggedOffEnabled
     * @return {bool}
     */
    NotificationProcessor.prototype.isLoggedOffEnabled = function() {
        var none = this.root.find(SELECTORS.STATE_NONE).find('input');

        if (none.prop('checked')) {
            return false;
        }

        var both = this.root.find(SELECTORS.STATE_BOTH).find('input');
        var loggedOff = this.root.find(SELECTORS.STATE_LOGGED_OFF).find('input');

        return loggedOff.prop('checked') || both.prop('checked');
    };

    return NotificationProcessor;
});


text:
struct android_egl_engine::d
{
    d() :
            app(nullptr),
            display(nullptr),
            surface(nullptr),
            context(nullptr),
            config(nullptr),
            width(0),
            height(0)
    {
    }

    ~d()
    {
        app    = nullptr;
        display = nullptr;
        surface = nullptr;
        context = nullptr;
        config = nullptr;

        width  = 0;
        height = 0;
    }

    android_app* app;

    EGLDisplay   display;
    EGLSurface   surface;
    EGLContext   context;
    EGLConfig    config;

    EGLint       width;
    EGLint       height;
};

android_egl_engine::android_egl_engine(android_app* app)
{
    m_d.reset(new d());
    m_d->app = app;

    init_display();
    init_surface();
    init_context();

    // bind them
    if (EGL_FALSE == eglMakeCurrent(m_d->display, m_d->surface, m_d->surface, m_d->context)) {
        std::cout << "NativeEngine: eglMakeCurrent failed, EGL error " << eglGetError() << std::endl;
    }

    EGLint w, h;

    eglQuerySurface(m_d->display, m_d->surface, EGL_WIDTH,  &w);
    eglQuerySurface(m_d->display, m_d->surface, EGL_HEIGHT, &h);

    m_d->width  = w;
    m_d->height = h;
}

android_egl_engine::~android_egl_engine()
{
    if (m_d->display != EGL_NO_DISPLAY) {

        eglMakeCurrent(m_d->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

        if (m_d->context != EGL_NO_CONTEXT) {
            eglDestroyContext(m_d->display, m_d->context);
        }
        if (m_d->surface != EGL_NO_SURFACE) {
            eglDestroySurface(m_d->display, m_d->surface);
        }
        eglTerminate(m_d->display);
    }

    m_d->display = EGL_NO_DISPLAY;
    m_d->context = EGL_NO_CONTEXT;
    m_d->surface = EGL_NO_SURFACE;
}

int android_egl_engine::get_width() const
{
    return m_d->width;
}

int android_egl_engine::get_height() const
{
    return m_d->height;
}

bool android_egl_engine::swap_buffers()
{
    if (EGL_FALSE == eglSwapBuffers(m_d->display, m_d->surface)) {
        // failed to swap buffers...
        std::cout << "NativeEngine: eglSwapBuffers failed, EGL error " << eglGetError() << std::endl;
        handle_egl_error(eglGetError());
        return false;
    }
    return true;
}

bool android_egl_engine::init_display()
{
    if (m_d->display != EGL_NO_DISPLAY) {
        // nothing to do
        std::cout << "NativeEngine: no need to init display (already had one)." << std::endl;
        return true;
    }

    std::cout << "NativeEngine: initializing display." << std::endl;
    m_d->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    if (EGL_FALSE == eglInitialize(m_d->display, 0, 0)) {
        std::cout << "NativeEngine: failed to init display, error " << eglGetError() << std::endl;
        return false;
    }
    return true;
}

bool android_egl_engine::init_surface()
{
    // need a display
    assert(m_d->display != EGL_NO_DISPLAY);

    if (m_d->surface != EGL_NO_SURFACE) {
        // nothing to do
        std::cout << "NativeEngine: no need to init surface (already had one)." << std::endl;
        return true;
    }

    std::cout << "NativeEngine: initializing surface." << std::endl;

    EGLint numConfigs;

    const EGLint attribs[] = {
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, // request OpenGL ES 2.0
            EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
            EGL_BLUE_SIZE, 8,
            EGL_GREEN_SIZE, 8,
            EGL_RED_SIZE, 8,
            EGL_DEPTH_SIZE, 16,
            EGL_NONE
    };

    // since this is a simple sample, we have a trivial selection process. We pick
    // the first EGLConfig that matches:
    eglChooseConfig(m_d->display, attribs, &m_d->config, 1, &numConfigs);

    // create EGL surface
    m_d->surface = eglCreateWindowSurface(m_d->display, m_d->config, m_d->app->window, NULL);
    if (m_d->surface == EGL_NO_SURFACE) {
        std::cout << "Failed to create EGL surface, EGL error " << eglGetError() << std::endl;
        return false;
    }

    std::cout << "NativeEngine: successfully initialized surface." << std::endl;
    return true;
}

bool android_egl_engine::init_context()
{
    // need a display
    assert(m_d->display != EGL_NO_DISPLAY);

    EGLint attribList[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; // OpenGL 2.0

    if (m_d->context != EGL_NO_CONTEXT) {
        // nothing to do
        std::cout << "NativeEngine: no need to init context (already had one)." << std::endl;
        return true;
    }

    std::cout << "NativeEngine: initializing context." << std::endl;

    // create EGL context
    m_d->context = eglCreateContext(m_d->display, m_d->config, NULL, attribList);
    if (m_d->context == EGL_NO_CONTEXT) {
        std::cout << "Failed to create EGL context, EGL error " << eglGetError() << std::endl;
        return false;
    }

    std::cout << "NativeEngine: successfull initialized context." << std::endl;

    return true;
}

bool android_egl_engine::handle_egl_error(EGLint error)
{
    switch (error) {
        case EGL_SUCCESS:
            // nothing to do
            return true;
        case EGL_CONTEXT_LOST:
            std::cout << "NativeEngine: egl error: EGL_CONTEXT_LOST. Recreating context." << std::endl;
            //KillContext();
            return true;
        case EGL_BAD_CONTEXT:
            std::cout << "NativeEngine: egl error: EGL_BAD_CONTEXT. Recreating context." << std::endl;
            //KillContext();
            return true;
        case EGL_BAD_DISPLAY:
            std::cout << "NativeEngine: egl error: EGL_BAD_DISPLAY. Recreating display." << std::endl;
            //KillDisplay();
            return true;
        case EGL_BAD_SURFACE:
            std::cout << "NativeEngine: egl error: EGL_BAD_SURFACE. Recreating display." << std::endl;
            //KillSurface();
            return true;
        default:
            std::cout << "NativeEngine: unknown egl error: " << error << std::endl;
            return false;
    }
}


text:
package ds

import (
	"context"
	"fmt"
	"path/filepath"

	"github.com/sselph/scraper/gdb"
)

// NeoGeo is a data source using GDB for Daphne games.
type NeoGeo struct {
	HM     *HashMap
	APIKey string
}

// getID gets the ID from the path.
func (n *NeoGeo) getID(p string) (string, error) {
	if filepath.Ext(p) == ".7z" {
		p = p[:len(p)-3] + ".zip"
	}
	if filepath.Ext(p) != ".zip" {
		return "", ErrNotFound
	}
	gameID := filepath.Base(p)
	id, ok := n.HM.ID(gameID)
	if !ok {
		return "", ErrNotFound
	}
	return id, nil
}

// GetName implements DS.
func (n *NeoGeo) GetName(p string) string {
	gameID := filepath.Base(p)
	name, ok := n.HM.Name(gameID)
	if !ok {
		return ""
	}
	return name
}

// GetGame implements DS.
func (n *NeoGeo) GetGame(ctx context.Context, p string) (*Game, error) {
	id, err := n.getID(p)
	if err != nil {
		return nil, err
	}
	resp, err := gdb.GetGame(ctx, n.APIKey, id)
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, fmt.Errorf("game with id (%s) not found", id)
	}

	result := ParseGDBGame(*resp)
	result.Images[ImgTitle] = result.Images[ImgBoxart]
	result.Thumbs[ImgTitle] = result.Thumbs[ImgBoxart]
	result.Images[ImgMarquee] = result.Images[ImgLogo]
	result.Thumbs[ImgMarquee] = result.Thumbs[ImgLogo]
	return result, nil
}


text:
require 'fog/openstack/volume/requests/list_backups'
require 'fog/openstack/volume/v2/requests/real'


text:
package org.onosproject.cli.net;

import org.apache.karaf.shell.api.console.CommandLine;
import org.apache.karaf.shell.api.console.Completer;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.api.console.Session;
import org.apache.karaf.shell.support.completers.StringsCompleter;

import java.util.List;
import java.util.SortedSet;

/**
 * ICMPv6 type completer.
 */
@Service
public class Icmp6TypeCompleter implements Completer {
    @Override
    public int complete(Session session, CommandLine commandLine, List<String> candidates) {
        // Delegate string completer
        StringsCompleter delegate = new StringsCompleter();
        SortedSet<String> strings = delegate.getStrings();

        for (Icmp6Type type : Icmp6Type.values()) {
            strings.add(type.toString());
        }

        // Now let the completer do the work for figuring out what to offer.
        return delegate.complete(session, commandLine, candidates);
    }

}


text:
// [START earthengine__apidocs__ee_geometry_polygon_geodesic]
// Define a Polygon object.
var polygon = ee.Geometry.Polygon(
    [[[-122.092, 37.424],
      [-122.086, 37.418],
      [-122.079, 37.425],
      [-122.085, 37.423]]]);

// Apply the geodesic method to the Polygon object.
var polygonGeodesic = polygon.geodesic();

// Print the result to the console.
print('polygon.geodesic(...) =', polygonGeodesic);

// Display relevant geometries on the map.
Map.setCenter(-122.085, 37.422, 15);
Map.addLayer(polygon,
             {'color': 'black'},
             'Geometry [black]: polygon');
// [END earthengine__apidocs__ee_geometry_polygon_geodesic]


text:
import CodeMirror from "./textcomplete.codemirror"

global.Textcomplete || (global.Textcomplete = {})
global.Textcomplete.editors || (global.Textcomplete.editors = {})
global.Textcomplete.editors.CodeMirror = CodeMirror


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self.thirdPartiesConfigurator configurate];
    [self.applicationConfigurator setupCoreDataStack];
    [self.applicationConfigurator configureInitialSettings];
    [self.pushNotificationCenter registerApplicationForPushNotificationsIfNeeded:application];

    NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (notification) {
        [self.pushNotificationCenter processPushNotificationWithUserInfo:notification
                                                        applicationState:application.applicationState];
    }

    return YES;
}

- (NSArray *)initialAssemblies {
    RamblerInitialAssemblyCollector *collector = [RamblerInitialAssemblyCollector new];
    return [collector collectInitialAssemblyClasses];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [self.pushNotificationCenter didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [self.pushNotificationCenter processPushNotificationWithUserInfo:userInfo
                                                    applicationState:application.applicationState];
}

@end


text:
@class CADisplayLink, NSMutableArray;

@interface ImplicitAnimationObj : NSObject
{
    CADisplayLink *m_displayLink;
    NSMutableArray *m_implicitViews;
    unsigned long long m_countOfViewStartAnimation;
    double m_nextTimeToLetNextViewStartAnimation;
    _Bool _isFromBottom;
    id <ImplicitAnimationControllerDelegate> _delegate;
    CDUnknownBlockType _durationBlock;
}

@property(copy, nonatomic) CDUnknownBlockType durationBlock; // @synthesize durationBlock=_durationBlock;
@property(nonatomic) _Bool isFromBottom; // @synthesize isFromBottom=_isFromBottom;
@property(nonatomic) __weak id <ImplicitAnimationControllerDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct;
- (void)updateCountOfViewStartAnimationWithCurTime:(double)arg1;
- (void)updateFrame;
- (void)startAnimationWithViews:(id)arg1;
- (void)stopAnimation;
- (void)dealloc;

@end


text:
<?php
/**
 * @author @jenschude <jens.schulze@commercetools.de>
 */

namespace JaySDe\HandlebarsBundle\Tests\Helper;

use JaySDe\HandlebarsBundle\Helper\CmsHelper;
use PHPUnit\Framework\TestCase;

class CmsHelperTest extends TestCase
{
    public function testHandle()
    {
        $observer = $this->prophesize('\JaySDe\HandlebarsBundle\Helper\TranslationHelper');
        $observer->handle('test', [])->willReturn('lorem ipsum')->shouldBeCalled();
        $helper = new CmsHelper($observer->reveal());

        $test = $helper->handle('test', []);
        $this->assertSame('lorem ipsum', $test);
    }

    public function testHandleWithOptions()
    {
        $observer = $this->prophesize('\JaySDe\HandlebarsBundle\Helper\TranslationHelper');
        $observer->handle('test', ['foo' => 'bar'])->willReturn('lorem ipsum')->shouldBeCalled();
        $helper = new CmsHelper($observer->reveal());

        $test = $helper->handle('test', ['hash' => ['foo' => 'bar']]);
        $this->assertSame('lorem ipsum', $test);
    }

    public function testHandleWithBundle()
    {
        $observer = $this->prophesize('\JaySDe\HandlebarsBundle\Helper\TranslationHelper');
        $observer->handle('foo:test', [])->willReturn('lorem ipsum')->shouldBeCalled();
        $helper = new CmsHelper($observer->reveal());

        $test = $helper->handle('test', ['hash' => ['bundle' => 'foo']]);
        $this->assertSame('lorem ipsum', $test);
    }

    public function testHandleWithOptionsAndBundle()
    {
        $observer = $this->prophesize('\JaySDe\HandlebarsBundle\Helper\TranslationHelper');
        $observer->handle('foo:test', ['foo' => 'bar'])->willReturn('lorem ipsum')->shouldBeCalled();
        $helper = new CmsHelper($observer->reveal());

        $test = $helper->handle('test', ['hash' => ['foo' => 'bar', 'bundle' => 'foo']]);
        $this->assertSame('lorem ipsum', $test);
    }

    public function testDefaultNamespace()
    {
        $observer = $this->prophesize('\JaySDe\HandlebarsBundle\Helper\TranslationHelper');
        $observer->handle('cms:test', [])->willReturn('lorem ipsum')->shouldBeCalled();
        $helper = new CmsHelper($observer->reveal(), 'cms');

        $test = $helper->handle('test', []);
        $this->assertSame('lorem ipsum', $test);
    }
}


text:
package org.apache.camel.component.ibatis.springboot;

import com.ibatis.sqlmap.client.SqlMapClient;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Performs a query poll insert update or delete in a relational database using
 * Apache iBATIS.
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@ConfigurationProperties(prefix = "camel.component.ibatis")
public class IBatisComponentConfiguration {

    /**
     * To use the given com.ibatis.sqlmap.client.SqlMapClient
     */
    private SqlMapClient sqlMapClient;
    /**
     * Location of iBatis xml configuration file. The default value is:
     * SqlMapConfig.xml loaded from the classpath
     */
    private String sqlMapConfig;
    /**
     * Whether to use transactions. This option is by default true.
     */
    private Boolean useTransactions;

    public SqlMapClient getSqlMapClient() {
        return sqlMapClient;
    }

    public void setSqlMapClient(SqlMapClient sqlMapClient) {
        this.sqlMapClient = sqlMapClient;
    }

    public String getSqlMapConfig() {
        return sqlMapConfig;
    }

    public void setSqlMapConfig(String sqlMapConfig) {
        this.sqlMapConfig = sqlMapConfig;
    }

    public Boolean getUseTransactions() {
        return useTransactions;
    }

    public void setUseTransactions(Boolean useTransactions) {
        this.useTransactions = useTransactions;
    }
}


text:
namespace Serenity.PropertyGrid
{
    public partial class BasicPropertyProcessor : PropertyProcessor
    {
        private void SetDefaultValue(IPropertySource source, PropertyItem item)
        {
            if (source.Property != null)
            {
                var attr = source.Property.GetAttribute<DefaultValueAttribute>(false);
                if (attr != null)
                {
                    item.DefaultValue = attr.Value;
                    return;
                }
            }

            if (source.BasedOnField is object && source.BasedOnField.DefaultValue != null)
                item.DefaultValue = source.BasedOnField.DefaultValue;
        }
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>登录(Login)</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">

        <link rel="stylesheet" href="assets/css/reset.css">
        <link rel="stylesheet" href="assets/css/supersized.css">
        <link rel="stylesheet" href="assets/css/style.css">

登录(Login)

            <form action="chk_login.php" method="post" onsubmit="return chkinput(this)">
                <input type="text" name="username" class="username" placeholder="请输入您的用户名!">
                <input type="password" name="password" class="password" placeholder="请输入您的用户密码!">

                <button type="submit" class="submit_button">登录</button>

+

            </form>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusarium solaris anon.

### Remarks
null


text:
using Microsoft.Azure.Documents;
using Newtonsoft.Json;
using System;

namespace SdkPerfTest
{
    public class SalesOrder
    {
        //You can use JsonProperty attributes to control how your objects are
        //handled by the Json Serializer/Deserializer
        //Any of the supported JSON.NET attributes here are supported, including the use of JsonConverters
        //if you really want fine grained control over the process

        //Here we are using JsonProperty to control how the Id property is passed over the wire
        //In this case, we're just making it a lowerCase string but you could entirely rename it
        //like we do with PurchaseOrderNumber below
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        [JsonProperty(PropertyName="ponumber")]
        public string PurchaseOrderNumber { get; set; }
        public DateTime OrderDate { get; set; }
        public DateTime ShippedDate { get; set; }
        public string AccountNumber { get; set; }
        public decimal SubTotal { get; set; }
        public decimal TaxAmount { get; set; }
        public decimal Freight { get; set; }
        public decimal TotalDue { get; set; }
        public SalesOrderDetail[] Items { get; set; }

        public static SalesOrder GetSalesOrderSample(string documentId, string accountNumber)
        {
            return new SalesOrder
            {
                Id = documentId,
                AccountNumber = accountNumber,
                PurchaseOrderNumber = "PO18009186470",
                OrderDate = new DateTime(2005, 7, 1),
                SubTotal = 419.4589m,
                TaxAmount = 12.5838m,
                Freight = 472.3108m,
                TotalDue = 985.018m,
                Items = new SalesOrderDetail[]
                {
                    new SalesOrderDetail
                    {
                        OrderQty = 1,
                        ProductId = 760,
                        UnitPrice = 419.4589m,
                        LineTotal = 419.4589m
                    }
                },
            };
        }
    }
    public class SalesOrderDetail
    {
        public int OrderQty { get; set; }
        public int ProductId { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal LineTotal { get; set; }
    }
    public class SalesOrder2
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        [JsonProperty(PropertyName = "ponumber")]
        public string PurchaseOrderNumber { get; set; }

        public DateTime OrderDate { get; set; }

        public DateTime DueDate { get; set; }

        public DateTime ShippedDate { get; set; }

        public string AccountNumber { get; set; }

        public decimal SubTotal { get; set; }

        public decimal TaxAmt { get; set; }

        public decimal Freight { get; set; }

        public decimal TotalDue { get; set; }

        public decimal DiscountAmt { get; set; }

        public SalesOrderDetail2[] Items { get; set; }
    }
    public class SalesOrderDetail2
    {
        public int OrderQty { get; set; }
        public string ProductCode { get; set; }
        public string ProductName { get; set; }
        public string CurrencySymbol { get; set; }
        public string CurrencyCode { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal LineTotal { get; set; }
    }
    internal class Product
    {
        string ProductCode { get; set; }
        string ProductName { get; set; }
        Price UnitPrice { get; set; }
    }
    internal class Price
    {
        double Amount { get; set; }
        string CurrencySymbol { get; set; }
        string CurrencyCode { get; set; }
    }

    /// <summary>
    /// SalesOrderDocument extends the Microsoft.Azure.Documents.Resource class
    /// This gives you access to internal properties of a Resource such as ETag, SelfLink, Id etc.
    /// When working with objects extending from Resource you get the benefit of not having to
    /// dynamically cast between Document and your POCO.
    /// </summary>
    public class SalesOrderDocument : Resource
    {
        public string PurchaseOrderNumber { get; set; }
        public DateTime OrderDate { get; set; }
        public DateTime ShipDate { get; set; }
        public string AccountNumber { get; set; }
        public decimal SubTotal { get; set; }
        public decimal TaxAmt { get; set; }
        public decimal Freight { get; set; }
        public decimal TotalDue { get; set; }
        public SalesOrderDetail[] Items { get; set; }
    }
}


text:
import unittest
import uuid

from airflow.contrib.hooks.aws_firehose_hook import AwsFirehoseHook

try:
    from moto import mock_kinesis
except ImportError:
    mock_kinesis = None

class TestAwsFirehoseHook(unittest.TestCase):

    @unittest.skipIf(mock_kinesis is None, 'mock_kinesis package not present')
    @mock_kinesis
    def test_get_conn_returns_a_boto3_connection(self):
        hook = AwsFirehoseHook(aws_conn_id='aws_default',
                               delivery_stream="test_airflow", region_name="us-east-1")
        self.assertIsNotNone(hook.get_conn())

    @unittest.skipIf(mock_kinesis is None, 'mock_kinesis package not present')
    @mock_kinesis
    def test_insert_batch_records_kinesis_firehose(self):
        hook = AwsFirehoseHook(aws_conn_id='aws_default',
                               delivery_stream="test_airflow", region_name="us-east-1")

        response = hook.get_conn().create_delivery_stream(
            DeliveryStreamName="test_airflow",
            S3DestinationConfiguration={
                'RoleARN': 'arn:aws:iam::123456789012:role/firehose_delivery_role',
                'BucketARN': 'arn:aws:s3:::kinesis-test',
                'Prefix': 'airflow/',
                'BufferingHints': {
                    'SizeInMBs': 123,
                    'IntervalInSeconds': 124
                },
                'CompressionFormat': 'UNCOMPRESSED',
            }
        )

        stream_arn = response['DeliveryStreamARN']
        self.assertEquals(
            stream_arn, "arn:aws:firehose:us-east-1:123456789012:deliverystream/test_airflow")

        records = [{"Data": str(uuid.uuid4())}
                   for _ in range(100)]

        response = hook.put_records(records)

        self.assertEquals(response['FailedPutCount'], 0)
        self.assertEquals(response['ResponseMetadata']['HTTPStatusCode'], 200)

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


text:
layout: post
title: "Criando Seu Próprio Template Nativescript"
date: "2017-05-26 22:56:59 -0300"
tags: [NativeScript, JavaScript, TypeScript, Angular, CSS, Mobile, Android, iOS, Programação, Telerik]
category: [programacao, mobile, NativeScript]
layout: article
share: true
toc: true
comments: true
feature:
 category: true
 index: true
ads:
 show: true
tagcloud: true
show: true
image:
 teaser: programacao/nativescript/NativeScript_logo.png
 feature: programacao/nativescript/NativeScript_logo_1800x600.png
---
Templates podem ser usados no NativeScript para criar modelos de projetos que podem ser reaproveitados a cada novo projeto de software a ser desenvolvido.

<!--more-->

Para criar um template é importante compreender bem como funciona o conceito de módulos no NodeJS, para isso leia o post [Como funciona o uso de módulos  para NativeScript]({% post_url programacao/NativeScript/2017-05-24-como_funciona_o_mecanismo_de_modulos_no_nativescript %})

---

Você pode criar um template de seus softwares que irá automaticamente carregar seus módulos mais usados, módulos personalizados, logo de sua empresa/startup/ou pessoal, e estrutura padrão de sua aplicação.

Como foi citado acima, é preciso compreender como funciona o sistema de módulos do NodeJS, pois o NativeScript usa este mesmo conceito para empacotar seus templates

**Atenção** Artigo em construção.
{: .notice }

## Fontes

* Documentação do NativeScript
* https://www.tjvantoll.com/2016/02/22/creating-nativescript-templates/#creating-your-own-templates


text:
import { inject } from 'ember-runtime';
import { Component } from 'ember-glimmer';
import { Route, NoneLocation } from 'ember-routing';
import { Controller } from 'ember-runtime';
import {
  run,
  get
} from 'ember-metal';
import {
  RouterTestCase,
  moduleFor
} from 'internal-test-helpers';
import { Transition } from 'router';

import { EMBER_ROUTING_ROUTER_SERVICE } from 'ember/features';

if (EMBER_ROUTING_ROUTER_SERVICE) {
  moduleFor('Router Service - transitionTo', class extends RouterTestCase {
    constructor() {
      super();

      let testCase = this;
      testCase.state = [];

      this.add('location:test', NoneLocation.extend({
        setURL(path) {
          testCase.state.push(path);
          this.set('path', path);
        },

        replaceURL(path) {
          testCase.state.splice(testCase.state.length -1, 1, path);
          this.set('path', path);
        }
      }));
    }

    get routerOptions() {
      return {
        location: 'test'
      };
    }

    ['@test RouterService#transitionTo returns a Transition'](assert) {
      assert.expect(1);

      let transition;

      return this.visit('/')
        .then(() => {
          transition = this.routerService.transitionTo('parent.child');

          assert.ok(transition instanceof Transition);

          return transition;
        });
    }

    ['@test RouterService#transitionTo with basic route updates location'](assert) {
      assert.expect(1);

      return this.visit('/')
        .then(() => {
          return this.routerService.transitionTo('parent.child');
        })
        .then(() => {
          return this.routerService.transitionTo('parent.sister');
        })
        .then(() => {
          return this.routerService.transitionTo('parent.brother');
        })
        .then(() => {
          assert.deepEqual(this.state, ['/', '/child', '/sister', '/brother']);
        });
    }

    ['@test RouterService#transitionTo transitioning back to previously visited route updates location'](assert) {
      assert.expect(1);

      return this.visit('/')
        .then(() => {
          return this.routerService.transitionTo('parent.child');
        })
        .then(() => {
          return this.routerService.transitionTo('parent.sister');
        })
        .then(() => {
          return this.routerService.transitionTo('parent.brother');
        })
        .then(() => {
          return this.routerService.transitionTo('parent.sister');
        })
        .then(() => {
          assert.deepEqual(this.state, ['/', '/child', '/sister', '/brother', '/sister']);
        });
    }

    ['@test RouterService#transitionTo with basic route'](assert) {
      assert.expect(1);

      let componentInstance;

      this.addTemplate('parent.index', '{{foo-bar}}');

      this.addComponent('foo-bar', {
        ComponentClass: Component.extend({
          routerService: inject.service('router'),
          init() {
            this._super();
            componentInstance = this;
          },
          actions: {
            transitionToSister() {
              get(this, 'routerService').transitionTo('parent.sister');
            }
          }
        }),
        template: `foo-bar`
      });

      return this.visit('/').then(() => {
        run(function() {
          componentInstance.send('transitionToSister');
        });

        assert.equal(this.routerService.get('currentRouteName'), 'parent.sister');
      });
    }

    ['@test RouterService#transitionTo with basic route using URL'](assert) {
      assert.expect(1);

      let componentInstance;

      this.addTemplate('parent.index', '{{foo-bar}}');

      this.addComponent('foo-bar', {
        ComponentClass: Component.extend({
          routerService: inject.service('router'),
          init() {
            this._super();
            componentInstance = this;
          },
          actions: {
            transitionToSister() {
              get(this, 'routerService').transitionTo('/sister');
            }
          }
        }),
        template: `foo-bar`
      });

      return this.visit('/').then(() => {
        run(function() {
          componentInstance.send('transitionToSister');
        });

        assert.equal(this.routerService.get('currentRouteName'), 'parent.sister');
      });
    }

    ['@test RouterService#transitionTo with dynamic segment'](assert) {
      assert.expect(3);

      let componentInstance;
      let dynamicModel = { id: 1, contents: 'much dynamicism' };

      this.addTemplate('parent.index', '{{foo-bar}}');
      this.addTemplate('dynamic', '{{model.contents}}');

      this.addComponent('foo-bar', {
        ComponentClass: Component.extend({
          routerService: inject.service('router'),
          init() {
            this._super();
            componentInstance = this;
          },
          actions: {
            transitionToDynamic() {
              get(this, 'routerService').transitionTo('dynamic', dynamicModel);
            }
          }
        }),
        template: `foo-bar`
      });

      return this.visit('/').then(() => {
        run(function() {
          componentInstance.send('transitionToDynamic');
        });

        assert.equal(this.routerService.get('currentRouteName'), 'dynamic');
        assert.equal(this.routerService.get('currentURL'), '/dynamic/1');
        this.assertText('much dynamicism');
      });
    }

    ['@test RouterService#transitionTo with dynamic segment and model hook'](assert) {
      assert.expect(3);

      let componentInstance;
      let dynamicModel = { id: 1, contents: 'much dynamicism' };

      this.add('route:dynamic', Route.extend({
        model() {
          return dynamicModel;
        }
      }));

      this.addTemplate('parent.index', '{{foo-bar}}');
      this.addTemplate('dynamic', '{{model.contents}}');

      this.addComponent('foo-bar', {
        ComponentClass: Component.extend({
          routerService: inject.service('router'),
          init() {
            this._super();
            componentInstance = this;
          },
          actions: {
            transitionToDynamic() {
              get(this, 'routerService').transitionTo('dynamic', 1);
            }
          }
        }),
        template: `foo-bar`
      });

      return this.visit('/').then(() => {
        run(function() {
          componentInstance.send('transitionToDynamic');
        });

        assert.equal(this.routerService.get('currentRouteName'), 'dynamic');
        assert.equal(this.routerService.get('currentURL'), '/dynamic/1');
        this.assertText('much dynamicism');
      });
    }

    ['@test RouterService#transitionTo with basic query params does not remove query param defaults'](assert) {
      assert.expect(1);

      this.add('controller:parent.child', Controller.extend({
        queryParams: ['sort'],
        sort: 'ASC'
      }));

      let queryParams = this.buildQueryParams({ sort: 'ASC' });

      return this.visit('/')
        .then(() => {
          return this.routerService.transitionTo('parent.child', queryParams);
        })
        .then(() => {
          assert.equal(this.routerService.get('currentURL'), '/child?sort=ASC');
        });
    }

    ['@test RouterService#transitionTo passing only queryParams works'](assert) {
      assert.expect(2);

      this.add('controller:parent.child', Controller.extend({
        queryParams: ['sort']
      }));

      let queryParams = this.buildQueryParams({ sort: 'DESC' });

      return this.visit('/')
        .then(() => {
          return this.routerService.transitionTo('parent.child');
        })
        .then(() => {
          assert.equal(this.routerService.get('currentURL'), '/child');
        })
        .then(() => {
          return this.routerService.transitionTo(queryParams);
        })
        .then(() => {
          assert.equal(this.routerService.get('currentURL'), '/child?sort=DESC');
        });
    }

    ['@test RouterService#transitionTo with unspecified query params'](assert) {
      assert.expect(1);

      this.add('controller:parent.child', Controller.extend({
        queryParams: ['sort', 'page', 'category', 'extra'],
        sort: 'ASC',
        page: null,
        category: undefined
      }));

      let queryParams = this.buildQueryParams({ sort: 'ASC' });

      return this.visit('/')
        .then(() => {
          return this.routerService.transitionTo('parent.child', queryParams);
        })
        .then(() => {
          assert.equal(this.routerService.get('currentURL'), '/child?sort=ASC');
        });
    }

    ['@test RouterService#transitionTo with aliased query params uses the original provided key'](assert) {
      assert.expect(1);

      this.add('controller:parent.child', Controller.extend({
        queryParams: {
          'cont_sort': 'url_sort'
        },
        cont_sort: 'ASC'
      }));

      let queryParams = this.buildQueryParams({ url_sort: 'ASC' });

      return this.visit('/').then(() => {
        return this.routerService.transitionTo('parent.child', queryParams);
      })
        .then(() => {
          assert.equal(this.routerService.get('currentURL'), '/child?url_sort=ASC');
        });
    }

    ['@test RouterService#transitionTo with aliased query params uses the original provided key when controller property name'](assert) {
      assert.expect(1);

      this.add('controller:parent.child', Controller.extend({
        queryParams: {
          'cont_sort': 'url_sort'
        },
        cont_sort: 'ASC'
      }));

      let queryParams = this.buildQueryParams({ cont_sort: 'ASC' });

      return this.visit('/').then(() => {
        expectAssertion(() => {
          return this.routerService.transitionTo('parent.child', queryParams);
        }, 'You passed the `cont_sort` query parameter during a transition into parent.child, please update to url_sort');
      });
    }
  });
}


text:
import smv

class input(smv.SmvCsvFile):
    def path(self):
        return "employment/CB1200CZ11.csv"


text:
import {Tensor} from '../../tensor';
import {convertToTensor} from '../../tensor_util_env';
import {TensorLike} from '../../types';
import {assertShapesMatch} from '../../util';
import {add} from '../add';
import {log} from '../log';
import {Reduction} from '../loss_ops_utils';
import {mul} from '../mul';
import {neg} from '../neg';
import {op} from '../operation';
import {scalar} from '../scalar';
import {sub} from '../sub';

import {computeWeightedLoss} from './compute_weighted_loss';

/**
 * Computes the log loss between two tensors.
 *
 * @param labels The ground truth output tensor, same dimensions as
 *    'predictions'.
 * @param predictions The predicted outputs.
 * @param weights Tensor whose rank is either 0, or the same rank as
 *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions
 *    must be either `1`, or the same as the corresponding `losses`
 *    dimension).
 * @param epsilon A small increment to avoid taking log of zero
 * @param reduction Type of reduction to apply to loss. Should be of type
 *    `Reduction`
 *
 * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
 */
function logLoss_<T extends Tensor, O extends Tensor>(
    labels: T|TensorLike, predictions: T|TensorLike,
    weights?: Tensor|TensorLike, epsilon = 1e-7,
    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {
  const $labels = convertToTensor(labels, 'labels', 'logLoss');
  const $predictions = convertToTensor(predictions, 'predictions', 'logLoss');
  let $weights: Tensor = null;
  if (weights != null) {
    $weights = convertToTensor(weights, 'weights', 'logLoss');
  }
  assertShapesMatch($labels.shape, $predictions.shape, 'Error in logLoss: ');

  const one = scalar(1);
  const epsilonScalar = scalar(epsilon);

  const l1 = neg(mul($labels, log(add($predictions, epsilonScalar))));
  const l2 =
      mul(sub(one, $labels), log(add(sub(one, $predictions), epsilonScalar)));
  const losses = sub(l1, l2);
  return computeWeightedLoss(losses, $weights, reduction);
}
export const logLoss = op({logLoss_});


text:
package org.kie.dmn.core.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.junit.Assert;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.Results;
import org.kie.api.internal.assembler.KieAssemblerService;
import org.kie.api.internal.assembler.KieAssemblers;
import org.kie.api.internal.utils.ServiceDiscoveryImpl;
import org.kie.api.internal.utils.ServiceRegistry;
import org.kie.api.internal.utils.ServiceRegistryImpl;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.dmn.api.core.DMNMessage;
import org.kie.dmn.api.core.DMNRuntime;
import org.kie.dmn.api.core.event.AfterEvaluateBKMEvent;
import org.kie.dmn.api.core.event.AfterEvaluateDecisionEvent;
import org.kie.dmn.api.core.event.AfterEvaluateDecisionTableEvent;
import org.kie.dmn.api.core.event.BeforeEvaluateBKMEvent;
import org.kie.dmn.api.core.event.BeforeEvaluateDecisionEvent;
import org.kie.dmn.api.core.event.BeforeEvaluateDecisionTableEvent;
import org.kie.dmn.api.core.event.DMNRuntimeEventListener;
import org.kie.dmn.core.api.event.DefaultDMNRuntimeEventListener;
import org.kie.dmn.core.compiler.RuntimeTypeCheckOption;
import org.kie.dmn.core.impl.DMNRuntimeImpl;
import org.kie.internal.builder.InternalKieBuilder;
import org.kie.internal.services.KieAssemblersImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

/**
 * A type-check safe runtime creation helper.
 */
public final class DMNRuntimeUtil {

    public static final Logger LOG = LoggerFactory.getLogger(DMNRuntimeUtil.class);

    public static DMNRuntime createRuntime(final Class testClass) {
        final KieServices ks = KieServices.Factory.get();
        final KieContainer kieContainer = KieHelper.getKieContainer(
        ks.newReleaseId("org.kie", "dmn-test-"+UUID.randomUUID(), "1.0"));
        final DMNRuntime runtime = typeSafeGetKieRuntime(kieContainer);
        Assert.assertNotNull(runtime);
        return runtime;
    }

    public static DMNRuntime createRuntime(final String resourceName, final Class testClass) {
        final KieServices ks = KieServices.Factory.get();
        final KieContainer kieContainer = KieHelper.getKieContainer(
                ks.newReleaseId("org.kie", "dmn-test-"+UUID.randomUUID(), "1.0"),
                ks.getResources().newClassPathResource(resourceName, testClass));

        final DMNRuntime runtime = typeSafeGetKieRuntime(kieContainer);
        Assert.assertNotNull(runtime);
        return runtime;
    }

    public static List<DMNMessage> createExpectingDMNMessages(final String resourceName, final Class testClass) {
        final KieServices ks = KieServices.Factory.get();
        final KieContainer kieContainer = getKieContainerIgnoringErrors(ks.newReleaseId("org.kie", "dmn-test-" + UUID.randomUUID(), "1.0"),
                                                                        ks.getResources().newClassPathResource(resourceName, testClass));

        Results verify = kieContainer.verify();
        List<Message> kie_messages = verify.getMessages();
        LOG.debug("{}", kie_messages);
        List<DMNMessage> dmnMessages = kie_messages.stream()
                                                   .filter(DMNMessage.class::isInstance)
                                                   .map(DMNMessage.class::cast)
                                                   .collect(Collectors.toList());
        assertThat(dmnMessages.isEmpty(), is(false));
        return dmnMessages;
    }

    public static void resetServices() {
        final ServiceDiscoveryImpl serviceDiscovery = ServiceDiscoveryImpl.getInstance();
        serviceDiscovery.reset();
        final ServiceRegistryImpl instance = (ServiceRegistryImpl)ServiceRegistry.getInstance();
        instance.reload();
    }

    public static DMNRuntime createRuntimeWithAdditionalResources(final String resourceName, final Class testClass, final String... additionalResources) {
        final KieServices ks = KieServices.Factory.get();
        Resource mainResource = ks.getResources().newClassPathResource(resourceName, testClass);
        List<Resource> totalResources = new ArrayList<>();
        totalResources.add(mainResource);
        for ( String add : additionalResources ) {
            totalResources.add( ks.getResources().newClassPathResource(add, testClass) );
        }
        final KieContainer kieContainer = KieHelper.getKieContainer(
                ks.newReleaseId("org.kie", "dmn-test-"+UUID.randomUUID(), "1.0"),
                totalResources.toArray(new Resource[] {}));

        final DMNRuntime runtime = typeSafeGetKieRuntime(kieContainer);
        Assert.assertNotNull(runtime);
        return runtime;
    }

    public static DMNRuntime typeSafeGetKieRuntime(final KieContainer kieContainer) {
        DMNRuntime dmnRuntime = kieContainer.newKieSession().getKieRuntime(DMNRuntime.class);
        ((DMNRuntimeImpl) dmnRuntime).setOption(new RuntimeTypeCheckOption(true));
        return dmnRuntime;
    }

    public static DMNRuntimeEventListener createListener() {
        return new DefaultDMNRuntimeEventListener() {
            private final Logger logger = LoggerFactory.getLogger(DMNRuntimeEventListener.class);

            @Override
            public void beforeEvaluateDecision(BeforeEvaluateDecisionEvent event) {
                logger.info(event.toString());
            }

            @Override
            public void afterEvaluateDecision(AfterEvaluateDecisionEvent event) {
                logger.info(event.toString());
            }

            @Override
            public void beforeEvaluateBKM(BeforeEvaluateBKMEvent event) {
                logger.info(event.toString());
            }

            @Override
            public void afterEvaluateBKM(AfterEvaluateBKMEvent event) {
                logger.info(event.toString());
            }

            @Override
            public void beforeEvaluateDecisionTable(BeforeEvaluateDecisionTableEvent event) {
                logger.info(event.toString());
            }

            @Override
            public void afterEvaluateDecisionTable(AfterEvaluateDecisionTableEvent event) {
                logger.info(event.toString());
            }
        };
    }

    public static String formatMessages(final List<DMNMessage> messages) {
        return messages.stream().map(Object::toString).peek(m -> LOG.debug(m)).collect(Collectors.joining("\n"));
    }

    private DMNRuntimeUtil() {
        // No constructor for util class.
    }

    public static KieContainer getKieContainerIgnoringErrors(ReleaseId releaseId,
                                                             Resource... resources) {
        KieServices ks = KieServices.Factory.get();
        createAndDeployJarIgnoringErrors(ks, releaseId, resources);
        return ks.newKieContainer(releaseId);
    }

    public static KieModule createAndDeployJarIgnoringErrors(KieServices ks,
                                                             ReleaseId releaseId,
                                                             Resource... resources) {
        byte[] jar = createJarIgnoringErrors(ks, releaseId, resources);

        KieModule km = KieHelper.deployJarIntoRepository(ks, jar);
        return km;
    }

    public static byte[] createJarIgnoringErrors(KieServices ks, ReleaseId releaseId, Resource... resources) {
        KieFileSystem kfs = ks.newKieFileSystem().generateAndWritePomXML(releaseId);
        for (int i = 0; i < resources.length; i++) {
            if (resources[i] != null) {
                kfs.write(resources[i]);
            }
        }
        KieBuilder kieBuilder = ks.newKieBuilder(kfs);
        ((InternalKieBuilder) kieBuilder).buildAll(o -> true);

        InternalKieModule kieModule = (InternalKieModule) ((InternalKieBuilder) kieBuilder).getKieModuleIgnoringErrors();

        byte[] jar = kieModule.getBytes();
        return jar;
    }
}


text:
package cuckoo

import (
	"crypto/sha256"
	"encoding/base64"
	"hash/fnv"
	"math/rand"
	"sync"
)

type entry []string

var (
	bucketSize int

	bucketLock sync.RWMutex
	buckets    []entry
)

const maxNumKicks = 500

func fingerprint(x string) string {
	newHash := sha256.New()
	return base64.StdEncoding.EncodeToString(newHash.Sum([]byte(x)))
}

func hash(x string) int {
	newHash := fnv.New32a()
	_, err := newHash.Write([]byte(x))
	if err != nil {
		panic(err)
	}
	return int(newHash.Sum32()) % bucketSize
}

// hasSpace returns an index pair if buckets[a] or buckets[b] has space to insert one more new value
func hasSpace(indexes ...int) (int, int) {
	for _, index := range indexes {
		for i := range buckets[index] {
			if buckets[index][i] == "" {
				return index, i
			}
		}
	}
	return -1, -1
}

// hasValue checks if the specific value in one of the bucket by given indexes
func hasValue(value string, indexes ...int) bool {
	for _, index := range indexes {
		if index >= len(buckets) {
			continue
		}
		for _, fp := range buckets[index] {
			if fp == value {
				return true
			}
		}
	}
	return false
}

// removeValue removes a value from buckets if it exists
func removeValue(value string, indexes ...int) bool {
	for _, index := range indexes {
		if index >= len(buckets) {
			continue
		}
		for i := range buckets[index] {
			if buckets[index][i] == value {
				buckets[index][i] = ""
				return true
			}
		}
	}

	return false
}

func addToBucket(index, candidate int, fp string) { buckets[index][candidate] = fp }

func randIndex(index ...int) int { return rand.Intn(len(index)) }

func randEntry(index int) int { return rand.Intn(len(buckets[index])) }

// Init initializes cuckoo filter buckets
func Init(size int) {
	bucketSize = size
	buckets = make([]entry, size)
	for i := range buckets {
		buckets[i] = make([]string, 4)
	}
}

// Insert inserts a new value into hash map
func Insert(value string) bool {
	fp := fingerprint(value)
	hashIndexOne := hash(value)
	hashIndexTwo := hashIndexOne ^ hash(fp)

	bucketLock.Lock()
	defer bucketLock.Unlock()

	if index, candidate := hasSpace(hashIndexOne, hashIndexTwo); index != -1 {
		addToBucket(index, candidate, fp)
		return true
	}
	// Must relocate existing items
	index := randIndex(hashIndexOne, hashIndexTwo)
	for n := 0; n < maxNumKicks; n++ {
		ent := randEntry(index)
		fp, buckets[index][ent] = buckets[index][ent], fp
		index = index ^ hash(fp)
		if index, candidate := hasSpace(index); index != -1 {
			addToBucket(index, candidate, fp)
			return true
		}
	}
	// Hash table is considered full
	return false
}

// LookUp checks if a given key in the hash map
func LookUp(value string) bool {
	fp := fingerprint(value)
	hashIndexOne := hash(value)
	hashIndexTwo := hashIndexOne ^ hash(fp)

	bucketLock.RLock()
	defer bucketLock.RUnlock()

	return hasValue(fp, hashIndexOne, hashIndexTwo)
}

// Delete removes an existing element from buckets if it exists
func Delete(value string) bool {
	fp := fingerprint(value)
	hashIndexOne := hash(value)
	hashIndexTwo := hashIndexOne ^ hash(fp)

	bucketLock.Lock()
	defer bucketLock.Unlock()

	return removeValue(fp, hashIndexOne, hashIndexTwo)
}


text:
namespace features {

#if BUILDFLAG(IS_ANDROID)
// Feature that enables Fast Checkout experiences on Android to help users
// speed up the checkout process.
extern const base::Feature kFastCheckout;

// Force enables fast checkout capabilities for every domain, regardless of
// the server response. The flag is meant for end-to-end testing purposes only.
extern const base::Feature kForceEnableFastCheckoutCapabilities;
#endif  // BUILDFLAG(IS_ANDROID)

}  // namespace features

#endif  // CHROME_BROWSER_FAST_CHECKOUT_FAST_CHECKOUT_FEATURES_H_


text:
<?php
/**
 * ALIPAY API: alipay.app.token.get request
 *
 * @author auto create
 * @since 1.0, 2014-05-15 12:14:54
 */
class AlipayAppTokenGetRequest
{
	/**
	 * 应用安全码
	 **/
	private $secret;

	private $apiParas = array();
	private $terminalType;
	private $terminalInfo;
	private $prodCode;
	private $apiVersion="1.0";
	private $notifyUrl;

	public function setSecret($secret)
	{
		$this->secret = $secret;
		$this->apiParas["secret"] = $secret;
	}

	public function getSecret()
	{
		return $this->secret;
	}

	public function getApiMethodName()
	{
		return "alipay.app.token.get";
	}

	public function setNotifyUrl($notifyUrl)
	{
		$this->notifyUrl=$notifyUrl;
	}

	public function getNotifyUrl()
	{
		return $this->notifyUrl;
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function getTerminalType()
	{
		return $this->terminalType;
	}

	public function setTerminalType($terminalType)
	{
		$this->terminalType = $terminalType;
	}

	public function getTerminalInfo()
	{
		return $this->terminalInfo;
	}

	public function setTerminalInfo($terminalInfo)
	{
		$this->terminalInfo = $terminalInfo;
	}

	public function getProdCode()
	{
		return $this->prodCode;
	}

	public function setProdCode($prodCode)
	{
		$this->prodCode = $prodCode;
	}

	public function setApiVersion($apiVersion)
	{
		$this->apiVersion=$apiVersion;
	}

	public function getApiVersion()
	{
		return $this->apiVersion;
	}

}


text:
var Body = require('../lib/body/Body');

/**
 * Contains methods for changing the velocity of a Matter Body. Should be used as a mixin and not called directly.
 *
 * @namespace Phaser.Physics.Matter.Components.Velocity
 * @since 3.0.0
 */
var Velocity = {

    /**
     * Sets the angular velocity of the body instantly.
     * Position, angle, force etc. are unchanged.
     *
     * @method Phaser.Physics.Matter.Components.Velocity#setAngularVelocity
     * @since 3.0.0
     *
     * @param {number} value - The angular velocity.
     *
     * @return {this} This Game Object instance.
     */
    setAngularVelocity: function (value)
    {
        Body.setAngularVelocity(this.body, value);

        return this;
    },

    /**
     * Sets the horizontal velocity of the physics body.
     *
     * @method Phaser.Physics.Matter.Components.Velocity#setVelocityX
     * @since 3.0.0
     *
     * @param {number} x - The horizontal velocity value.
     *
     * @return {this} This Game Object instance.
     */
    setVelocityX: function (x)
    {
        this._tempVec2.set(x, this.body.velocity.y);

        Body.setVelocity(this.body, this._tempVec2);

        return this;
    },

    /**
     * Sets vertical velocity of the physics body.
     *
     * @method Phaser.Physics.Matter.Components.Velocity#setVelocityY
     * @since 3.0.0
     *
     * @param {number} y - The vertical velocity value.
     *
     * @return {this} This Game Object instance.
     */
    setVelocityY: function (y)
    {
        this._tempVec2.set(this.body.velocity.x, y);

        Body.setVelocity(this.body, this._tempVec2);

        return this;
    },

    /**
     * Sets both the horizontal and vertical velocity of the physics body.
     *
     * @method Phaser.Physics.Matter.Components.Velocity#setVelocity
     * @since 3.0.0
     *
     * @param {number} x - The horizontal velocity value.
     * @param {number} [y=x] - The vertical velocity value, it can be either positive or negative. If not given, it will be the same as the `x` value.
     *
     * @return {this} This Game Object instance.
     */
    setVelocity: function (x, y)
    {
        this._tempVec2.set(x, y);

        Body.setVelocity(this.body, this._tempVec2);

        return this;
    }

};

module.exports = Velocity;


text:
using System;
using System.IO;
using p5.exp;
using p5.core;
using p5.mime.helpers;
using p5.exp.exceptions;
using MimeKit;

namespace p5.mime
{
    /// <summary>
    ///     Class wrapping the MIME parse features of Phosphorus Five.
    /// </summary>
    public static class MimeParserEvents
    {
        /// <summary>
        ///     Parses the MIME message given as string.
        /// </summary>
        /// <param name="context">Application Context</param>
        /// <param name="e">Active Event arguments</param>
        [ActiveEvent (Name = "p5.mime.parse")]
        public static void p5_mime_parse (ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning.
            using (new ArgsRemover (e.Args, true)) {

                // Looping through each MIME message supplied.
                foreach (var idxMimeMessage in XUtil.Iterate<string> (context, e.Args)) {

                    // Sanity check.
                    if (string.IsNullOrEmpty (idxMimeMessage))
                        throw new LambdaException (
                            "No MIME message provided to [p5.mime.parse]",
                            e.Args,
                            context);

                    // Loading MIME entity from stream.
                    using (var writer = new StreamWriter (new MemoryStream ())) {

                        // Writing MIME content to StreamWriter, flushing the stream, and setting stream's read head back to beginning.
                        writer.Write (idxMimeMessage);
                        writer.Flush ();
                        writer.BaseStream.Position = 0;

                        // Creating the MIME entity to hold our parsed content.
                        MimeEntity entity = null;

                        // Checking if an explicit [Content-Type] was supplied.
                        if (e.Args ["Content-Type"] != null)
                            entity = MimeEntity.Load (ContentType.Parse (e.Args ["Content-Type"].GetExValue<string> (context)), writer.BaseStream);
                        else
                            entity = MimeEntity.Load (writer.BaseStream);

                        // Creating our parser wrapper.
                        var parser = new helpers.MimeParser (
                            context,
                            e.Args,
                            entity,
                            e.Args.GetExChildValue<string> ("attachment-folder", context),
                            e.Args.GetExChildValue<bool> ("attachments-use-prefix", context, true));

                        // Parses the MimeEntity and stuffs results into e.Args node.
                        parser.Process ();
                    }
                }
            }
        }

        /// <summary>
        ///     Loads the file given as a string, and creates a MIME message from it.
        /// </summary>
        /// <param name="context">Application Context</param>
        /// <param name="e">Active Event arguments</param>
        [ActiveEvent (Name = "p5.mime.load")]
        public static void p5_mime_load (ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning.
            using (new ArgsRemover (e.Args, true)) {

                // Looping through each file supplied by caller.
                foreach (var idxMimeMessage in XUtil.Iterate<string> (context, e.Args)) {

                    // Sanity check.
                    if (string.IsNullOrEmpty (idxMimeMessage))
                        throw new LambdaException (
                            "No file supplied to [p5.mime.load]",
                            e.Args,
                            context);

                    // Retrieving output filename, unrolling path, and authorising that user has read access to file.
                    var filePath = idxMimeMessage;
                    filePath = context.RaiseEvent (".p5.io.unroll-path", new Node ("", filePath)).Get<string> (context);
                    context.RaiseEvent (".p5.io.authorize.read-file", new Node ("", filePath).Add ("args", e.Args));

                    // Creating a FileStream wrapping our file.
                    using (var reader = File.OpenRead (Common.GetRootFolder (context) + filePath)) {

                        // Creating our MIME entity.
                        MimeEntity entity = null;

                        // Checking if caller supplied an explicit [Content-Type].
                        if (e.Args ["Content-Type"] != null)
                            entity = MimeEntity.Load (ContentType.Parse (e.Args ["Content-Type"].GetExValue<string> (context)), reader);
                        else
                            entity = MimeEntity.Load (reader);

                        // Creating our MIME parser.
                        var parser = new helpers.MimeParser (
                            context,
                            e.Args,
                            entity,
                            e.Args.GetExChildValue<string> ("attachment-folder", context),
                            e.Args.GetExChildValue<bool> ("attachments-use-prefix", context, true));

                        // Parses the MimeEntity and stuffs the results into e.Args node.
                        parser.Process ();
                    }
                }
            }
        }

        /// <summary>
        ///     Parses the MIME message given as MimeEntity.
        /// </summary>
        /// <param name="context">Application Context</param>
        /// <param name="e">Active Event arguments</param>
        [ActiveEvent (Name = ".p5.mime.parse-native")]
        static void _p5_mime_parse_native (ApplicationContext context, ActiveEventArgs e)
        {
            // Retrieving MimeEntity from caller's arguments.
            var entity = e.Args.Get<MimeEntity> (context);

            // Creating our parser.
            var parser = new helpers.MimeParser (
                context,
                e.Args,
                entity,
                e.Args.GetExChildValue<string> ("attachment-folder", context),
                e.Args.GetExChildValue<bool> ("attachments-use-prefix", context, true));

            // Parses the MimeEntity and stuffs results into e.Args node.
            parser.Process ();
        }

        /// <summary>
        ///     Parses the MIME message given as a stream.
        /// </summary>
        /// <param name="context">Application Context</param>
        /// <param name="e">Active Event arguments</param>
        [ActiveEvent (Name = ".p5.mime.load-from-stream")]
        public static void _p5_mime_load_from_stream (ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning.
            using (new ArgsRemover (e.Args, true)) {

                // Sanity check.
                var tuple = e.Args.Value as Tuple<object, Stream>;
                if (tuple == null)
                    throw new LambdaException (
                        "No Tuple<object, Stream> provided to [.p5.mime.load-from-stream]",
                        e.Args,
                        context);
                var stream = tuple.Item2;
                if (stream == null)
                    throw new LambdaException (
                        "No stream provided to [.p5.mime.load-from-stream]",
                        e.Args,
                        context);

                // Creating our MIME entity.
                MimeEntity entity = null;

                // Checking if caller supplied an explicit [Content-Type].
                if (e.Args ["Content-Type"] != null)
                    entity = MimeEntity.Load (ContentType.Parse (e.Args ["Content-Type"].Get<string> (context)), stream);
                else
                    entity = MimeEntity.Load (stream);

                // Creating our parser.
                var parser = new helpers.MimeParser (
                    context,
                    e.Args,
                    entity,
                    e.Args.GetExChildValue<string> ("attachment-folder", context),
                    e.Args.GetExChildValue<bool> ("attachments-use-prefix", context, true));

                // Parses the MimeEntity and stuffs the results into e.Args node.
                parser.Process ();
            }
        }
    }
}


text:
package javaImportTool;

public class NodeInitializer {

	public NodeInitializer(String nodeType, String[][] children)
	{
		nodeType_ = nodeType;
		children_ = children;
	}

	public NodeInitializer(String nodeType, boolean isPersistenceUnit, String[][] children)
	{
		nodeType_ = nodeType;
		children_ = children;
		isPersistenceUnit_ = isPersistenceUnit;
	}

	public NodeInitializer(String nodeType, long initialValue)
	{
		nodeType_ = nodeType;
		initialLongValue_ = new Long(initialValue);
	}

	public NodeInitializer(String nodeType, double initialValue)
	{
		nodeType_ = nodeType;
		initialDoubleValue_ = new Double(initialValue);
	}

	public NodeInitializer(String nodeType, String initialValue)
	{
		nodeType_ = nodeType;
		initialStringValue_ = initialValue;
	}

	public NodeInitializer(String nodeType, String baseNodeType, String[][] children)
	{
		nodeType_ = nodeType;
		baseNodeType_ = baseNodeType;
		children_ = children;
	}

	public NodeInitializer(String nodeType, boolean isPersistenceUnit, String baseNodeType, String[][] children)
	{
		nodeType_ = nodeType;
		baseNodeType_ = baseNodeType;
		children_ = children;
		isPersistenceUnit_ = isPersistenceUnit;
	}

	public void initialize(Node node)
	{
		if (baseNodeType_ != null) NodeDescriptors.initialize(node, baseNodeType_);

		if (children_ != null)
			for (String[] childAttributes : children_)
				node.add(new Node(node, childAttributes[0], childAttributes[1]));

		if (initialDoubleValue_ != null) node.setDoubleValue(initialDoubleValue_);
		if (initialLongValue_ != null) node.setLongValue(initialLongValue_);
		if (initialStringValue_ != null) node.setStringValue(initialStringValue_);
	}

	private String nodeType_;
	private String baseNodeType_;
	private String[][] children_;

	private Double initialDoubleValue_;
	private Long initialLongValue_;
	private String initialStringValue_;

	private boolean isPersistenceUnit_ = false;

	public String nodeType() { return nodeType_; }
	public boolean isPersistenceUnit() { return isPersistenceUnit_; }
}


text:
from __future__ import absolute_import, print_function

import os.path
from uuid import uuid4
from functools import wraps

import warnings
import logging
logger = logging.getLogger(__file__)

from six import add_metaclass, iteritems
from six.moves.urllib.parse import urlsplit

from .embed import autoload_static, autoload_server
from .properties import HasProps, MetaHasProps, Instance
from .protocol import serialize_json
from .utils import get_ref, convert_references, dump

class Viewable(MetaHasProps):
    """ Any plot object (Data Model) which has its own View Model in the
    persistence layer.

    Adds handling of a __view_model__ attribute to the class (which is
    provided by default) which tells the View layer what View class to
    create.

    One thing to keep in mind is that a Viewable should have a single
    unique representation in the persistence layer, but it might have
    multiple concurrent client-side Views looking at it.  Those may
    be from different machines altogether.
    """

    # Stores a mapping from subclass __view_model__ names to classes
    model_class_reverse_map = {}

    # Mmmm.. metaclass inheritance.  On the one hand, it seems a little
    # overkill. On the other hand, this is exactly the sort of thing
    # it's meant for.
    def __new__(cls, class_name, bases, class_dict):
        if "__view_model__" not in class_dict:
            class_dict["__view_model__"] = class_name
        class_dict["get_class"] = Viewable.get_class

        # Create the new class
        newcls = super(Viewable,cls).__new__(cls, class_name, bases, class_dict)
        entry = class_dict["__view_model__"]
        # Add it to the reverse map, but check for duplicates first
        if entry in Viewable.model_class_reverse_map:
            raise Warning("Duplicate __view_model__ declaration of '%s' for " \
                          "class %s.  Previous definition: %s" % \
                          (entry, class_name,
                           Viewable.model_class_reverse_map[entry]))
        Viewable.model_class_reverse_map[entry] = newcls
        return newcls

    @classmethod
    def _preload_models(cls):
        from . import objects, widgetobjects

    @classmethod
    def get_class(cls, view_model_name):
        """ Given a __view_model__ name, returns the corresponding class
        object
        """
        cls._preload_models()
        d = Viewable.model_class_reverse_map
        if view_model_name in d:
            return d[view_model_name]
        else:
            raise KeyError("View model name '%s' not found" % view_model_name)

def usesession(meth):
    """ Checks for 'session' in kwargs and in **self**, and guarantees
    that **kw** always has a valid 'session' parameter.  Wrapped methods
    should define 'session' as an optional argument, and in the body of
    the method, should expect an
    """
    @wraps(meth)
    def wrapper(self, *args, **kw):
        session = kw.get("session", None)
        if session is None:
            session = getattr(self, "session")
        if session is None:
            raise RuntimeError("Call to %s needs a session" % meth.__name__)
        kw["session"] = session
        return meth(self, *args, **kw)
    return wrapper

def is_ref(frag):
    return isinstance(frag, dict) and \
           frag.get('type') and \
           frag.get('id')

def json_apply(fragment, check_func, func):
    """recursively searches through a nested dict/lists
    if check_func(fragment) is True, then we return
    func(fragment)
    """
    if check_func(fragment):
        return func(fragment)
    elif isinstance(fragment, list):
        output = []
        for val in fragment:
            output.append(json_apply(val, check_func, func))
        return output
    elif isinstance(fragment, dict):
        output = {}
        for k, val in fragment.items():
            output[k] = json_apply(val, check_func, func)
        return output
    else:
        return fragment

def resolve_json(fragment, models):
    check_func = is_ref
    def func(fragment):
        if fragment['id'] in models:
            return models[fragment['id']]
        else:
            logging.error("model not found for %s", fragment)
            return None
    return json_apply(fragment, check_func, func)

@add_metaclass(Viewable)
class PlotObject(HasProps):
    """ Base class for all plot-related objects """

    session = Instance(".session.Session")

    def __init__(self, **kwargs):
        # Eventually should use our own memo instead of storing
        # an attribute on the class
        if "id" in kwargs:
            self._id = kwargs.pop("id")
        else:
            self._id = str(uuid4())

        self._dirty = True
        self._callbacks_dirty = False
        self._callbacks = {}
        self._callback_queue = []
        self._block_callbacks = False

        block_events = kwargs.pop('_block_events', False)

        if not block_events:
            super(PlotObject, self).__init__(**kwargs)
            self.setup_events()
        else:
            self._block_callbacks = True
            super(PlotObject, self).__init__(**kwargs)

    def get_ref(self):
        return {
            'type': self.__view_model__,
            'id': self._id,
        }

    def setup_events(self):
        pass

    @classmethod
    def load_json(cls, attrs, instance=None):
        """Loads all json into a instance of cls, EXCEPT any references
        which are handled in finalize
        """
        if 'id' not in attrs:
            raise RuntimeError("Unable to find 'id' attribute in JSON: %r" % attrs)
        _id = attrs.pop('id')

        if not instance:
            instance = cls(id=_id, _block_events=True)

        _doc = attrs.pop("doc", None)

        ref_props = {}
        for p in instance.properties_with_refs():
            if p in attrs:
                ref_props[p] = attrs.pop(p)

        special_props = {}
        for p in dict(attrs):
            if p not in instance.properties():
                special_props[p] = attrs.pop(p)

        instance._ref_props = ref_props
        instance._special_props = special_props

        instance.update(**attrs)
        return instance

    def finalize(self, models):
        """Convert any references into instances
        models is a dict of id->model mappings
        """
        if hasattr(self, "_ref_props"):
            return resolve_json(self._ref_props, models)
        else:
            return {}

    @classmethod
    def collect_plot_objects(cls, *input_objs):
        """ Iterate over ``input_objs`` and descend through their structure
        collecting all nested ``PlotObjects`` on the go. The resulting list
        is duplicate-free based on objects' identifiers.
        """
        ids = set([])
        objs = []

        def descend_props(obj):
            for attr in obj.properties_with_refs():
                descend(getattr(obj, attr))

        def descend(obj):
            if isinstance(obj, PlotObject):
                if obj._id not in ids:
                    ids.add(obj._id)
                    descend_props(obj)
                    objs.append(obj)
            elif isinstance(obj, HasProps):
                descend_props(obj)
            elif isinstance(obj, (list, tuple)):
                for item in obj:
                    descend(item)
            elif isinstance(obj, dict):
                for key, value in iteritems(obj):
                    descend(key); descend(value)

        descend(input_objs)
        return objs

    def references(self):
        """Returns all ``PlotObjects`` that this object has references to. """
        return set(self.collect_plot_objects(self))

    #---------------------------------------------------------------------
    # View Model connection methods
    #
    # Whereas a rich client rendering framework can maintain view state
    # alongside model state, we need an explicit send/receive protocol for
    # communicating with a set of view models that reside on the front end.
    # Many of the calls one would expect in a rich client map instead to
    # batched updates on the M-VM-V approach.
    #---------------------------------------------------------------------
    def vm_props(self):
        """ Returns the ViewModel-related properties of this object. """
        props = self.changed_properties_with_values()
        props.pop("session", None)
        return props

    def vm_serialize(self):
        """ Returns a dictionary of the attributes of this object, in
        a layout corresponding to what BokehJS expects at unmarshalling time.
        """
        attrs = self.vm_props()
        attrs['id'] = self._id
        return attrs

    def dump(self, docid=None):
        """convert all references to json
        """
        models = self.references()
        return dump(models, docid=docid)

    def update(self, **kwargs):
        for k,v in kwargs.items():
            setattr(self, k, v)

    def __str__(self):
        return "%s, ViewModel:%s, ref _id: %s" % (self.__class__.__name__,
                self.__view_model__, getattr(self, "_id", None))

    def on_change(self, attrname, obj, callbackname=None):
        """when attrname of self changes, call callbackname
        on obj
        """
        callbacks = self._callbacks.setdefault(attrname, [])
        callback = dict(obj=obj, callbackname=callbackname)
        if callback not in callbacks:
            callbacks.append(callback)
        self._callbacks_dirty = True

    def _trigger(self, attrname, old, new):
        """attrname of self changed.  So call all callbacks
        """
        callbacks = self._callbacks.get(attrname)
        if callbacks:
            for callback in callbacks:
                obj = callback.get('obj')
                callbackname = callback.get('callbackname')
                fn = obj if callbackname is None else getattr(obj, callbackname)
                fn(self, attrname, old, new)

    # TODO: deprecation warnign about args change (static_path)
    def create_html_snippet(
            self, server=False, embed_base_url="", embed_save_loc=".",
            static_path="http://localhost:5006/bokehjs/static"):
        """create_html_snippet is used to embed a plot in an html page.

        create_html_snippet returns the embed string to be put in html.
        This will be a <script> tag.

        To embed a plot dependent on the Bokeh Plot Server, set server=True,
        otherwise a file with the data for the plot will be built.

        embed_base_url is used for non-server embedding.  This is used
        as the root of the url where the embed.js file will be saved.

        embed_save_loc controls where the embed.js will be actually written to.

        static_path controls where the embed snippet looks to find
        bokeh.js and the other resources it needs for bokeh.
        """
        if server:
            from .session import Session
            if embed_base_url:
                session = Session(root_url=server_url)
            else:
                session = Session()
            return autoload_server(self, session)

        from .templates import AUTOLOAD, AUTOLOAD_STATIC
        import uuid

        js_filename = "%s.embed.js" % self._id
        script_path = embed_base_url + js_filename

        elementid = str(uuid.uuid4())

        js = AUTOLOAD.render(
            all_models = serialize_json(self.dump()),
            js_url = static_path + "js/bokeh.min.js",
            css_files = [static_path + "css/bokeh.min.css"],
            elementid = elementid,
        )

        tag = AUTOLOAD_STATIC.render(
            src_path = script_path,
            elementid = elementid,
            modelid = self._id,
            modeltype = self.__view_model__,
        )

        save_path = os.path.join(embed_save_loc, js_filename)
        with open(save_path,"w") as f:
            f.write(js)

        return tag

    def inject_snippet(
            self, server=False, embed_base_url="", embed_save_loc=".",
            static_path="http://localhost:5006/bokeh/static/"):
        warnings.warn("inject_snippet is deprecated, please use create_html_snippet")
        return self.create_html_snippet(
            server, embed_base_url, embed_save_loc, static_path)

    def _build_server_snippet(self, base_url=False):
        sess = self._session
        modelid = self._id
        typename = self.__view_model__
        if not base_url:
            base_url = sess.root_url
        split = urlsplit(base_url)
        if split.scheme == 'http':
            ws_conn_string = "ws://%s/bokeh/sub" % split.netloc
        else:
            ws_conn_string = "wss://%s/bokeh/sub" % split.netloc

        f_dict = dict(
            docid = sess.docid,
            ws_conn_string = ws_conn_string,
            docapikey = sess.apikey,
            root_url = base_url,
            modelid = modelid,
            modeltype = typename,
            script_url = base_url + "bokeh/embed.js")
        e_str = '''<script src="%(script_url)s" bokeh_plottype="serverconn"
        bokeh_docid="%(docid)s" bokeh_ws_conn_string="%(ws_conn_string)s"
        bokeh_docapikey="%(docapikey)s" bokeh_root_url="%(root_url)s"
        bokeh_modelid="%(modelid)s" bokeh_modeltype="%(modeltype)s" async="true"></script>
        '''
        return "", e_str % f_dict

    def _build_static_embed_snippet(self, static_path, embed_base_url):

        embed_filename = "%s.embed.js" % self._id
        full_embed_path = embed_base_url + embed_filename

        js_str = self._session.embed_js(self._id, static_path)

        sess = self._session
        modelid = self._id
        typename = self.__view_model__
        embed_filename = full_embed_path
        f_dict = dict(modelid = modelid, modeltype = typename,
                      embed_filename=embed_filename)
        e_str = '''<script src="%(embed_filename)s" bokeh_plottype="embeddata"
        bokeh_modelid="%(modelid)s" bokeh_modeltype="%(modeltype)s" async="true"></script>
        '''
        return js_str, e_str % f_dict


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Promotion" table="promotion">
    <id name="idpromotion" type="integer" column="idpromotion">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="numPromotion" type="integer" column="num_promotion" nullable="true"/>
  </entity>
</doctrine-mapping>


text:
package org.ojalgo.random.process;

/**
 * A random field is a generalization of a stochastic process such that the underlying parameter need no
 * longer be a simple real or integer valued "time", but can instead take values that are multidimensional
 * vectors, or points on some manifold.
 *
 * @author apete
 */
abstract class RandomField<T> {

    RandomField() {
        super();
    }

}


text:
<?php

/* SMASMABundle:Public:showmember.html.twig */
class __TwigTemplate_2113f9e63cb85f29ea8e0a310bc75ff66b21ab612aaddcf13aa20cbb60b88c88 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("SMASMABundle:Public:template.html.twig");

        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "SMASMABundle:Public:template.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "
User

                Username
                ";
        // line 10
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "username"), "html", null, true);
        echo "

                Password
                ";
        // line 14
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "password"), "html", null, true);
        echo "

                Nama
                ";
        // line 18
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "nama"), "html", null, true);
        echo "

                Status
                ";
        // line 22
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "status"), "html", null, true);
        echo "

                Email
                ";
        // line 26
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "email"), "html", null, true);
        echo "

                Alamat
                ";
        // line 30
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "alamat"), "html", null, true);
        echo "

        env, $this->env->getExtension('routing')->getPath("memberedit", array("id" => $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "id"))), "html", null, true);
        echo "\">
        Edit

";
    }

    public function getTemplateName()
    {
        return "SMASMABundle:Public:showmember.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  83 => 36,  74 => 30,  67 => 26,  60 => 22,  53 => 18,  46 => 14,  39 => 10,  31 => 4,  28 => 3,);
    }
}


text:
package pl.solaris.showcasefragment;

import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;

/**
 * Created by pbednarz on 2015-01-20.
 */
public class ShowcaseFragment extends Fragment implements View.OnClickListener {

    private static final String ARG_STYLE_ID = "style_id";
    private static final String ARG_VIEW_ID = "view_id";
    private static final String ARG_SC_TITLE = "sc_title";
    private static final String ARG_SC_DESC = "sc_desc";
    private static final String ARG_SC_OK = "sc_ok";
    private ShowcaseLayout root;

    public static void startShowcase(final FragmentActivity activity,
                                     final View targetView,
                                     String title,
                                     String description,
                                     String ok) {
        startShowcase(activity, targetView, title, description, ok, 0);
    }

    public static void startShowcase(final FragmentActivity activity,
                                     final View targetView,
                                     String title,
                                     String description,
                                     String ok,
                                     @StyleRes int style) {
        FragmentTransaction ft = activity.getSupportFragmentManager()
                .beginTransaction();
        ft.add(android.R.id.content, ShowcaseFragment.newInstance(targetView, title, description, ok, style));
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.addToBackStack(null);
        ft.commit();
    }

    public static ShowcaseFragment newInstance(View targetView,
                                               String title,
                                               String description,
                                               String ok,
                                               int style) {
        ShowcaseFragment fragment = new ShowcaseFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_VIEW_ID, targetView.getId());
        args.putString(ARG_SC_TITLE, title);
        args.putInt(ARG_STYLE_ID, style);
        args.putString(ARG_SC_DESC, description);
        args.putString(ARG_SC_OK, ok);
        fragment.setArguments(args);
        return fragment;
    }

    private static Bitmap loadBitmapFromView(View v) {
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache(true));
        v.setDrawingCacheEnabled(false);
        return bitmap;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        int styleId = getArguments().getInt(ARG_STYLE_ID, 0);
        root = new ShowcaseLayout(getActivity()
                , null
                , ((styleId > 0) ? 0 : R.attr.scf_style),
                styleId);
        root.setOnDoneClickListener(this);
        root.setData(getArguments().getString(ARG_SC_TITLE, ""),
                getArguments().getString(ARG_SC_DESC, ""),
                getArguments().getString(ARG_SC_OK, ""));
        return root;
    }

    @Override
    public void onDestroyView() {
        root = null;
        super.onDestroyView();
    }

    @Override
    public void onStart() {
        super.onStart();
        getTargetView();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getTargetView();
    }

    private void getTargetView() {
        if (getActivity() != null) {
            final View view = getActivity().findViewById(getArguments().getInt(ARG_VIEW_ID));
            if (view != null) {
                view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        view.getViewTreeObserver().removeOnPreDrawListener(this);
                        show(view);
                        return false;
                    }
                });
            }
        }
    }

    private void show(View targetView) {
        if (targetView != null) {
            Bitmap bmp = loadBitmapFromView(targetView);
            ImageView targetSpot = root.getTargetSpot();
            targetSpot.setImageBitmap(bmp);
            int imageWidth = bmp.getWidth();
            int imageHeight = bmp.getHeight();
            View windowRoot = getActivity().getWindow().getDecorView().findViewById(android.R.id.content);
            int[] viewLocation = new int[2];
            int[] viewLocationDestination = new int[2];
            targetView.getLocationOnScreen(viewLocation);
            windowRoot.getLocationOnScreen(viewLocationDestination);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) targetSpot.getLayoutParams();
            params.leftMargin = viewLocation[0] - viewLocationDestination[0];
            params.topMargin = viewLocation[1] - viewLocationDestination[1];
            targetSpot.setLayoutParams(params);
            root.setCircleBounds(imageWidth, imageHeight, params.topMargin, params.leftMargin);
        }
    }

    @Override
    public void onClick(View v) {
        try {
            ((ShowcaseListener) getActivity()).onShowcaseClose();
        } catch (ClassCastException ignored) {
            getActivity().onBackPressed();
        }
    }

    public static interface ShowcaseListener {
        public void onShowcaseClose();
    }
}