text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ SODA Android SDK - Socrata, Inc
  ~
  ~ Copyright (C) 2013 Socrata, Inc
  ~ All rights reserved.
  ~
  ~ Developed for Socrata, Inc by:
  ~ 47 Degrees, LLC
  ~ http://47deg.com
  ~ hello@47deg.com
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.socrata.soda.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="25" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:label="@string/app_name" >
    </application>

</manifest>


text:
package main

import "net/http"
import "sync"
import "html/template"
import "github.com/gorilla/sessions"
import "github.com/gorilla/csrf"
import "github.com/gorilla/mux"
import "github.com/anaminus/rbxweb"
import "time"

var Store *sessions.CookieStore
var Client *rbxweb.Client

type PassportHTTPInterface struct {
    Address string
}

type ServePageOptions struct {
    Name string
    Writer http.ResponseWriter
    Request *http.Request
    Data map[string]interface{}
    Files []string
}
var VerificationTimers map[int64]*time.Timer

func NewServePageOptions(Name string, Writer http.ResponseWriter, Request *http.Request) *ServePageOptions {
    return &ServePageOptions{Name: Name, Writer: Writer, Request: Request}
}

func PreHandlerFunction(Writer http.ResponseWriter, Request *http.Request) {
    Session, _ := Store.Get(Request, "CCPassportSession")

    if Session.Values["Username"] == nil {
        Session.Values["Username"] = ""
        Session.Values["User"] = -1
        err := Session.Save(Request, Writer)
        if err != nil {
            print("Failed to save session because, " + err.Error())
        }
    }
}

func ServePage(Options *ServePageOptions) {
    Session, _ := Store.Get(Options.Request, "CCPassportSession")

    if Options.Data == nil {
        Options.Data = make(map[string]interface{})
    }

    Options.Data["CurrentPage"] = Options.Name
    Options.Data["Session"] = Session.Values
    Options.Data[csrf.TemplateTag] = csrf.TemplateField(Options.Request)
    Breadcrumbs, err := GetBreadcrumbs(Options.Request.URL.Path)
    if err != nil {
        http.Error(Options.Writer, "Failed to populate service data: " + err.Error(), http.StatusInternalServerError)
        return
    }
    Options.Data["Breadcrumbs"] = Breadcrumbs

    Options.Files = append(Options.Files, "views/" + Options.Name + ".html", "views/header.html", "views/footer.html", "views/breadcrumbs.html")

    Template := template.New(Options.Name + ".html").Funcs(fns)

    Template, err = Template.ParseFiles(Options.Files...)
    if err != nil {
        http.Error(Options.Writer, err.Error(), http.StatusInternalServerError)
        return
    }

    err = Template.Execute(Options.Writer, Options.Data)
    if err != nil {
        http.Error(Options.Writer, err.Error(), http.StatusInternalServerError)
        return
    }
}

func IndexHandler(Writer http.ResponseWriter, Request *http.Request) {
    ServePage(NewServePageOptions("index", Writer, Request))
}

func HandleExact(Mux *mux.Router, Route string, Function func(http.ResponseWriter, *http.Request) ()) {
    Mux.HandleFunc(Route, func(Writer http.ResponseWriter, Request *http.Request) {
        if Request.URL.Path != Route {
            http.NotFound(Writer, Request)
            return
        }
        PreHandlerFunction(Writer, Request)
        Function(Writer, Request)
    })
}

func (Interface *PassportHTTPInterface) Start(wg *sync.WaitGroup, SecretKey []byte, RobloxUN string, RobloxPW string) {
    Client = rbxweb.NewClient()
    if err := Client.Login(RobloxUN, RobloxPW); err != nil {
        panic(err)
    }
    VerificationTimers = make(map[int64]*time.Timer)
    wg.Add(1)
    go func() {
        defer wg.Done()
        Store = sessions.NewCookieStore(SecretKey)
        Mux := mux.NewRouter()
        HandleExact(Mux, "/", IndexHandler)
        HandleExact(Mux, "/signup", SignupPageHandler)
        HandleExact(Mux, "/login", LoginPageHandler)
        HandleExact(Mux, "/logout", LogoutPageHandler)
        HandleExact(Mux, "/identities/4096/link", LinkRobloxPageHandler)
        HandleExact(Mux, "/identities", IdentitiesPageHandler)
        Mux.HandleFunc("/identities/{ServiceID:[0-9]+}", IdentityPageHandler)
        Mux.HandleFunc("/identities/{ServiceID:[0-9]+}/unlink/{ExtID}", UnlinkHandler)
        Mux.HandleFunc("/identities/{ServiceID:[0-9]+}/change-key", ChangeKeyHandler)
        Mux.HandleFunc("/identities/{ServiceID:[0-9]+}/delete-encryption", DeleteIdentityHandler)
        Mux.HandleFunc("/identities/{ServiceID:[0-9]+}/{BlobURLForm:(?:public|private)}", BlobPageHandler)
        Mux.HandleFunc("/enter-sudo", EnterSudoPageHandler)
        http.ListenAndServe(Interface.Address, csrf.Protect(SecretKey)(Mux))
    }()
}

func NewHTTPInterface(Address string) *PassportHTTPInterface {
    return &PassportHTTPInterface{Address}
}

redpajama_set_name: RedPajamaGithub


text:
package oshi.demo.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.Timer;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;

import oshi.PlatformEnum;
import oshi.SystemInfo;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.util.FormatUtil;

/**
 * Displays used and free space on all filesystems.
 */
public class FileStorePanel extends OshiJPanel { // NOSONAR squid:S110

    private static final long serialVersionUID = 1L;

    private static final String USED = "Used";
    private static final String AVAILABLE = "Available";

    public FileStorePanel(SystemInfo si) {
        super();
        init(si.getOperatingSystem().getFileSystem());
    }

    private void init(FileSystem fs) {
        List<OSFileStore> fileStores = fs.getFileStores();
        @SuppressWarnings("unchecked")
        DefaultPieDataset<String>[] fsData = new DefaultPieDataset[fileStores.size()];
        JFreeChart[] fsCharts = new JFreeChart[fsData.length];

        JPanel fsPanel = new JPanel();
        fsPanel.setLayout(new GridBagLayout());
        GridBagConstraints fsConstraints = new GridBagConstraints();
        fsConstraints.weightx = 1d;
        fsConstraints.weighty = 1d;
        fsConstraints.fill = GridBagConstraints.BOTH;

        int modBase = (int) (fileStores.size() * (Config.GUI_HEIGHT + Config.GUI_WIDTH)
                / (Config.GUI_WIDTH * Math.sqrt(fileStores.size())));
        for (int i = 0; i < fileStores.size(); i++) {
            fsData[i] = new DefaultPieDataset<>();
            fsCharts[i] = ChartFactory.createPieChart(null, fsData[i], true, true, false);
            configurePlot(fsCharts[i]);
            fsConstraints.gridx = i % modBase;
            fsConstraints.gridy = i / modBase;
            fsPanel.add(new ChartPanel(fsCharts[i]), fsConstraints);
        }
        updateDatasets(fs, fsData, fsCharts);

        add(fsPanel, BorderLayout.CENTER);

        Timer timer = new Timer(Config.REFRESH_SLOWER, e -> {
            if (!updateDatasets(fs, fsData, fsCharts)) {
                ((Timer) e.getSource()).stop();
                fsPanel.removeAll();
                init(fs);
                fsPanel.revalidate();
                fsPanel.repaint();
            }
        });
        timer.start();
    }

    private static boolean updateDatasets(FileSystem fs, DefaultPieDataset<String>[] fsData, JFreeChart[] fsCharts) {
        List<OSFileStore> fileStores = fs.getFileStores();
        if (fileStores.size() != fsData.length) {
            return false;
        }
        int i = 0;
        for (OSFileStore store : fileStores) {
            fsCharts[i].setTitle(store.getName());
            List<TextTitle> subtitles = new ArrayList<>();
            if (SystemInfo.getCurrentPlatform().equals(PlatformEnum.WINDOWS)) {
                subtitles.add(new TextTitle(store.getLabel()));
            }
            long usable = store.getUsableSpace();
            long total = store.getTotalSpace();
            subtitles.add(new TextTitle(
                    "Available: " + FormatUtil.formatBytes(usable) + "/" + FormatUtil.formatBytes(total)));
            fsCharts[i].setSubtitles(subtitles);
            fsData[i].setValue(USED, (double) total - usable);
            fsData[i].setValue(AVAILABLE, usable);
            i++;
        }
        return true;
    }

    private static void configurePlot(JFreeChart chart) {
        @SuppressWarnings("unchecked")
        PiePlot<String> plot = (PiePlot<String>) chart.getPlot();
        plot.setSectionPaint(USED, Color.red);
        plot.setSectionPaint(AVAILABLE, Color.green);
        plot.setExplodePercent(USED, 0.10);
        plot.setSimpleLabels(true);

        PieSectionLabelGenerator labelGenerator = new StandardPieSectionLabelGenerator("{0}: {1} ({2})",
                new DecimalFormat("0"), new DecimalFormat("0%"));
        plot.setLabelGenerator(labelGenerator);
    }

}


text:
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using PlayOnline.Core;
using PlayOnline.Core.Audio;

namespace PlayOnline.Utils.AudioManager
{
    public partial class InfoBuilder : Form
    {
        public InfoBuilder()
        {
            InitializeComponent();
            this.prbApplication.Select();
        }

        private TreeNode TargetNode_;

        public TreeNode TargetNode
        {
            get { return this.TargetNode_; }
            set { this.TargetNode_ = value; }
        }

        private string FileTypeName_;

        public string FileTypeName
        {
            get { return this.FileTypeName_; }
            set { this.FileTypeName_ = value; }
        }

        private string ResourceName_;

        public string ResourceName
        {
            get { return this.ResourceName_; }
            set { this.ResourceName_ = value; }
        }

        private string FilePattern_;

        public string FilePattern
        {
            get { return this.FilePattern_; }
            set { this.FilePattern_ = value; }
        }

        public void Run()
        {
            Stream InfoData = Assembly.GetExecutingAssembly().GetManifestResourceStream(this.ResourceName_);
            if (InfoData != null)
            {
                XmlReader XR = new XmlTextReader(InfoData);
                try
                {
                    XmlDocument XD = new XmlDocument();
                    XD.Load(XR);
                    XmlNodeList Apps = XD.SelectNodes("/pol-audio-data/application");
                    this.txtApplication.Text = null;
                    this.prbApplication.Value = 0;
                    this.prbApplication.Maximum = Apps.Count;
                    foreach (XmlNode App in Apps)
                    {
                        try
                        {
                            string AppName = App.Attributes["name"].InnerText;
                            this.txtApplication.Text = String.Format("[{0}/{1}] {2}", this.prbApplication.Value + 1,
                                this.prbApplication.Maximum, AppName);
                            this.txtDirectory.Text = "Scanning...";
                            this.txtFile.Text = "Scanning...";
                            this.prbDirectory.Value = 0;
                            this.prbFile.Value = 0;
                            Application.DoEvents();
                            string AppPath = POL.GetApplicationPath(App.Attributes["id"].InnerText);
                            if (AppPath != null)
                            {
                                TreeNode AppNode = new TreeNode(AppName);
                                AppNode.ImageIndex = 1;
                                AppNode.SelectedImageIndex = 1;
                                AppNode.Tag = AppPath;
                                XmlNodeList DataPaths = App.SelectNodes("data-path");
                                // Precompute totals for directories/files
                                this.prbDirectory.Maximum = 0;
                                this.prbFile.Maximum = 0;
                                foreach (XmlNode DataPath in DataPaths)
                                {
                                    this.PreScanDataPath(Path.Combine(AppPath,
                                        DataPath.InnerText.Replace('/', Path.DirectorySeparatorChar)));
                                }
                                ++this.prbApplication.Value;
                                // Now do a full scan
                                foreach (XmlNode DataPath in DataPaths)
                                {
                                    this.ScanDataPath(App,
                                        Path.Combine(AppPath, DataPath.InnerText.Replace('/', Path.DirectorySeparatorChar)), AppNode);
                                }
                                if (AppNode.Nodes.Count > 0)
                                {
                                    this.TargetNode_.Nodes.Add(AppNode);
                                }
                            }
                            else
                            {
                                ++this.prbApplication.Value;
                            }
                        }
                        catch (Exception E)
                        {
                            Console.WriteLine(E.ToString());
                        }
                    }
                }
                catch (Exception E)
                {
                    Console.WriteLine(E.ToString());
                }
                XR.Close();
                InfoData.Close();
            }
        }

        private void PreScanDataPath(string DataPath)
        {
            if (!Directory.Exists(DataPath))
            {
                return;
            }
            ++this.prbDirectory.Maximum;
            this.prbFile.Maximum += Directory.GetFiles(DataPath, this.FilePattern_).Length;
            foreach (string SubDir in Directory.GetDirectories(DataPath))
            {
                this.PreScanDataPath(SubDir);
            }
        }

        private void ScanDataPath(XmlNode App, string DataPath, TreeNode AppNode)
        {
            if (!Directory.Exists(DataPath))
            {
                return;
            }
            this.txtDirectory.Text = String.Format("[{0}/{1}] {2}", this.prbDirectory.Value + 1, this.prbDirectory.Maximum, DataPath);
            Application.DoEvents();
            foreach (string File in Directory.GetFiles(DataPath, this.FilePattern_))
            {
                this.txtFile.Text = String.Format("[{0}/{1}] {2}", this.prbFile.Value + 1, this.prbFile.Maximum,
                    Path.GetFileName(File));
                Application.DoEvents();
                AudioFile AF = new AudioFile(File);
                if (AF.Type != AudioFileType.Unknown)
                {
                    FileInfo FI = new FileInfo(App, AF);
                    TreeNode FileNode =
                        new TreeNode(String.Format("[{0}] {1}", AF.ID, ((FI.Title == null) ? Path.GetFileName(File) : FI.Title)));
                    FileNode.ImageIndex = 3;
                    FileNode.SelectedImageIndex = 3;
                    FileNode.Tag = FI;
                    AppNode.Nodes.Add(FileNode);
                }
                ++this.prbFile.Value;
            }
            ++this.prbDirectory.Value;
            // Recurse
            foreach (string SubDir in Directory.GetDirectories(DataPath))
            {
                TreeNode DirNode = new TreeNode(Path.GetFileName(SubDir));
                DirNode.ImageIndex = 1;
                DirNode.SelectedImageIndex = 1;
                FileInfo FI = new FileInfo(App, SubDir);
                DirNode.Tag = FI;
                if (FI.Title != null)
                {
                    DirNode.Text += String.Format(" - {0}", FI.Title);
                }
                this.ScanDataPath(App, SubDir, DirNode);
                if (DirNode.Nodes.Count > 0)
                {
                    AppNode.Nodes.Add(DirNode);
                }
            }
        }

        private bool Running = false;

        private void InfoBuilder_VisibleChanged(object sender, System.EventArgs e)
        {
            if (this.TargetNode == null)
            {
                throw new InvalidOperationException("No target node set.");
            }
            lock (this)
            {
                if (this.Running)
                {
                    return;
                }
                this.Running = true;
            }
            this.Show();
            Application.DoEvents();
            this.Activate();
            Application.DoEvents();
            this.Refresh();
            Application.DoEvents();
            this.Run();
            this.Close();
        }
    }
}


text:
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Platform.WPF;

namespace MediaManager.Forms
{
    public static partial class ImageSourceExtensions
    {
        public static async Task<System.Windows.Media.ImageSource> ToNative(this ImageSource source)
        {
            var imageHandler = source.GetImageSourceHandler();
            if (imageHandler == null)
                return null;

            return await imageHandler.LoadImageAsync(source).ConfigureAwait(false);
        }

        public static IImageSourceHandler GetImageSourceHandler(this ImageSource source)
        {
            //check the specific source type and return the correct image source handler
            switch (source)
            {
                case FileImageSource _:
                    return new FileImageSourceHandler();
                case StreamImageSource _:
                    return new StreamImageSourceHandler();
                case FontImageSource _:
                case UriImageSource _:
                default:
                    return new UriImageSourceHandler();
            }
        }
    }
}


text:
<?php

namespace KoolKode\Domain;

use KoolKode\Util\UUID;

abstract class DomainEvent { }


text:
package org.lobobrowser.primary.gui;

public enum FieldType {
  TEXT, PASSWORD
}


text:
from __future__ import absolute_import

from conda_kapsel.conda_manager import (push_conda_manager_class, pop_conda_manager_class, new_conda_manager,
                                        CondaManager)

def test_use_non_default_conda_manager():
    called = dict()

    class MyCondaManager(CondaManager):
        def find_environment_deviations(self, *args):
            called['find_environment_deviations'] = args

        def fix_environment_deviations(self, *args):
            called['fix_environment_deviations'] = args

        def remove_packages(self, *args):
            called['remove_packages'] = args

    push_conda_manager_class(MyCondaManager)
    try:
        manager = new_conda_manager()
        manager.find_environment_deviations(None, None)
        manager.fix_environment_deviations(None, None)
        manager.remove_packages(None, None)
        assert dict(find_environment_deviations=(None, None),
                    fix_environment_deviations=(None, None),
                    remove_packages=(None, None)) == called
    finally:
        pop_conda_manager_class()


text:
#ifndef EventQueue_h
#define EventQueue_h

#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
#include <wtf/PassOwnPtr.h>

namespace WebCore {

class Event;

class EventQueue {
public:
    virtual ~EventQueue() { }
    virtual bool enqueueEvent(PassRefPtr<Event>) = 0;
    virtual bool cancelEvent(Event*) = 0;
    // The accumulated and all the future events will be discarded, no events will be dispatched anymore.
    virtual void close() = 0;
};

}

#endif // EventQueue_h


text:
<?php
/*
 * This work is hereby released into the Public Domain.
 * To view a copy of the public domain dedication,
 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
 *
 */

/**
 * Create your gradients
 *
 * @package Artichow
 */
abstract class awGradient {

	/**
	 * From color
	 *
	 * @var Color
	 */
	public $from;

	/**
	 * To color
	 *
	 * @var Color
	 */
	public $to;

	/**
	 * Build the gradient
	 *
	 * @param awColor $from From color
	 * @param awColor $to To color
	 */
	public function __construct($from, $to) {

		$this->from = $from;
		$this->to = $to;

	}

	/**
	 * Free memory used by the colors of the gradient
	 */
	public function free() {

		$this->from->free();
		$this->to->free();

	}

	public function __destruct( ){

		$this->free();

	}

}

registerClass('Gradient', TRUE);

/**
 * Create a linear gradient
 *
 * @package Artichow
 */
class awLinearGradient extends awGradient {

	/**
	 * Gradient angle
	 *
	 * @var int
	 */
	public $angle;

	/**
	 * Build the linear gradient
	 *
	 * @param awColor $from From color
	 * @param awColor $to To color
	 * @param int $angle Gradient angle
	 */
	public function __construct($from, $to, $angle) {

		parent::__construct(
			$from, $to
		);

		$this->angle = $angle;

	}

}

registerClass('LinearGradient');

/**
 * Create a bilinear gradient
 *
 * @package Artichow
 */
class awBilinearGradient extends awLinearGradient {

	/**
	 * Gradient center
	 *
	 * @var int Center between 0 and 1
	 */
	public $center;

	/**
	 * Build the bilinear gradient
	 *
	 * @param awColor $from From color
	 * @param awColor $to To color
	 * @param int $angle Gradient angle
	 * @param int $center Gradient center
	 */
	public function __construct($from, $to, $angle, $center = 0.5) {

		parent::__construct(
			$from, $to, $angle
		);

		$this->center = $center;

	}

}

registerClass('BilinearGradient');

/**
 * Create a radial gradient
 *
 * @package Artichow
 */
class awRadialGradient extends awGradient {

}

registerClass('RadialGradient');
?>


text:
package ua.com.fielden.platform.domaintree.centre.analyses.impl;

import java.util.Set;

import ua.com.fielden.platform.domaintree.centre.analyses.ILifecycleDomainTreeRepresentation;
import ua.com.fielden.platform.entity.annotation.Calculated;
import ua.com.fielden.platform.entity.annotation.Monitoring;
import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.equery.lifecycle.LifecycleModel.GroupingPeriods;
import ua.com.fielden.platform.reflection.AnnotationReflector;
import ua.com.fielden.platform.reflection.PropertyTypeDeterminator;
import ua.com.fielden.platform.reflection.TitlesDescsGetter;
import ua.com.fielden.platform.utils.EntityUtils;
import ua.com.fielden.platform.utils.Pair;

/**
 * A domain tree representation for lifecycle analyses.
 *
 * @author TG Team
 *
 */
public class LifecycleDomainTreeRepresentation extends AbstractAnalysisDomainTreeRepresentation implements ILifecycleDomainTreeRepresentation {
    public static final String CATEGORY_PROPERTY_MARKER = "\"This is a marker expression, that indicates that this is a 'category' property to be used in lifecycle analyses.\"";

    /**
     * A representation constructor for the first time instantiation.
     *
     * @param entityFactory
     * @param rootTypes
     */
    public LifecycleDomainTreeRepresentation(final EntityFactory entityFactory, final Set<Class<?>> rootTypes) {
        this(entityFactory, rootTypes, createSet(), new LifecycleAddToDistributionTickRepresentation(), new LifecycleAddToCategoriesTickRepresentation());
    }

    /**
     * A representation constructor. Initialises also children references on itself.
     */
    protected LifecycleDomainTreeRepresentation(final EntityFactory entityFactory, final Set<Class<?>> rootTypes, final Set<Pair<Class<?>, String>> excludedProperties, final LifecycleAddToDistributionTickRepresentation firstTick, final LifecycleAddToCategoriesTickRepresentation secondTick) {
        super(entityFactory, rootTypes, excludedProperties, firstTick, secondTick);
    }

    @Override
    public ILifecycleAddToDistributionTickRepresentation getFirstTick() {
        return (ILifecycleAddToDistributionTickRepresentation) super.getFirstTick();
    }

    @Override
    public ILifecycleAddToCategoriesTickRepresentation getSecondTick() {
        return (ILifecycleAddToCategoriesTickRepresentation) super.getSecondTick();
    }

    public static class LifecycleAddToDistributionTickRepresentation extends AbstractAnalysisAddToDistributionTickRepresentation implements ILifecycleAddToDistributionTickRepresentation {
        /**
         * Used for serialisation and for normal initialisation. IMPORTANT : To use this tick it should be passed into representation constructor, which should initialise "dtr"
         * field.
         */
        public LifecycleAddToDistributionTickRepresentation() {
        }

        @Override
        public boolean isDisabledImmutablyLightweight(final Class<?> root, final String property) {
            final boolean isEntityItself = "".equals(property); // empty property means "entity itself"
            if (isEntityItself) { // "entities itself" should be enabled for lifecycle distribution
                return false;
            }
            return super.isDisabledImmutablyLightweight(root, property);
        }
    }

    public static class LifecycleAddToCategoriesTickRepresentation extends AbstractAnalysisAddToAggregationTickRepresentation implements ILifecycleAddToCategoriesTickRepresentation {
        /**
         * Used for serialisation and for normal initialisation. IMPORTANT : To use this tick it should be passed into representation constructor, which should initialise "dtr"
         * field.
         */
        public LifecycleAddToCategoriesTickRepresentation() {
        }

        @Override
        public LifecycleDomainTreeRepresentation getDtr() {
            return (LifecycleDomainTreeRepresentation) super.getDtr();
        }

        /**
         * A contract for reverse "enabling" of the properties. For e.g. in base analyses second tick we should enable only AGGREGATED_EXPRESSION properties. But here the following
         * properties should be enabled:
         *

         * 1) Lifecycle properties (with @Monitoring)

         * 2) "category" properties (they will appear after appropriate Lifecycle property will be chosen)
         *
         * @param root
         * @param property
         * @return
         */
        @Override
        protected boolean isEnabledImmutably(final Class<?> root, final String property) {
            // inject an enhanced type into method implementation
            final Class<?> managedType = managedType(root);
            final boolean isEntityItself = "".equals(property); // empty property means "entity itself"

            final Pair<Class<?>, String> transformed = PropertyTypeDeterminator.transform(managedType /* root */, property);
            final Class<?> penultType = transformed.getKey();
            final String lastPropertyName = transformed.getValue();

            return !isEntityItself && AnnotationReflector.isPropertyAnnotationPresent(Monitoring.class, penultType, lastPropertyName) || // enable "lifecycle" properties (with @Monitoring)
                    !isEntityItself && isCategoryProperty(managedType, property); // enable "category" properties
        }

        /**
         * Indicates whether the property represents so called "category" property.
         *
         * @param managedType
         * @param property
         * @return
         */
        protected static boolean isCategoryProperty(final Class<?> managedType, final String property) {
            final boolean isEntityItself = "".equals(property); // empty property means "entity itself"
            final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, property);
            final Calculated calculatedAnnotation = isEntityItself ? null : AnnotationReflector.getPropertyAnnotation(Calculated.class, managedType, property);
            final String expr = calculatedAnnotation != null ? calculatedAnnotation.value() : null;
            return expr != null && EntityUtils.isString(propertyType) && //
                    expr.equals(CATEGORY_PROPERTY_MARKER);
        }

        /**
         * Indicates whether the property represents so called "date period" marker.
         *
         * @param property
         * @return
         */
        public static boolean isDatePeriodProperty(final Class<?> managedType, final String property) {
            final boolean isEntityItself = "".equals(property); // empty property means "entity itself"
            if (isEntityItself) {
                return false;
            }
            for (final GroupingPeriods period : GroupingPeriods.values()) {
                final String title = TitlesDescsGetter.getTitleAndDesc(property, managedType).getKey();
                if (period.getTitle().equals(title)) {
                    return true;
                }
            }
            return false;
        }
    }

    /**
     * Provides a meta-state for Date Period distribution properties.
     */
    public void provideMetaStateForLifecycleAnalysesDatePeriodProperties() {
    }

}


text:
namespace cc {
class CompositorFrame;
class SyntheticBeginFrameSource;
}

namespace ui {

// An OutputSurface implementation that directly draws and
// swaps to an actual GL surface.
class DirectOutputSurface : public cc::OutputSurface,
                            public SurfacesContextProviderDelegate {
 public:
  explicit DirectOutputSurface(
      scoped_refptr<SurfacesContextProvider> context_provider,
      cc::SyntheticBeginFrameSource* synthetic_begin_frame_source);
  ~DirectOutputSurface() override;

  // cc::OutputSurface implementation
  void BindToClient(cc::OutputSurfaceClient* client) override;
  void EnsureBackbuffer() override;
  void DiscardBackbuffer() override;
  void BindFramebuffer() override;
  void Reshape(const gfx::Size& size,
               float device_scale_factor,
               const gfx::ColorSpace& color_space,
               bool has_alpha) override;
  void SwapBuffers(cc::OutputSurfaceFrame frame) override;
  uint32_t GetFramebufferCopyTextureFormat() override;
  cc::OverlayCandidateValidator* GetOverlayCandidateValidator() const override;
  bool IsDisplayedAsOverlayPlane() const override;
  unsigned GetOverlayTextureId() const override;
  bool SurfaceIsSuspendForRecycle() const override;
  bool HasExternalStencilTest() const override;
  void ApplyExternalStencil() override;

  // SurfacesContextProviderDelegate implementation
  void OnVSyncParametersUpdated(const base::TimeTicks& timebase,
                                const base::TimeDelta& interval) override;

 private:
  void OnSwapBuffersComplete();

  cc::OutputSurfaceClient* client_ = nullptr;
  cc::SyntheticBeginFrameSource* const synthetic_begin_frame_source_;
  base::WeakPtrFactory<DirectOutputSurface> weak_ptr_factory_;
};

}  // namespace ui

#endif  // SERVICES_UI_SURFACES_DIRECT_OUTPUT_SURFACE_H_


text:
if(!window.GGRC) {
  window.GGRC = {};
}
if(!GGRC.config) {
  GGRC.config = {};
}
GGRC.config.GDRIVE_ROOT_FOLDER = '0ByeYJ052BwIZb2hoTWtjcDV2dTg';
GGRC.config.GDRIVE_SCRIPT_ID = 'AKfycbxb-W3rUBTKFF6Ua_eJ5PH9RAvGVL7W3aDqtmnbnUc7PD0FY3zo';

describe("GDrive integration models", function() {

  beforeEach(function() {
    spyOn(GGRC.Controllers.GAPI, "authorize").and.callFake(function() {
      return $.when();
    });
  });

  describe("CMS.Models.GDriveFolder", function() {
       //randomly fails with:

       //Chrome 39.0.2171 (Linux) GDrive integration models CMS.Models.GDriveFolder ::findAll calls the root when parentfolderid is not supplied FAILED
       // Error: spyOn could not find an object to spy upon for request()
       //       at Object.<anonymous> (/vagrant/src/ggrc_gdrive_integration/assets/js_specs/models/gdrive_models_spec.js:24:19)
       //       Chrome 39.0.2171 (Linux): Executed 129 of 146 (1 FAILED) (0.228 secs / 0.182 secs)

    /*
    describe("::findAll", function() {

      it("calls the root when parentfolderid is not supplied", function() {
        var returned;
        spyOn(gapi.client, 'request').and.returnValue(new $.Deferred().resolve());
        CMS.Models.GDriveFolder.findAll();
        expect(gapi.client.request.calls.mostRecent().args[0].path).toMatch(/\?q=.*'root'%20in%20parents/);
      });
    });
    */

    describe("::findChildFolders", function() {
      beforeEach(function() {
        spyOn(CMS.Models.GDriveFolder, "findAll");
      });
      it("performs a findAll with a supplied string as parentfolderid", function() {
        CMS.Models.GDriveFolder.findChildFolders("foo");
        expect(CMS.Models.GDriveFolder.findAll).toHaveBeenCalledWith({ parents : "foo" });
      });
      it("performs a findAll with a supplied object's id as parentfolderid", function() {
        CMS.Models.GDriveFolder.findChildFolders({id : "bar"});
        expect(CMS.Models.GDriveFolder.findAll).toHaveBeenCalledWith({ parents : "bar" });
      });
    });
  });

});


text:
<?php

namespace Develop\Business\Application\ProductWishlist\Tests;

use Develop\Business\Application\ProductWishlist\EchoNotifier;
use Develop\Business\Wishlist\Item;
use Develop\Business\Wishlist\Wishlist;

class EchoNotifierTest extends \PHPUnit_Framework_TestCase
{
    public function testEchoSomeText()
    {
        $this->expectOutputString('Email: email@test.com, Message: T-Shirt' . PHP_EOL);
        $notifier = new EchoNotifier();
        $notifier->send(new Wishlist('email@test.com', new Item(1, 'T-Shirt')));
    }
}


text:
layout: post
title: "Lessons that I learned"
date: 2014-02-27 11:20:00
categories: blog
description: About posting a post everyday
---

Review about this year so far:

### A post per day is hard!

It's very hard, but in the other hand, seems like my ideas and creativity are flowing better.

### Jekyll seems not to be ideal for the item above

At least, using the Yeoman Jekyll Generator. I really love this generator, but there's some stuff that make me sad about it. e.g. the deploy process that "regenerate" all your pages. I'm still not sure, but I think sooner or later I'll really migrate to Ghost.

Anyway, this year has been a great year!


text:
namespace Xilium.CefGlue
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using Xilium.CefGlue.Interop;

    /// <summary>
    /// Implement this interface to handle events related to browser requests. The
    /// methods of this class will be called on the thread indicated.
    /// </summary>
    public abstract unsafe partial class CefRequestHandler
    {
        private int on_before_browse(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request, int is_redirect)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_frame = CefFrame.FromNative(frame);
            var m_request = CefRequest.FromNative(request);
            var m_isRedirect = is_redirect != 0;

            var result = OnBeforeBrowse(m_browser, m_frame, m_request, m_isRedirect);

            return result ? 1 : 0;
        }

        /// <summary>
        /// Called on the UI thread before browser navigation. Return true to cancel
        /// the navigation or false to allow the navigation to proceed. The |request|
        /// object cannot be modified in this callback.
        /// CefLoadHandler::OnLoadingStateChange will be called twice in all cases.
        /// If the navigation is allowed CefLoadHandler::OnLoadStart and
        /// CefLoadHandler::OnLoadEnd will be called. If the navigation is canceled
        /// CefLoadHandler::OnLoadError will be called with an |errorCode| value of
        /// ERR_ABORTED.
        /// </summary>
        protected virtual bool OnBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest request, bool isRedirect)
        {
            return false;
        }

        private int on_open_urlfrom_tab(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_string_t* target_url, CefWindowOpenDisposition target_disposition, int user_gesture)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_frame = CefFrame.FromNative(frame);
            var m_targetUrl = cef_string_t.ToString(target_url);
            var m_userGesture = user_gesture != 0;

            var m_result = OnOpenUrlFromTab(m_browser, m_frame, m_targetUrl, target_disposition, m_userGesture);

            return m_result ? 1 : 0;
        }

        /// <summary>
        /// Called on the UI thread before OnBeforeBrowse in certain limited cases
        /// where navigating a new or different browser might be desirable. This
        /// includes user-initiated navigation that might open in a special way (e.g.
        /// links clicked via middle-click or ctrl + left-click) and certain types of
        /// cross-origin navigation initiated from the renderer process (e.g.
        /// navigating the top-level frame to/from a file URL). The |browser| and
        /// |frame| values represent the source of the navigation. The
        /// |target_disposition| value indicates where the user intended to navigate
        /// the browser based on standard Chromium behaviors (e.g. current tab,
        /// new tab, etc). The |user_gesture| value will be true if the browser
        /// navigated via explicit user gesture (e.g. clicking a link) or false if it
        /// navigated automatically (e.g. via the DomContentLoaded event). Return true
        /// to cancel the navigation or false to allow the navigation to proceed in the
        /// source browser's top-level frame.
        /// </summary>
        protected virtual bool OnOpenUrlFromTab(CefBrowser browser, CefFrame frame, string targetUrl, CefWindowOpenDisposition targetDisposition, bool userGesture)
        {
            return false;
        }

        private CefReturnValue on_before_resource_load(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request, cef_request_callback_t* callback)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_frame = CefFrame.FromNative(frame);
            var m_request = CefRequest.FromNative(request);
            var m_callback = CefRequestCallback.FromNative(callback);

            var result = OnBeforeResourceLoad(m_browser, m_frame, m_request, m_callback);

            if (result != CefReturnValue.ContinueAsync)
            {
                m_browser.Dispose();
                m_frame.Dispose();
                m_request.Dispose();
                m_callback.Dispose();
            }

            return result;
        }

        /// <summary>
        /// Called on the IO thread before a resource request is loaded. The |request|
        /// object may be modified. Return RV_CONTINUE to continue the request
        /// immediately. Return RV_CONTINUE_ASYNC and call CefRequestCallback::
        /// Continue() at a later time to continue or cancel the request
        /// asynchronously. Return RV_CANCEL to cancel the request immediately.
        /// </summary>
        protected virtual CefReturnValue OnBeforeResourceLoad(CefBrowser browser, CefFrame frame, CefRequest request, CefRequestCallback callback)
        {
            return CefReturnValue.Continue;
        }

        private cef_resource_handler_t* get_resource_handler(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_frame = CefFrame.FromNative(frame);
            var m_request = CefRequest.FromNative(request);

            var handler = GetResourceHandler(m_browser, m_frame, m_request);

            m_request.Dispose();

            return handler != null ? handler.ToNative() : null;
        }

        /// <summary>
        /// Called on the IO thread before a resource is loaded. To allow the resource
        /// to load normally return NULL. To specify a handler for the resource return
        /// a CefResourceHandler object. The |request| object should not be modified in
        /// this callback.
        /// </summary>
        protected virtual CefResourceHandler GetResourceHandler(CefBrowser browser, CefFrame frame, CefRequest request)
        {
            return null;
        }

        private void on_resource_redirect(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request, cef_response_t* response, cef_string_t* new_url)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_frame = CefFrame.FromNative(frame);
            var m_request = CefRequest.FromNative(request);
            var m_response = CefResponse.FromNative(response);
            var m_newUrl = cef_string_t.ToString(new_url);

            var o_newUrl = m_newUrl;
            OnResourceRedirect(m_browser, m_frame, m_request, m_response, ref m_newUrl);

            if ((object)m_newUrl != (object)o_newUrl)
            {
                cef_string_t.Copy(m_newUrl, new_url);
            }
        }

        /// <summary>
        /// Called on the IO thread when a resource load is redirected. The |request|
        /// parameter will contain the old URL and other request-related information.
        /// The |response| parameter will contain the response that resulted in the
        /// redirect. The |new_url| parameter will contain the new URL and can be
        /// changed if desired. The |request| object cannot be modified in this
        /// callback.
        /// </summary>
        protected virtual void OnResourceRedirect(CefBrowser browser, CefFrame frame, CefRequest request, CefResponse response, ref string newUrl)
        {
        }

        private int on_resource_response(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request, cef_response_t* response)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_frame = CefFrame.FromNative(frame);
            var m_request = CefRequest.FromNative(request);
            var m_response = CefResponse.FromNative(response);

            var m_result = OnResourceResponse(m_browser, m_frame, m_request, m_response);

            return m_result ? 1 : 0;
        }

        /// <summary>
        /// Called on the IO thread when a resource response is received. To allow the
        /// resource to load normally return false. To redirect or retry the resource
        /// modify |request| (url, headers or post body) and return true. The
        /// |response| object cannot be modified in this callback.
        /// </summary>
        protected virtual bool OnResourceResponse(CefBrowser browser, CefFrame frame, CefRequest request, CefResponse response)
        {
            return false;
        }

        private cef_response_filter_t* get_resource_response_filter(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request, cef_response_t* response)
        {
            CheckSelf(self);

            var mBrowser = CefBrowser.FromNative(browser);
            var mFrame = CefFrame.FromNative(frame);
            var mRequest = CefRequest.FromNative(request);
            var mResponse = CefResponse.FromNative(response);

            var result = GetResourceResponseFilter(mBrowser, mFrame, mRequest, mResponse);

            if (result != null)
            {
                return result.ToNative();
            }

            return null;
        }

        /// <summary>
        /// Called on the IO thread to optionally filter resource response content.
        /// |request| and |response| represent the request and response respectively
        /// and cannot be modified in this callback.
        /// </summary>
        protected virtual CefResponseFilter GetResourceResponseFilter(CefBrowser browser, CefFrame frame, CefRequest request, CefResponse response)
        {
            return null;
        }

        private void on_resource_load_complete(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request, cef_response_t* response, CefUrlRequestStatus status, long received_content_length)
        {
            CheckSelf(self);

            var mBrowser = CefBrowser.FromNative(browser);
            var mFrame = CefFrame.FromNative(frame);
            var mRequest = CefRequest.FromNative(request);
            var mResponse = CefResponse.FromNative(response);

            OnResourceLoadComplete(mBrowser, mFrame, mRequest, mResponse, status, received_content_length);
        }

        /// <summary>
        /// Called on the IO thread when a resource load has completed. |request| and
        /// |response| represent the request and response respectively and cannot be
        /// modified in this callback. |status| indicates the load completion status.
        /// |received_content_length| is the number of response bytes actually read.
        /// </summary>
        protected virtual void OnResourceLoadComplete(CefBrowser browser, CefFrame frame, CefRequest request, CefResponse response, CefUrlRequestStatus status, long receivedContentLength)
        {
        }

        private int get_auth_credentials(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, int isProxy, cef_string_t* host, int port, cef_string_t* realm, cef_string_t* scheme, cef_auth_callback_t* callback)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_frame = CefFrame.FromNative(frame);
            var m_host = cef_string_t.ToString(host);
            var m_realm = cef_string_t.ToString(realm);
            var m_scheme = cef_string_t.ToString(scheme);
            var m_callback = CefAuthCallback.FromNative(callback);

            var result = GetAuthCredentials(m_browser, m_frame, isProxy != 0, m_host, port, m_realm, m_scheme, m_callback);

            return result ? 1 : 0;
        }

        /// <summary>
        /// Called on the IO thread when the browser needs credentials from the user.
        /// |isProxy| indicates whether the host is a proxy server. |host| contains the
        /// hostname and |port| contains the port number. |realm| is the realm of the
        /// challenge and may be empty. |scheme| is the authentication scheme used,
        /// such as "basic" or "digest", and will be empty if the source of the request
        /// is an FTP server. Return true to continue the request and call
        /// CefAuthCallback::Continue() either in this method or at a later time when
        /// the authentication information is available. Return false to cancel the
        /// request immediately.
        /// </summary>
        protected virtual bool GetAuthCredentials(CefBrowser browser, CefFrame frame, bool isProxy, string host, int port, string realm, string scheme, CefAuthCallback callback)
        {
            return false;
        }

        private int on_quota_request(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* origin_url, long new_size, cef_request_callback_t* callback)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_origin_url = cef_string_t.ToString(origin_url);
            var m_callback = CefRequestCallback.FromNative(callback);

            var result = OnQuotaRequest(m_browser, m_origin_url, new_size, m_callback);

            return result ? 1 : 0;
        }

        /// <summary>
        /// Called on the IO thread when JavaScript requests a specific storage quota
        /// size via the webkitStorageInfo.requestQuota function. |origin_url| is the
        /// origin of the page making the request. |new_size| is the requested quota
        /// size in bytes. Return true to continue the request and call
        /// CefRequestCallback::Continue() either in this method or at a later time to
        /// grant or deny the request. Return false to cancel the request immediately.
        /// </summary>
        protected virtual bool OnQuotaRequest(CefBrowser browser, string originUrl, long newSize, CefRequestCallback callback)
        {
            callback.Continue(true);
            return true;
        }

        private void on_protocol_execution(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* url, int* allow_os_execution)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_url = cef_string_t.ToString(url);
            bool m_allow_os_execution;

            OnProtocolExecution(m_browser, m_url, out m_allow_os_execution);

            *allow_os_execution = m_allow_os_execution ? 1 : 0;
        }

        /// <summary>
        /// Called on the UI thread to handle requests for URLs with an unknown
        /// protocol component. Set |allow_os_execution| to true to attempt execution
        /// via the registered OS protocol handler, if any.
        /// SECURITY WARNING: YOU SHOULD USE THIS METHOD TO ENFORCE RESTRICTIONS BASED
        /// ON SCHEME, HOST OR OTHER URL ANALYSIS BEFORE ALLOWING OS EXECUTION.
        /// </summary>
        protected virtual void OnProtocolExecution(CefBrowser browser, string url, out bool allowOSExecution)
        {
            allowOSExecution = true;
        }

        private int on_certificate_error(cef_request_handler_t* self, cef_browser_t* browser, CefErrorCode cert_error, cef_string_t* request_url, cef_sslinfo_t* ssl_info, cef_request_callback_t* callback)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_request_url = cef_string_t.ToString(request_url);
            var m_ssl_info = CefSslInfo.FromNative(ssl_info);
            var m_callback = CefRequestCallback.FromNativeOrNull(callback);

            var result = OnCertificateError(m_browser, cert_error, m_request_url, m_ssl_info, m_callback);

            return result ? 1 : 0;
        }

        /// <summary>
        /// Called on the UI thread to handle requests for URLs with an invalid
        /// SSL certificate. Return true and call CefRequestCallback::Continue() either
        /// in this method or at a later time to continue or cancel the request. Return
        /// false to cancel the request immediately. If
        /// CefSettings.ignore_certificate_errors is set all invalid certificates will
        /// be accepted without calling this method.
        /// </summary>
        protected virtual bool OnCertificateError(CefBrowser browser, CefErrorCode certError, string requestUrl, CefSslInfo sslInfo, CefRequestCallback callback)
        {
            return false;
        }

        private int on_select_client_certificate(cef_request_handler_t* self, cef_browser_t* browser, int isProxy, cef_string_t* host, int port, UIntPtr certificatesCount, cef_x509certificate_t** certificates, cef_select_client_certificate_callback_t* callback)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_isProxy = isProxy != 0;
            var m_host = cef_string_t.ToString(host);
            var m_certCount = checked((int)certificatesCount);
            var m_certificates = new CefX509Certificate[m_certCount];
            for (var i = 0; i < m_certCount; i++)
            {
                m_certificates[i] = CefX509Certificate.FromNative(certificates[i]);
            }
            var m_callback = CefSelectClientCertificateCallback.FromNative(callback);

            var result = OnSelectClientCertificate(m_browser, m_isProxy, m_host, port, m_certificates, m_callback);
            if (result)
            {
                return 1;
            }
            else
            {
                m_callback.Dispose();
                return 0;
            }
        }

        /// <summary>
        /// Called on the UI thread when a client certificate is being requested for
        /// authentication. Return false to use the default behavior and automatically
        /// select the first certificate available. Return true and call
        /// CefSelectClientCertificateCallback::Select either in this method or at a
        /// later time to select a certificate. Do not call Select or call it with NULL
        /// to continue without using any certificate. |isProxy| indicates whether the
        /// host is an HTTPS proxy or the origin server. |host| and |port| contains the
        /// hostname and port of the SSL server. |certificates| is the list of
        /// certificates to choose from; this list has already been pruned by Chromium
        /// so that it only contains certificates from issuers that the server trusts.
        /// </summary>
        protected virtual bool OnSelectClientCertificate(CefBrowser browser, bool isProxy, string host, int port, CefX509Certificate[] certificates, CefSelectClientCertificateCallback callback)
        {
            return false;
        }

        private void on_plugin_crashed(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* plugin_path)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            var m_plugin_path = cef_string_t.ToString(plugin_path);

            OnPluginCrashed(m_browser, m_plugin_path);
        }

        /// <summary>
        /// Called on the browser process UI thread when a plugin has crashed.
        /// |plugin_path| is the path of the plugin that crashed.
        /// </summary>
        protected virtual void OnPluginCrashed(CefBrowser browser, string pluginPath)
        {
        }

        private void on_render_view_ready(cef_request_handler_t* self, cef_browser_t* browser)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);
            OnRenderViewReady(m_browser);
        }

        /// <summary>
        /// Called on the browser process UI thread when the render view associated
        /// with |browser| is ready to receive/handle IPC messages in the render
        /// process.
        /// </summary>
        protected virtual void OnRenderViewReady(CefBrowser browser)
        {
        }

        private void on_render_process_terminated(cef_request_handler_t* self, cef_browser_t* browser, CefTerminationStatus status)
        {
            CheckSelf(self);

            var m_browser = CefBrowser.FromNative(browser);

            OnRenderProcessTerminated(m_browser, status);
        }

        /// <summary>
        /// Called on the browser process UI thread when the render process
        /// terminates unexpectedly. |status| indicates how the process
        /// terminated.
        /// </summary>
        protected virtual void OnRenderProcessTerminated(CefBrowser browser, CefTerminationStatus status)
        {
        }
    }
}


text:
/*
 *  test_attribute_convert.js
 *
 *  David Janes
 *  IOTDB
 *  2013-12-28
 *
 *  Test attribute conversions
 */

"use strict";

var assert = require("assert")
var iotdb = require("../iotdb")
var attribute = require("./instrument/attribute")
var _ = require("../helpers")
var constants = require("../constants")

/* --- tests --- */
describe('test_attribute_convert:', function(){
  describe('boolean->', function(){
      describe('->boolean', function(){
        it('return true or false as appropriate', function(){
            var a = new attribute.Attribute();
            /* simple converion */
            assert.strictEqual(false, a._convert(false, [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(true, [ constants.iot_boolean ]))
        })
      })
      describe('->integer', function(){
        it('return 0 or 1 as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(0, a._convert(false, [ constants.iot_integer ]))
            assert.strictEqual(1, a._convert(true, [ constants.iot_integer ]))
        })
        it('return 10 or 99 as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(10, a._convert_boolean(false, [ constants.iot_integer ], 10, 99))
            assert.strictEqual(99, a._convert_boolean(true, [ constants.iot_integer ], 10, 99))
        })
      })
      describe('->number', function(){
        it('return 0 or 1 as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(0, a._convert(false, [ constants.iot_integer ]))
            assert.strictEqual(1, a._convert(true, [ constants.iot_integer ]))
        })
        it('return -99.1 or 99.9 as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(-99.1, a._convert_boolean(false, [ constants.iot_integer ], -99.1, 99.9))
            assert.strictEqual(99.9, a._convert_boolean(true, [ constants.iot_integer ], -99.1, 99.9))
        })
      })
      describe('->string', function(){
        it('return true or false as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual("0", a._convert(false, [ constants.iot_string ]))
            assert.strictEqual("1", a._convert(true, [ constants.iot_string ]))
        })
      })
    })
  describe('integer->', function(){
      describe('->boolean', function(){
        it('return true or false as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(false, a._convert(0, [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(1, [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(-1, [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(-99, [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(99, [ constants.iot_boolean ]))
        })
      })
      describe('->integer', function(){
        it('return same number', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(0, a._convert(0, [ constants.iot_integer ]))
            assert.strictEqual(1, a._convert(1, [ constants.iot_integer ]))
            assert.strictEqual(-1, a._convert(-1, [ constants.iot_integer ]))
            assert.strictEqual(-99, a._convert(-99, [ constants.iot_integer ]))
            assert.strictEqual(99, a._convert(99, [ constants.iot_integer ]))
        })
      })
      describe('->number', function(){
        it('return same number', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(0, a._convert(0, [ constants.iot_number ]))
            assert.strictEqual(1, a._convert(1, [ constants.iot_number ]))
            assert.strictEqual(-1, a._convert(-1, [ constants.iot_number ]))
            assert.strictEqual(-99, a._convert(-99, [ constants.iot_number ]))
            assert.strictEqual(99, a._convert(99, [ constants.iot_number ]))
        })
      })
      describe('->string', function(){
        it('return true or false as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual("0", a._convert(0, [ constants.iot_string ]))
            assert.strictEqual("1", a._convert(1, [ constants.iot_string ]))
            assert.strictEqual("-1", a._convert(-1, [ constants.iot_string ]))
            assert.strictEqual("-99", a._convert(-99, [ constants.iot_string ]))
            assert.strictEqual("99", a._convert(99, [ constants.iot_string ]))
        })
      })
    })
  describe('number->', function(){
      describe('->boolean', function(){
        it('return true or false as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(false, a._convert(0.0, [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(1.0, [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(-1.0, [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(-99.0, [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(99.0, [ constants.iot_boolean ]))

            assert.strictEqual(true, a._convert(".9", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(".5", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert(".4999", [ constants.iot_boolean ]))

            assert.strictEqual(true, a._convert("100.49", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert("100.01", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert("99.9", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert("99.5", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert("99.499", [ constants.iot_boolean ]))
        })
      })
      describe('->integer', function(){
        it('return same number', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(0, a._convert(0.0, [ constants.iot_integer ]))
            assert.strictEqual(1, a._convert(1.0, [ constants.iot_integer ]))
            assert.strictEqual(-1, a._convert(-1.0, [ constants.iot_integer ]))
            assert.strictEqual(-99, a._convert(-99.0, [ constants.iot_integer ]))
            assert.strictEqual(99, a._convert(99.0, [ constants.iot_integer ]))

            assert.strictEqual(1, a._convert(".9", [ constants.iot_integer ]))
            assert.strictEqual(1, a._convert(".5", [ constants.iot_integer ]))
            assert.strictEqual(0, a._convert(".4999", [ constants.iot_integer ]))

            assert.strictEqual(100, a._convert("100.49", [ constants.iot_integer ]))
            assert.strictEqual(100, a._convert("100.01", [ constants.iot_integer ]))
            assert.strictEqual(100, a._convert("99.9", [ constants.iot_integer ]))
            assert.strictEqual(100, a._convert("99.5", [ constants.iot_integer ]))
            assert.strictEqual(99, a._convert("99.499", [ constants.iot_integer ]))
        })
      })
      describe('->number', function(){
        it('return same number', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(0.0, a._convert(0.0, [ constants.iot_number ]))
            assert.strictEqual(1.0, a._convert(1.0, [ constants.iot_number ]))
            assert.strictEqual(-1.0, a._convert(-1.0, [ constants.iot_number ]))
            assert.strictEqual(-99.0, a._convert(-99.0, [ constants.iot_number ]))
            assert.strictEqual(99.0, a._convert(99.0, [ constants.iot_number ]))

            assert.strictEqual(.9, a._convert(".9", [ constants.iot_number ]))
            assert.strictEqual(.5, a._convert(".5", [ constants.iot_number ]))
            assert.strictEqual(.4999, a._convert(".4999", [ constants.iot_number ]))

            assert.strictEqual(100.49, a._convert("100.49", [ constants.iot_number ]))
            assert.strictEqual(100.01, a._convert("100.01", [ constants.iot_number ]))
            assert.strictEqual(99.9, a._convert("99.9", [ constants.iot_number ]))
            assert.strictEqual(99.5, a._convert("99.5", [ constants.iot_number ]))
            assert.strictEqual(99.499, a._convert("99.499", [ constants.iot_number ]))
        })
      })
      describe('->string', function(){
        it('return true or false as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual("0", a._convert(0.0, [ constants.iot_string ]))
            assert.strictEqual("1", a._convert(1.0, [ constants.iot_string ]))
            assert.strictEqual("-1", a._convert(-1.0, [ constants.iot_string ]))
            assert.strictEqual("-99", a._convert(-99.0, [ constants.iot_string ]))
            assert.strictEqual("99", a._convert(99.0, [ constants.iot_string ]))

            assert.strictEqual(".9", a._convert(".9", [ constants.iot_string ]))
            assert.strictEqual(".5", a._convert(".5", [ constants.iot_string ]))
            assert.strictEqual(".4999", a._convert(".4999", [ constants.iot_string ]))

            assert.strictEqual("100.49", a._convert("100.49", [ constants.iot_string ]))
            assert.strictEqual("100.01", a._convert("100.01", [ constants.iot_string ]))
            assert.strictEqual("99.9", a._convert("99.9", [ constants.iot_string ]))
            assert.strictEqual("99.5", a._convert("99.5", [ constants.iot_string ]))
            assert.strictEqual("99.499", a._convert("99.499", [ constants.iot_string ]))
        })
      })
    })
  describe('string->', function(){
      describe('->boolean', function(){
        it('return true or false as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(false, a._convert("", [ constants.iot_boolean ]))
            assert.strictEqual(false, a._convert("off", [ constants.iot_boolean ]))
            assert.strictEqual(false, a._convert("false", [ constants.iot_boolean ]))
            assert.strictEqual(false, a._convert("no", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert("yes", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert("on", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert("true", [ constants.iot_boolean ]))
            assert.strictEqual(true, a._convert("any string really", [ constants.iot_boolean ]))
        })
      })
      describe('->integer', function(){
        it('return same number or rounded as needed', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(0, a._convert("0", [ constants.iot_integer ]))
            assert.strictEqual(1, a._convert("1", [ constants.iot_integer ]))
            assert.strictEqual(-1, a._convert("-1", [ constants.iot_integer ]))
            assert.strictEqual(-99, a._convert("-99", [ constants.iot_integer ]))
            assert.strictEqual(99, a._convert("99", [ constants.iot_integer ]))

            assert.strictEqual(1, a._convert(".9", [ constants.iot_integer ]))
            assert.strictEqual(1, a._convert(".5", [ constants.iot_integer ]))
            assert.strictEqual(0, a._convert(".4999", [ constants.iot_integer ]))

            assert.strictEqual(100, a._convert("100.49", [ constants.iot_integer ]))
            assert.strictEqual(100, a._convert("100.01", [ constants.iot_integer ]))
            assert.strictEqual(100, a._convert("99.9", [ constants.iot_integer ]))
            assert.strictEqual(100, a._convert("99.5", [ constants.iot_integer ]))
            assert.strictEqual(99, a._convert("99.499", [ constants.iot_integer ]))

            assert.ok(isNaN(a._convert("", [ constants.iot_integer ])))
            assert.ok(isNaN(a._convert("off", [ constants.iot_integer ])))
            assert.ok(isNaN(a._convert("false", [ constants.iot_integer ])))
            assert.ok(isNaN(a._convert("no", [ constants.iot_integer ])))
            assert.ok(isNaN(a._convert("yes", [ constants.iot_integer ])))
            assert.ok(isNaN(a._convert("on", [ constants.iot_integer ])))
            assert.ok(isNaN(a._convert("true", [ constants.iot_integer ])))
            assert.ok(isNaN(a._convert("any string really", [ constants.iot_integer ])))
        })
      })
      describe('->number', function(){
        it('return same number', function(){
            var a = new attribute.Attribute();
            assert.strictEqual(0, a._convert("0", [ constants.iot_number ]))
            assert.strictEqual(1, a._convert("1", [ constants.iot_number ]))
            assert.strictEqual(-1, a._convert("-1", [ constants.iot_number ]))
            assert.strictEqual(-99, a._convert("-99", [ constants.iot_number ]))
            assert.strictEqual(99, a._convert("99", [ constants.iot_number ]))

            assert.strictEqual(.9, a._convert(".9", [ constants.iot_number ]))
            assert.strictEqual(.5, a._convert(".5", [ constants.iot_number ]))
            assert.strictEqual(.4999, a._convert(".4999", [ constants.iot_number ]))

            assert.strictEqual(100.49, a._convert("100.49", [ constants.iot_number ]))
            assert.strictEqual(100.01, a._convert("100.01", [ constants.iot_number ]))
            assert.strictEqual(99.9, a._convert("99.9", [ constants.iot_number ]))
            assert.strictEqual(99.5, a._convert("99.5", [ constants.iot_number ]))
            assert.strictEqual(99.499, a._convert("99.499", [ constants.iot_number ]))

            assert.ok(isNaN(a._convert("", [ constants.iot_number ])))
            assert.ok(isNaN(a._convert("off", [ constants.iot_number ])))
            assert.ok(isNaN(a._convert("false", [ constants.iot_number ])))
            assert.ok(isNaN(a._convert("no", [ constants.iot_number ])))
            assert.ok(isNaN(a._convert("yes", [ constants.iot_number ])))
            assert.ok(isNaN(a._convert("on", [ constants.iot_number ])))
            assert.ok(isNaN(a._convert("true", [ constants.iot_number ])))
            assert.ok(isNaN(a._convert("any string really", [ constants.iot_number ])))
        })
      })
      describe('->string', function(){
        it('return true or false as appropriate', function(){
            var a = new attribute.Attribute();
            assert.strictEqual("0", a._convert("0", [ constants.iot_string ]))
            assert.strictEqual("1", a._convert("1", [ constants.iot_string ]))
            assert.strictEqual("-1", a._convert("-1", [ constants.iot_string ]))
            assert.strictEqual("-99", a._convert("-99", [ constants.iot_string ]))
            assert.strictEqual("99", a._convert("99", [ constants.iot_string ]))

            assert.strictEqual(".9", a._convert(".9", [ constants.iot_string ]))
            assert.strictEqual(".5", a._convert(".5", [ constants.iot_string ]))
            assert.strictEqual(".4999", a._convert(".4999", [ constants.iot_string ]))

            assert.strictEqual("100.49", a._convert("100.49", [ constants.iot_string ]))
            assert.strictEqual("100.01", a._convert("100.01", [ constants.iot_string ]))
            assert.strictEqual("99.9", a._convert("99.9", [ constants.iot_string ]))
            assert.strictEqual("99.5", a._convert("99.5", [ constants.iot_string ]))
            assert.strictEqual("99.499", a._convert("99.499", [ constants.iot_string ]))

            assert.strictEqual("", a._convert("", [ constants.iot_string ]))
            assert.strictEqual("off", a._convert("off", [ constants.iot_string ]))
            assert.strictEqual("false", a._convert("false", [ constants.iot_string ]))
            assert.strictEqual("no", a._convert("no", [ constants.iot_string ]))
            assert.strictEqual("yes", a._convert("yes", [ constants.iot_string ]))
            assert.strictEqual("on", a._convert("on", [ constants.iot_string ]))
            assert.strictEqual("true", a._convert("true", [ constants.iot_string ]))
            assert.strictEqual("any string really", a._convert("any string really", [ constants.iot_string ]))
        })
      })
    })
})


text:
/*
    This library 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 2 of the license, or (at your option) any later version.
*/
package org.gjt.jclasslib.structures.elementvalues;

import org.gjt.jclasslib.structures.*;

import java.io.*;

/**
 * Describes an  <tt>ElementValue</tt> attribute structure.
 *
 * @author Vitor Carreira
 * @version $Revision: 1.1 $ $Date: 2005/11/01 13:18:24 $
 */
public abstract class ElementValue extends AbstractStructure {

    public final static char BYTE_TAG = 'B';
    public final static char CHAR_TAG = 'C';
    public final static char DOUBLE_TAG = 'D';
    public final static char FLOAT_TAG = 'F';
    public final static char INT_TAG = 'I';
    public final static char LONG_TAG = 'J';
    public final static char SHORT_TAG = 'S';
    public final static char BOOL_TAG = 'Z';
    public final static char STRING_TAG = 's';
    public final static char ENUM_TAG = 'e';
    public final static char CLASS_TAG = 'c';
    public final static char ARRAY_TAG = '[';
    public final static char ANNOTATION_TAG = '@';

    public final static String BYTE_TAG_VERBOSE = "byte";
    public final static String CHAR_TAG_VERBOSE = "String";
    public final static String DOUBLE_TAG_VERBOSE = "double";
    public final static String FLOAT_TAG_VERBOSE = "float";
    public final static String INT_TAG_VERBOSE = "int";
    public final static String LONG_TAG_VERBOSE = "long";
    public final static String SHORT_TAG_VERBOSE = "short";
    public final static String BOOL_TAG_VERBOSE = "boolean";
    public final static String STRING_TAG_VERBOSE = "String";
    public final static String ENUM_TAG_VERBOSE = "Enum";
    public final static String CLASS_TAG_VERBOSE = "Class";
    public final static String ARRAY_TAG_VERBOSE = "Array";
    public final static String ANNOTATION_TAG_VERBOSE = "Annotation";

    protected static final int INITIAL_LENGTH = 1;
    private int tag;

    public ElementValue(int tag) {
        this.tag = tag;
    }

    /**
     * Factory for creating <tt>ElementValue</tt> structures.
     *
     * @param in        the <tt>DataInput</tt> from which to read the
     *                  <tt>ElementValue</tt> structure
     * @param classFile the parent class file of the structure to be created
     * @return the new <tt>ElementValue</tt> structure
     * @throws org.gjt.jclasslib.structures.InvalidByteCodeException
     *                             if the byte code is invalid
     * @throws IOException if an exception occurs with the <tt>DataInput</tt>
     */
    public static ElementValue create(DataInput in, ClassFile classFile)
            throws InvalidByteCodeException, IOException {

        int tagType = in.readUnsignedByte();

        ElementValue entry = null;
        switch (tagType) {
            case BOOL_TAG:
            case BYTE_TAG:
            case CHAR_TAG:
            case DOUBLE_TAG:
            case FLOAT_TAG:
            case SHORT_TAG:
            case INT_TAG:
            case LONG_TAG:
            case STRING_TAG:
                entry = new ConstElementValue(tagType);
                break;
            case ENUM_TAG:
                entry = new EnumElementValue();
                break;
            case CLASS_TAG:
                entry = new ClassElementValue();
                break;
            case ANNOTATION_TAG:
                entry = new AnnotationElementValue();
                break;
            case ARRAY_TAG:
                entry = new ArrayElementValue();
                break;
            default:
                throw new InvalidByteCodeException("Unknown tag " + (char)tagType);
        }
        entry.setClassFile(classFile);
        entry.read(in);

        return entry;
    }

    public void write(DataOutput out) throws InvalidByteCodeException, IOException {
        super.write(out);

        out.writeByte(tag);

        if (debug) debug("wrote ");
    }

    protected abstract int getSpecificLength();

    final public int getLength() {
        return INITIAL_LENGTH + getSpecificLength();
    }

    public abstract String getEntryName();

    protected String printAccessFlagsVerbose(int accessFlags) {
        if (accessFlags != 0)
            throw new RuntimeException("Access flags should be zero: " + Integer.toHexString(accessFlags));
        return "";
    }

    public int getTag() {
        return tag;
    }

    public static String getTagDescription(int tag) {
        switch (tag) {
            case BOOL_TAG:
                return BOOL_TAG_VERBOSE;
            case BYTE_TAG:
                return BYTE_TAG_VERBOSE;
            case CHAR_TAG:
                return CHAR_TAG_VERBOSE;
            case DOUBLE_TAG:
                return DOUBLE_TAG_VERBOSE;
            case FLOAT_TAG:
                return FLOAT_TAG_VERBOSE;
            case SHORT_TAG:
                return SHORT_TAG_VERBOSE;
            case INT_TAG:
                return INT_TAG_VERBOSE;
            case LONG_TAG:
                return LONG_TAG_VERBOSE;
            case STRING_TAG:
                return STRING_TAG_VERBOSE;
            case ENUM_TAG:
                return ENUM_TAG_VERBOSE;
            case CLASS_TAG:
                return CLASS_TAG_VERBOSE;
            case ANNOTATION_TAG:
                return ANNOTATION_TAG_VERBOSE;
            case ARRAY_TAG:
                return ARRAY_TAG_VERBOSE;
            default:
                return "Unknown";
        }
    }

}


text:
using System;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Web.Hosting;
using System.Web.Security;
using MongoMembership.Mongo;
using MongoMembership.Utils;

namespace MongoMembership.Providers
{
    public class MongoMembershipProvider : MembershipProvider
    {
        #region Fields
        private IMongoGateway mongoGateway;
        private bool enablePasswordReset;
        private bool enablePasswordRetrieval;
        private int maxInvalidPasswordAttempts;
        private int minRequiredNonAlphanumericCharacters;
        private int minRequiredPasswordLength;
        private int passwordAttemptWindow;
        private MembershipPasswordFormat passwordFormat;
        private string passwordStrengthRegularExpression;
        private bool requiresQuestionAndAnswer;
        private bool requiresUniqueEmail;
        #endregion

        #region Properties
        internal string MongoConnectionString { get; private set; }

        public override string ApplicationName { get; set; }

        public override bool EnablePasswordReset => enablePasswordReset;

        public override bool EnablePasswordRetrieval => enablePasswordRetrieval;

        public override int MaxInvalidPasswordAttempts => maxInvalidPasswordAttempts;

        public override int MinRequiredNonAlphanumericCharacters => minRequiredNonAlphanumericCharacters;

        public override int MinRequiredPasswordLength => minRequiredPasswordLength;

        public override int PasswordAttemptWindow => passwordAttemptWindow;

        public override MembershipPasswordFormat PasswordFormat => passwordFormat;

        public override string PasswordStrengthRegularExpression => passwordStrengthRegularExpression;

        public override bool RequiresQuestionAndAnswer => requiresQuestionAndAnswer;

        public override bool RequiresUniqueEmail => requiresUniqueEmail;

        #endregion

        #region Public Methods
        public override void Initialize(string name, NameValueCollection config)
        {
            ApplicationName = config["applicationName"].ConvertOrDefault(HostingEnvironment.ApplicationVirtualPath);

            enablePasswordReset = config["enablePasswordReset"].ConvertOrDefault(true);
            enablePasswordRetrieval = config["enablePasswordRetrieval"].ConvertOrDefault(false);
            maxInvalidPasswordAttempts = config["maxInvalidPasswordAttempts"].ConvertOrDefault(5);
            minRequiredNonAlphanumericCharacters = config["minRequiredNonAlphanumericCharacters"].ConvertOrDefault(1);
            minRequiredPasswordLength = config["minRequiredPasswordLength"].ConvertOrDefault(7);
            passwordAttemptWindow = config["passwordAttemptWindow"].ConvertOrDefault(10);
            passwordFormat = config["passwordFormat"].ConvertOrDefault(MembershipPasswordFormat.Hashed);
            passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"].ConvertOrDefault(string.Empty);
            requiresQuestionAndAnswer = config["requiresQuestionAndAnswer"].ConvertOrDefault(false);
            requiresUniqueEmail = config["requiresUniqueEmail"].ConvertOrDefault(true);
            MongoConnectionString = Util.GetConnectionStringByName(config["connectionStringKeys"].ConvertOrDefault(string.Empty));

            mongoGateway = new MongoGateway(MongoConnectionString);

            if (PasswordFormat == MembershipPasswordFormat.Hashed && EnablePasswordRetrieval)
            {
                throw new ProviderException("Configured settings are invalid: Hashed passwords cannot be retrieved. Either set the password format to different type, or set enablePasswordRetrieval to false.");
            }

            base.Initialize(name, config);
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (username.IsNullOrWhiteSpace()) return false;

            var user = mongoGateway.GetByUserName(ApplicationName, username);

            if (!IsPasswordCorrect(user, oldPassword))
                return false;

            var validatePasswordEventArgs = new ValidatePasswordEventArgs(username, newPassword, false);
            OnValidatingPassword(validatePasswordEventArgs);

            if (validatePasswordEventArgs.Cancel)
                throw new MembershipPasswordException(validatePasswordEventArgs.FailureInformation.Message);

            user.ChangePassword(Encode(newPassword, user.PasswordSalt));
            mongoGateway.UpdateUser(user);
            return true;
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            if (username.IsNullOrWhiteSpace()) return false;
            return UpdateAndReturn(username, user =>
            {
                if (!IsPasswordCorrect(user, password)) return false;
                user.ChangePasswordQuestionAndAnswer(newPasswordQuestion, Encode(newPasswordAnswer, user.PasswordSalt));
                return true;
            });
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            if (providerUserKey == null)
            {
                providerUserKey = Guid.NewGuid();
            }

            var validatePasswordEventArgs = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(validatePasswordEventArgs);

            if (validatePasswordEventArgs.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (RequiresQuestionAndAnswer)
            {
                if (passwordQuestion.IsNullOrWhiteSpace())
                {
                    status = MembershipCreateStatus.InvalidQuestion;
                    return null;
                }
                if (passwordAnswer.IsNullOrWhiteSpace())
                {
                    status = MembershipCreateStatus.InvalidAnswer;
                    return null;
                }
            }

            if (GetUser(username, false) != null)
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }

            if (GetUser(providerUserKey, false) != null)
            {
                status = MembershipCreateStatus.DuplicateProviderUserKey;
                return null;
            }

            if (RequiresUniqueEmail && !GetUserNameByEmail(email).IsNullOrWhiteSpace())
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            var buffer = new byte[16];
            buffer.RngGenerator();
            var passwordSalt = buffer.ToBase64String();

            var createDate = DateTime.UtcNow;
            var user = new User
            {
                Id = providerUserKey.ToString(),
                ApplicationName = ApplicationName,
                CreateDate = createDate,
                EmailLowercase = email?.ToLowerInvariant(),
                Email = email,
                FailedPasswordAnswerAttemptCount = 0,
                FailedPasswordAnswerAttemptWindowStart = createDate,
                FailedPasswordAttemptCount = 0,
                FailedPasswordAttemptWindowStart = createDate,
                IsApproved = isApproved,
                IsDeleted = false,
                IsLockedOut = false,
                LastActivityDate = createDate,
                LastLockedOutDate = new DateTime(1970, 1, 1),
                LastLoginDate = createDate,
                LastPasswordChangedDate = createDate,
                Password = Encode(password, passwordSalt),
                PasswordAnswer = Encode(passwordAnswer, passwordSalt),
                PasswordQuestion = passwordQuestion,
                PasswordSalt = passwordSalt,
                UsernameLowercase = username?.ToLowerInvariant(),
                Username = username
            };

            mongoGateway.CreateUser(user);
            status = MembershipCreateStatus.Success;
            return GetUser(username, false);
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            if (username.IsNullOrWhiteSpace()) return false;
            return UpdateAndReturn(username, user =>
            {
                user.Delete();
                return true;
            });
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            var membershipUsers = new MembershipUserCollection();
            var users = mongoGateway.GetAllByEmail(ApplicationName, emailToMatch, pageIndex, pageSize, out totalRecords);

            foreach (var user in users)
            {
                membershipUsers.Add(user.ToMembershipUser(Name));
            }

            return membershipUsers;
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            var membershipUsers = new MembershipUserCollection();
            var users = mongoGateway.GetAllByUserName(ApplicationName, usernameToMatch, pageIndex, pageSize, out totalRecords);

            foreach (var user in users)
            {
                membershipUsers.Add(user.ToMembershipUser(Name));
            }

            return membershipUsers;
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            var membershipUsers = new MembershipUserCollection();
            var users = mongoGateway.GetAll(ApplicationName, pageIndex, pageSize, out totalRecords);

            foreach (var user in users)
            {
                membershipUsers.Add(user.ToMembershipUser(Name));
            }

            return membershipUsers;
        }

        public override int GetNumberOfUsersOnline()
        {
            var timeSpan = TimeSpan.FromMinutes(Membership.UserIsOnlineTimeWindow);
            return mongoGateway.GetUserForPeriodOfTime(ApplicationName, timeSpan);
        }

        public override string GetPassword(string username, string answer)
        {
            if (!EnablePasswordRetrieval)
                throw new NotSupportedException("This Membership Provider has not been configured to support password retrieval.");

            var user = mongoGateway.GetByUserName(ApplicationName, username);
            ValidatePasswordAnswer(user, answer);

            return DecodePassword(user.Password);
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            return UpdateAndReturn(username, user =>
            {
                if (user == null) return null;
                if (userIsOnline) user.UpdateLastActivityDate();
                return user.ToMembershipUser(Name);
            });
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            var user = mongoGateway.GetById(providerUserKey.ToString());

            if (user == null)
                return null;

            if (userIsOnline)
            {
                user.UpdateLastActivityDate();
                mongoGateway.UpdateUser(user);
            }

            return user.ToMembershipUser(Name);
        }

        public override string GetUserNameByEmail(string email)
        {
            var user = mongoGateway.GetByEmail(ApplicationName, email);
            return user?.Username;
        }

        public override string ResetPassword(string username, string answer)
        {
            if (!EnablePasswordReset)
                throw new NotSupportedException("This provider is not configured to allow password resets. To enable password reset, set enablePasswordReset to \"true\" in the configuration file.");

            return UpdateAndReturn(username, user =>
            {
                ValidatePasswordAnswer(user, answer);
                var password = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters);
                user.ChangePassword(Encode(password, user.PasswordSalt));
                return password;
            });
        }

        public override bool UnlockUser(string username)
        {
            if (username.IsNullOrWhiteSpace()) return false;
            return UpdateAndReturn(username, user =>
            {
                if (user == null) return false;
                user.Unlock();
                return true;
            });
        }

        public override void UpdateUser(MembershipUser membershipUser)
        {
            var user = mongoGateway.GetById(membershipUser.ProviderUserKey?.ToString());

            if (user == null)
                throw new ProviderException("The membershipUser was not found.");

            user.Update(membershipUser);

            mongoGateway.UpdateUser(user);
        }

        public override bool ValidateUser(string username, string password)
        {
            return UpdateAndReturn(username, user =>
            {
                if (user == null || !user.IsApproved || user.IsLockedOut)
                    return false;

                var isPasswordCorrect = IsPasswordCorrect(user, password);
                if (isPasswordCorrect)
                {
                    user.UpdateLastLoginDate();
                }
                else
                {
                    user.PasswordValidationFailed();
                }
                return isPasswordCorrect;
            });
        }
        #endregion

        #region Private Methods
        private T UpdateAndReturn<T>(string username, Func<User, T> updater)
        {
            var user = mongoGateway.GetByUserName(ApplicationName, username);
            var result = updater(user);
            if (user != null) mongoGateway.UpdateUser(user);
            return result;
        }

        private string DecodePassword(string password)
        {
            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    return password;

                case MembershipPasswordFormat.Hashed:
                    throw new ProviderException("Hashed passwords cannot be decoded.");

                default:
                    var passwordBytes = Convert.FromBase64String(password);
                    var decryptedBytes = DecryptPassword(passwordBytes);
                    return decryptedBytes?.ToUnicodeString(16);
            }
        }

        private string Encode(string password, string salt)
        {
            if (password == null || PasswordFormat == MembershipPasswordFormat.Clear)
            {
                return password;
            }

            var passwordBytes = password.ToByteArray();
            var saltBytes = Convert.FromBase64String(salt);
            var allBytes = new byte[saltBytes.Length + passwordBytes.Length];

            Buffer.BlockCopy(saltBytes, 0, allBytes, 0, saltBytes.Length);
            Buffer.BlockCopy(passwordBytes, 0, allBytes, saltBytes.Length, passwordBytes.Length);

            if (PasswordFormat == MembershipPasswordFormat.Hashed)
            {
                return allBytes.ComputeHash().ToBase64String();
            }

            return EncryptPassword(allBytes).ToBase64String();
        }

        private bool IsPasswordCorrect(User user, string password)
        {
            return user.Password == Encode(password, user.PasswordSalt);
        }

        private void ValidatePasswordAnswer(User user, string passwordAnswer)
        {
            if (!RequiresQuestionAndAnswer) return;

            if (user.PasswordAnswer != Encode(passwordAnswer, user.PasswordSalt))
                throw new MembershipPasswordException("The password-answer supplied is invalid.");
        }
        #endregion
    }
}


text:
@interface NSImage (Extensions)

+ (NSImage *)imageFromText:(NSString *)text size:(CGFloat)size;
+ (NSImage *)imageFromView:(NSView *)view;

@end


text:
package com.mercury.platform.ui.adr.components.panel.ui.impl;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class TIconVProgressBarTrackerUI extends VProgressBarTrackerUI {
    @Override
    protected void paintShapes(Graphics g, int barRectWidth, int barRectHeight, Insets insets) {
        if (tracker.isShowCase()) {
            super.paintShapes(g, barRectWidth, barRectHeight, insets);
            return;
        }
        Graphics2D g2 = (Graphics2D) g.create();
        int iconX = 0;
        int iconY = 0;
        int sectorX = 0;
        int sectorY = (int) ((barRectHeight - barRectWidth) * (1f - this.tracker.getPercentComplete())) + barRectWidth;
        if (this.descriptor.isInvertMask()) {
            sectorY = (int) ((barRectHeight - barRectWidth) * this.tracker.getPercentComplete()) + barRectWidth;
        }
        float sectorHeight = barRectHeight - sectorY;
        Shape outer = new Rectangle2D.Double(0, 0, barRectWidth, barRectHeight);
        Shape sector = new Rectangle2D.Double(insets.left + sectorX, insets.top + sectorY, barRectWidth - insets.right * 2, sectorHeight - insets.bottom * 2);
        try {
            BufferedImage read = ImageIO.read(this.config.getIcon(descriptor.getIconPath()));
            g2.drawImage(read, iconX, iconY, tracker.getWidth(), tracker.getWidth(), null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Area foreground = new Area(sector);
        Area background = new Area(outer);

        foreground.intersect(background);
        g2.setPaint(descriptor.getForegroundColor());
        g2.fill(foreground);
        g2.dispose();
        this.paintString(g, 0, this.tracker.getWidth(), barRectWidth, barRectHeight - tracker.getWidth(), 0);
    }
}


text:
#include "stdafx.h"
#include "DeviceScannerPPC.h"
#include "DeviceScannerPPCDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CDeviceScannerPPCApp

BEGIN_MESSAGE_MAP(CDeviceScannerPPCApp, CWinApp)
	//{{AFX_MSG_MAP(CDeviceScannerPPCApp)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDeviceScannerPPCApp construction

CDeviceScannerPPCApp::CDeviceScannerPPCApp()
	: CWinApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CDeviceScannerPPCApp object

CDeviceScannerPPCApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CDeviceScannerPPCApp initialization

BOOL CDeviceScannerPPCApp::InitInstance()
{
	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

	CDeviceScannerPPCDlg dlg;
	m_pMainWnd = &dlg;
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}