text:
#import "GameOfLifeLayer.h"
#import "OptionsLayer.h"
#import "PoolOfLife.h"
#import "SoundManager.h"

@interface GameOfLifeLayer () <PoolOfLifeDelegate, OptionsLayerDelegate>
@property (nonatomic) BOOL done;
@property (nonatomic, strong) PoolOfLife *game;
//Define next grid update. Maybe a from an rng.
@property (nonatomic) ccTime nextUpdateTime;
@property (nonatomic) ccTime currentTime;
@property (nonatomic) ccColor4F toggleButtonColor;
@property (nonatomic) ccColor4F resetButtonColor;
@property (nonatomic, weak) CCLabelTTF *toggleLabel;
@property (nonatomic, strong) SoundManager *soundManager;
@property (nonatomic, strong) OptionsLayer *optionsLayer;
@property (nonatomic, weak) KKRotationRate *rotationRate;
@property (nonatomic, weak) KKAcceleration *acceleration;
@property (nonatomic) float currentIntensity;
@property (nonatomic) float lastYAcceleration;
//Window properties
@property (nonatomic) NSInteger widthWindow;
@property (nonatomic) NSInteger heightWindow;
@property (nonatomic) CGFloat yOffset;
@property (nonatomic) CGFloat cellWidthPercentage;
@property (nonatomic) NSInteger cellWidth;
@property (nonatomic) NSInteger widthGame;
@property (nonatomic) NSInteger heightGame;
@property (nonatomic) NSInteger gameOffset;
@property (nonatomic) NSInteger numRows;
@property (nonatomic) NSInteger numCols;
@property (nonatomic) float delayInSeconds;
@property (nonatomic) CGFloat fontSize;
//Game properties
@property (nonatomic) PoolOfLifeGameMode gameMode;
@property (nonatomic) ccTime currentBeatDelta;
@end

@implementation GameOfLifeLayer

#define TOGGLE_BUTTON_COLOR_NORMAL ccc4f(150.0/255.0, 0.0, 1.0, 1.0)
#define BUTTON_COLOR_PRESSED ccc4f(1.0, 0.0, 1.0, 1.0)
#define RESET_BUTTON_COLOR_NORMAL ccc4f(50.0/255.0, 0.0, 1.0, 1.0)
#define CELL_COLOR ccc4f(100.0/255.0, 0, 1.0, 1.0)
#define FOOD_COLOR ccc4f(188.0/255.0, 143.0/255.0, 143.0/255.0, 1.0) //188-143-143 = "Rosy Brown"

#pragma mark -

-(OptionsLayer *)optionsLayer
{
    if(!_optionsLayer)
    {
        _optionsLayer = [OptionsLayer node];
        _optionsLayer.delegate = self;
    }
    return _optionsLayer;
}

-(void)setDone:(BOOL)done
{
    _done = done;
    if(done)
    {
        self.soundManager.playing = NO;
        self.toggleButtonColor = BUTTON_COLOR_PRESSED;
        self.toggleLabel.string = @"Paused";
    }
    else
    {
        self.soundManager.playing = YES;
        self.toggleButtonColor = TOGGLE_BUTTON_COLOR_NORMAL;
        self.toggleLabel.string = @"Pause";
    }
}

-(PoolOfLife *)game
{
    if(!_game)
    {
        _game = [[PoolOfLife alloc] initWithRows:self.numRows cols:self.numCols gameMode:self.gameMode];
    }
    return _game;
}

-(KKAcceleration *)acceleration
{
    if(!_acceleration)
    {
        KKInput *input = [KKInput sharedInput];
        if(input.accelerometerAvailable)
        {
            input.accelerometerActive = YES;
            _acceleration = input.acceleration;
        }
    }
    return _acceleration;
}

#pragma mark Lifecycle

-(id) init
{
	if ((self = [super init]))
	{
        //Properties
        CGSize winSize = [[CCDirector sharedDirector] winSize];
        self.heightWindow = winSize.height;
        self.widthWindow = winSize.width;
        self.yOffset = (self.heightWindow * .04375f);
        //Cells
        self.cellWidthPercentage = 20.0f / self.widthWindow;
        self.cellWidth = (NSInteger)(self.widthWindow * self.cellWidthPercentage);
        //Game
        self.widthGame = self.widthWindow;
        self.gameOffset = (NSInteger)(self.heightWindow * .125);
        self.heightGame = self.heightWindow - self.gameOffset;
        //Cols/Rows
        self.numCols = self.widthGame / self.cellWidth;
        self.numRows = self.heightGame / self.cellWidth;
        //Other
        self.delayInSeconds = 0.17f;
        self.fontSize = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? 26.0f : 18.0f);
        self.gameMode = PoolOfLifeGameModeConwayWithFood;
        self.currentBeatDelta = 0.16667f;

        //Natural Major scale
        self.soundManager = [[SoundManager alloc] initWithScale:kSoundManagerScaleIonian];
        self.soundManager.numCols = self.numCols;
        self.game.delegate = self;
        self.currentIntensity = 1.0f;

        [self reset:NO];
        //[self schedule:@selector(nextStep) interval:DELAY_IN_SECONDS];
        [self scheduleUpdate];
        CCLabelTTF *resetButton = [CCLabelTTF labelWithString:@"Reset" fontName:@"Helvetica" fontSize:self.fontSize];
        resetButton.position = CGPointMake(self.widthWindow / 4, self.heightWindow - self.yOffset);
        self.toggleLabel = [CCLabelTTF labelWithString:@"Pause" fontName:@"Helvetica" fontSize:self.fontSize];
        self.toggleLabel.position = CGPointMake((self.widthWindow / 4) * 3, self.heightWindow - self.yOffset);
        self.toggleButtonColor = TOGGLE_BUTTON_COLOR_NORMAL;
        [self addChild:resetButton];
        [self addChild:self.toggleLabel];
	}
	return self;
}

-(void)reset:(BOOL)withColorChange
{
    [self.game reset];
    if(withColorChange)
    {
        self.resetButtonColor = BUTTON_COLOR_PRESSED;
        [self scheduleOnce:@selector(resetButtonNormal) delay:self.delayInSeconds];
    }
    else
    {
        self.resetButtonColor = RESET_BUTTON_COLOR_NORMAL;
    }
}

-(void)resetButtonNormal
{
    self.resetButtonColor = RESET_BUTTON_COLOR_NORMAL;
}

#pragma mark -

//-(void)didActivateCellAtRow:(NSInteger)row col:(NSInteger)col numActive:(NSInteger)numActive
//{
//    //Float32 pitch = ((440.0f / NUM_COLS) * (col + 1)) / 440.0f; //Based on column
//    Float32 gain = ((row + 1.0f) / (4 * NUM_ROWS)) * (1.0f / numActive); //Based on row
//    //NSLog(@"pitch: %g, gain: %g, active: %d", pitch, gain, self.cellsCurrentlyActive);
//    //[self.audioEngine playEffect:@"a-sound.WAV" pitch:pitch pan:0 gain:gain];
//    [self.audioEngine playEffect:[SOUNDS objectAtIndex:(col % [SOUNDS count])] pitch:1.0f pan:0.0f gain:gain];
//}
-(void)updateIntensity
{
    if(self.acceleration)
    {
        //NSLog(@"x: %g, y: %g, z: %g", self.rotationRate.x, self.rotationRate.y, self.rotationRate.z);
        //intensity += self.rotationRate.x * intensityStep;
        //NSLog(@"x: %g, y: %g, z: %g", self.acceleration.smoothedX, self.acceleration.smoothedY, self.acceleration.smoothedZ);
        float currentAcceleration = self.acceleration.smoothedY;
        float deltaY = self.lastYAcceleration - currentAcceleration;
        //NSLog(@"y: %g, deltaY: %g", self.acceleration.smoothedY, deltaY);
        self.lastYAcceleration = currentAcceleration;
        self.currentIntensity += deltaY;
        if(self.currentIntensity > 1.0f)
        {
            self.currentIntensity = 1.0f;
        }
        else if(self.currentIntensity < 0.0f)
        {
            self.currentIntensity = 0.0f;
        }
        //NSLog(@"current intensity: %g", self.currentIntensity);
    }
}

-(void)didActivateCellAtRow:(NSInteger)row col:(NSInteger)col numActive:(NSInteger)numActive
{
    if(!self.soundManager.isPlaying)
    {
        self.soundManager.playing = YES;
    }
    [self updateIntensity];
    [self.soundManager playNoteForCol:col intensity:self.currentIntensity];
}

-(void)didFinishUpdatingRowWithResultingRow:(NSArray *)row
{
    if(!self.soundManager.isPlaying)
    {
        self.soundManager.playing = YES;
    }
    [self updateIntensity];
    [self.soundManager pushRow:row intensity:self.currentIntensity];
}

-(void)didFinishWithOptionsLayer
{
    [self.optionsLayer layerWillDisappear];
    [self removeChild:self.optionsLayer];
    self.done = NO;
    self.toggleButtonColor = TOGGLE_BUTTON_COLOR_NORMAL;
}

-(void)didSetOption:(PoolOfLifeOption)option withValue:(id)value
{
    switch (option) {
        case PoolOfLifeOptionGameMode:
            self.gameMode = (PoolOfLifeGameMode)value;
            break;
        default:
            break;
    }
}

#pragma mark -

-(void)update:(ccTime)delta
{
    self.currentTime += delta;
    //Check if it's time for the next grid update
    if(self.currentTime > self.nextUpdateTime)
    {
        if(!self.done)
        {
            //Perform the next step
            [self.game stepThroughCycle];
        }
        //Set the next update time
        self.nextUpdateTime = self.currentTime + self.currentBeatDelta;
        //NSLog(@"Next delta: %g, updating: %g", nextDelta, self.nextUpdateTime);
    }
    //React to touch input
    KKInput *input = [KKInput sharedInput];
    if(input.touchesAvailable && !self.optionsLayer.isLayerCurrentlyVisible)
    {
        KKTouch *touch;
        CCARRAY_FOREACH(input.touches, touch)
        {
            CGPoint touchLocation = touch.location;
            NSInteger row = touchLocation.y / self.cellWidth;
            NSInteger col = touchLocation.x / self.cellWidth;
            if(touch.phase == KKTouchPhaseBegan)
            {
                //Handle touches on the right button
                if(touchLocation.x >= self.widthWindow / 2 && touchLocation.y > self.heightGame + self.yOffset)
                {
                    self.done = !self.done;
                    if(self.done)
                    {
                        [self.soundManager stopPlaying];
                    }
//                    if(self.optionsLayer.isLayerCurrentlyVisible)
//                    {
//                        [self.optionsLayer layerWillDisappear];
//                        [self removeChild:self.optionsLayer];
//                    }
//                    else
//                    {
//                        [self.optionsLayer layerWillAppear];
//                        [self addChild:self.optionsLayer];
//                    }
                }
                //Handle touches on the left button
                else if(touchLocation.x < self.widthWindow / 2 && touchLocation.y > self.heightGame + self.yOffset)
                {
                    [self reset:YES];
                }
            }
            if(row >= 0 && row < self.numRows && col >= 0 && col < self.numCols)
            {
                [self.game flipCellAtRow:row col:col started:(touch.phase == KKTouchPhaseBegan)];
            }
        }
    }
}

-(void) draw
{
    ccDrawSolidRect(CGPointMake(0, 0),
                    CGPointMake(self.widthGame, self.heightGame),
                    ccc4f(0, 1, 1, 1));

    //Set the color in RGB to draw the line with:
    ccDrawColor4B(100, 0, 255, 255); //purple, values range from 0 to 255

    //Draw row lines
    for(int row = 0; row < self.numRows; row ++)
    {
        //and now draw a line between them!
        ccDrawLine(CGPointMake(0,row * self.cellWidth),
                   CGPointMake(self.widthGame, row * self.cellWidth));
    }

    // Draw column lines
    for(int col = 0; col < self.numCols; col ++)
    {
        //and now draw a line between them!
        ccDrawLine(CGPointMake(col * self.cellWidth, 0),
                   CGPointMake(col * self.cellWidth, self.heightGame));
    }

    //Fill in active locations in the gameGrid
    for(int row = 0; row < self.numRows; row ++)
    {
        for(int col = 0; col < self.numCols; col ++)
        {
            NSInteger cellValue = [self.game cellAtRow:row col:col];
            NSInteger foodValue = [self.game foodAtRow:row col:col];
            if(cellValue || foodValue)
            {
                ccDrawSolidRect(CGPointMake(col * self.cellWidth, row * self.cellWidth),
                                CGPointMake((col + 1) * self.cellWidth, (row + 1) * self.cellWidth),
                                (cellValue ? CELL_COLOR : FOOD_COLOR));
            }
        }
    }

    //Draw the button
    ccDrawSolidRect(CGPointMake(self.widthWindow / 2, self.heightGame + self.yOffset),
                    CGPointMake(self.widthWindow, self.heightWindow),
                    self.toggleButtonColor);

    //Draw the clear button
    ccDrawSolidRect(CGPointMake(0, self.heightGame + self.yOffset),
                    CGPointMake(self.widthWindow / 2, self.heightWindow),
                    self.resetButtonColor);
}

+(CCScene *)scene
{
    CCScene *scene = [CCScene node];
    [scene addChild:[self node]];
    return scene;
}

@end


text:
require 'builder/blankslate'

module Builder

  # Generic error for builder
  class IllegalBlockError < RuntimeError; end

  # XmlBase is a base class for building XML builders.  See
  # Builder::XmlMarkup and Builder::XmlEvents for examples.
  class XmlBase < BlankSlate

    class << self
      attr_accessor :cache_method_calls
    end

    # Create an XML markup builder.
    #
    # out      :: Object receiving the markup.  +out+ must respond to
    #             <tt><<</tt>.
    # indent   :: Number of spaces used for indentation (0 implies no
    #             indentation and no line breaks).
    # initial  :: Level of initial indentation.
    # encoding :: When <tt>encoding</tt> and $KCODE are set to 'utf-8'
    #             characters aren't converted to character entities in
    #             the output stream.
    def initialize(indent=0, initial=0, encoding='utf-8')
      @indent = indent
      @level  = initial
      @encoding = encoding.downcase
    end

    def explicit_nil_handling?
      @explicit_nil_handling
    end

    # Create a tag named +sym+.  Other than the first argument which
    # is the tag name, the arguments are the same as the tags
    # implemented via <tt>method_missing</tt>.
    def tag!(sym, *args, &block)
      text = nil
      attrs = nil
      sym = "#{sym}:#{args.shift}" if args.first.kind_of?(::Symbol)
      sym = sym.to_sym unless sym.class == ::Symbol
      args.each do |arg|
        case arg
        when ::Hash
          attrs ||= {}
          attrs.merge!(arg)
        when nil
          attrs ||= {}
          attrs.merge!({:nil => true}) if explicit_nil_handling?
        else
          text ||= ''
          text << arg.to_s
        end
      end
      if block
        unless text.nil?
          ::Kernel::raise ::ArgumentError,
            "XmlMarkup cannot mix a text argument with a block"
        end
        _indent
        _start_tag(sym, attrs)
        _newline
        begin
          _nested_structures(block)
        ensure
          _indent
          _end_tag(sym)
          _newline
        end
      elsif text.nil?
        _indent
        _start_tag(sym, attrs, true)
        _newline
      else
        _indent
        _start_tag(sym, attrs)
        text! text
        _end_tag(sym)
        _newline
      end
      @target
    end

    # Create XML markup based on the name of the method.  This method
    # is never invoked directly, but is called for each markup method
    # in the markup block that isn't cached.
    def method_missing(sym, *args, &block)
      cache_method_call(sym) if ::Builder::XmlBase.cache_method_calls
      tag!(sym, *args, &block)
    end

    # Append text to the output target.  Escape any markup.  May be
    # used within the markup brackets as:
    #
    #   builder.p { |b| b.br; b.text! "HI" }   #=>

HI

    def text!(text)
      _text(_escape(text))
    end

    # Append text to the output target without escaping any markup.
    # May be used within the markup brackets as:
    #
    #   builder.p { |x| x << "
HI" }   #=>

HI

    #
    # This is useful when using non-builder enabled software that
    # generates strings.  Just insert the string directly into the
    # builder without changing the inserted markup.
    #
    # It is also useful for stacking builder objects.  Builders only
    # use <tt><<</tt> to append to the target, so by supporting this
    # method/operation builders can use other builders as their
    # targets.
    def <<(text)
      _text(text)
    end

    # For some reason, nil? is sent to the XmlMarkup object.  If nil?
    # is not defined and method_missing is invoked, some strange kind
    # of recursion happens.  Since nil? won't ever be an XML tag, it
    # is pretty safe to define it here. (Note: this is an example of
    # cargo cult programming,
    # cf. http://fishbowl.pastiche.org/2004/10/13/cargo_cult_programming).
    def nil?
      false
    end

    private

    require 'builder/xchar'
    if ::String.method_defined?(:encode)
      def _escape(text)
        result = XChar.encode(text)
        begin
          encoding = ::Encoding::find(@encoding)
          raise Exception if encoding.dummy?
          result.encode(encoding)
        rescue
          # if the encoding can't be supported, use numeric character references
          result.
            gsub(/[^\u0000-\u007F]/) {|c| "&##{c.ord};"}.
            force_encoding('ascii')
        end
      end
    else
      def _escape(text)
        if (text.method(:to_xs).arity == 0)
          text.to_xs
        else
          text.to_xs((@encoding != 'utf-8' or $KCODE != 'UTF8'))
        end
      end
    end

    def _escape_attribute(text)
      _escape(text).gsub("\n", "
").gsub("\r", "
").
        gsub(%r{"}, '"') # " WART
    end

    def _newline
      return if @indent == 0
      text! "\n"
    end

    def _indent
      return if @indent == 0 || @level == 0
      text!(" " * (@level * @indent))
    end

    def _nested_structures(block)
      @level += 1
      block.call(self)
    ensure
      @level -= 1
    end

    # If XmlBase.cache_method_calls = true, we dynamicly create the method
    # missed as an instance method on the XMLBase object. Because XML
    # documents are usually very repetative in nature, the next node will
    # be handled by the new method instead of method_missing. As
    # method_missing is very slow, this speeds up document generation
    # significantly.
    def cache_method_call(sym)
      class << self; self; end.class_eval do
        unless method_defined?(sym)
          define_method(sym) do |*args, &block|
            tag!(sym, *args, &block)
          end
        end
      end
    end
  end

  XmlBase.cache_method_calls = true

end

redpajama_set_name: RedPajamaGithub


text:
from django.contrib import admin

from account.models import UserInfo

admin.site.register(UserInfo)


text:
int main()
{
    LoadPythonInterperter();
    return 0;
}
#endif


text:
TRACER_FLAG_USEATTACHMENT	= 0x0002;
SOUND_FROM_WORLD			= 0;
CHAN_STATIC					= 6;

EFFECT.Speed				= 6500;
EFFECT.Length				= 64;
//EFFECT.WhizSound			= Sound( "nomad/whiz.wav" );		-- by Robinhood76 (http:--www.freesound.org/people/Robinhood76/sounds/96556/)
EFFECT.WhizDistance			= 72;

local MaterialMain			= Material( "effects/sw_laser_green_main" );
local MaterialFront			= Material( "effects/sw_laser_green_front" );

function EFFECT:GetTracerOrigin( data )

	-- this is almost a direct port of GetTracerOrigin in fx_tracer.cpp
	local start = data:GetStart();

	-- use attachment?
	if( bit.band( data:GetFlags(), TRACER_FLAG_USEATTACHMENT ) == TRACER_FLAG_USEATTACHMENT ) then

		local entity = data:GetEntity();
		local att =2-entity.AnimCycle or data:GetAttachment()

		if( not IsValid( entity ) ) then return start; end
		if( not game.SinglePlayer() and entity:IsEFlagSet( EFL_DORMANT ) ) then return start; end

		if( entity:IsWeapon() and entity:IsCarriedByLocalPlayer() ) then
			-- can't be done, can't call the real function
			-- local origin = weapon:GetTracerOrigin();
			-- if( origin ) then
			-- 	return origin, angle, entity;
			-- end

			-- use the view model
			local pl = entity:GetOwner();
			if( IsValid( pl ) ) then
				local vm = pl:GetViewModel();
				if( IsValid( vm ) and not LocalPlayer():ShouldDrawLocalPlayer() ) then
					entity = vm;
				else
					-- HACK: fix the model in multiplayer
					if( entity.WorldModel ) then
						entity:SetModel( entity.WorldModel );
					end
				end
			end
		end

		local attachment = entity:GetAttachment( att );
		if( attachment ) then
			start = attachment.Pos;
		end

	end

	return start;

end

function EFFECT:Init( data )

	self.StartPos = self:GetTracerOrigin( data );
	self.EndPos = data:GetOrigin();

	self.Entity:SetRenderBoundsWS( self.StartPos, self.EndPos );

	local diff = ( self.EndPos - self.StartPos );

	self.Normal = diff:GetNormal();
	self.StartTime = 0;
	self.LifeTime = ( diff:Length() + self.Length ) / self.Speed;

	-- whiz by sound
	local weapon = data:GetEntity();
	if( IsValid( weapon ) and ( not weapon:IsWeapon() or not weapon:IsCarriedByLocalPlayer() ) ) then

		local dist, pos, time = util.DistanceToLine( self.StartPos, self.EndPos, EyePos() );
	end
end

function EFFECT:Think()

	self.LifeTime = self.LifeTime - FrameTime();
	self.StartTime = self.StartTime + FrameTime();

	return self.LifeTime > 0;

end

function EFFECT:Render()

	local endDistance = self.Speed * self.StartTime;
	local startDistance = endDistance - self.Length;

	startDistance = math.max( 0, startDistance );
	endDistance = math.max( 0, endDistance );

	local startPos = self.StartPos + self.Normal * startDistance;
	local endPos = self.StartPos + self.Normal * endDistance;

	render.SetMaterial( MaterialFront );
	render.DrawSprite( endPos, 8, 8, color_white );

	render.SetMaterial( MaterialMain );
	render.DrawBeam( startPos, endPos, 10, 0, 1, color_white );

end


text:
<?php

namespace OOUI;

/**
 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
 * items), with small margins between them.
 */
class HorizontalLayout extends Layout {
	/**
	 * @param array $config Configuration options
	 * @param Widget[]|Layout[] $config['items'] Widgets or other layouts to add to the layout.
	 */
	public function __construct( array $config = array() ) {
		// Parent constructor
		parent::__construct( $config );

		// Mixins
		$this->mixin( new GroupElement( $this, array_merge( $config, array( 'group' => $this ) ) ) );

		// Initialization
		$this->addClasses( array( 'oo-ui-horizontalLayout' ) );
		if ( isset( $config['items'] ) ) {
			$this->addItems( $config['items'] );
		}
	}
}


text:
package main

import (
	"fmt"
	"time"

	"github.com/coscms/webx"
)

type MainAction struct {
	*webx.Action

	start time.Time

	hello webx.Mapper `webx:"/(.*)"`
}

func (c *MainAction) Hello(world string) bool {
	c.Write("hello %v", world)
	return true
}

func (c *MainAction) Before(structName, actionName string) bool {
	c.start = time.Now()
	fmt.Println("before", c.start)
	return true
}

func (c *MainAction) After(structName, actionName string, actionResult interface{}) bool {
	fmt.Println("after", time.Now().Sub(c.start))
	return true
}

func main() {
	webx.AddRouter("/", &MainAction{})
	webx.Run("0.0.0.0:9999")
}


text:
title: Save Made Changes to TreeView to Database
page_title: Save Made Changes to TreeView to Database - RadTreeView
description: Check our Web Forms article about Save Made Changes to TreeView to Database.
slug: treeview/application-scenarios/server-side-programming/save-made-changes-to-treeview-to-database
tags: save,made,changes,to,treeview,to,database
published: True
position: 1
---

# Save Made Changes to TreeView to Database

##

This example demonstrates a simple mechanism using **Access database** with single self-referencing table containing columns **id**, **parentId** and **Text**.

The structure of the **TreeView** is loaded from this database in the **Page_Load** event. Then the user edits the text of random nodes in the **TreeView** and hits the **Save** button on the page. Thus, a postback is triggered and the updated information is saved back in the database file.

The code below shows the approach:

````C#
protected System.Web.UI.WebControls.Button Button1;
protected Telerik.Web.UI.RadTreeView RadTree1;
protected OleDbCommand command;
protected OleDbConnection con;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        GenerateTreeView();
    }
}
private void GenerateTreeView()
{
    OleDbConnection dbCon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("treeSave.mdb"));
    //the database is in the web app root!
    dbCon.Open();
    OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Links", dbCon);
    DataSet ds = new DataSet();
    adapter.Fill(ds);
    ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["id"], ds.Tables[0].Columns
    ["parentId"]);
    foreach (DataRow dbRow in ds.Tables[0].Rows)
    {
        if (dbRow.IsNull("parentId"))
        {
            RadTreeNode node = CreateNode(dbRow["Text"].ToString(), true);
            RadTree1.Nodes.Add(node);
            RecursivelyPopulate(dbRow, node);
        }
    }
}
private void RecursivelyPopulate(DataRow dbRow, RadTreeNode node)
{
    foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))
    {
        RadTreeNode childNode = CreateNode(childRow["Text"].ToString(), true);
        node.Nodes.Add(childNode);
        RecursivelyPopulate(childRow, childNode);
    }
}
private RadTreeNode CreateNode(string text, bool expanded)
{
    RadTreeNode node = new RadTreeNode(text);
    node.Expanded = true;
    return node;
}

private void RadTree1_NodeEdit(object o, Telerik.Web.UI.RadTreeNodeEditEventArgs e)
{
    RadTreeNode edit = e.Node;
    String text = e.Text;
    edit.Text = text;
}
private void Button1_Click(object sender, System.EventArgs e)
{
    con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
    Server.MapPath("treeSave.mdb"));
    con.Open();
    command = new OleDbCommand("DELETE * from Links", con);
    command.ExecuteNonQuery();
    con.Close();
    UpdateNodes();
}
private void UpdateNodes()
{
    OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DataSource=" + Server.MapPath("treeSave.mdb"));
    con.Open();
    IList<RadTreeNode> allNodes = RadTree1.GetAllNodes();
    for (int i = 0; i < allNodes.Count; i++)
    {
        RadTreeNode node = (RadTreeNode)allNodes[i];
        int parentId = node.ParentNode == null ? -1 : allNodes.IndexOf(node.ParentNode);
        command = new OleDbCommand("INSERT into Links([id],parentId,[Text]) values (@ID,@parentId,@Text)", con);
        command.Parameters.AddWithValue("ID", i.ToString());
        if (parentId > -1)
            command.Parameters.AddWithValue("parentId", parentId);
        else
            command.Parameters.AddWithValue("parentId", System.DBNull.Value);
        command.Parameters.AddWithValue("Text", node.Text);
        command.ExecuteNonQuery();
    }
    con.Close();
}
````
````VB.NET
Protected Button1 As System.Web.UI.WebControls.Button
Protected RadTree1 As Telerik.Web.UI.RadTreeView
Protected command As OleDbCommand
Protected con As OleDbConnection
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Page.IsPostBack Then
        GenerateTreeView()
    End If
End Sub
Private Sub GenerateTreeView()
    Dim dbCon As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("treeSave.mdb"))
    'the database is in the web app root!
    dbCon.Open()
    Dim adapter As New OleDbDataAdapter("SELECT * FROM Links", dbCon)
    Dim ds As New DataSet()
    adapter.Fill(ds)
    ds.Relations.Add("NodeRelation", ds.Tables(0).Columns("id"), ds.Tables(0).Columns("parentId"))
    For Each dbRow As DataRow In ds.Tables(0).Rows
        If dbRow.IsNull("parentId") Then
            Dim node As RadTreeNode = CreateNode(dbRow("Text").ToString(), True)
            RadTree1.Nodes.Add(node)
            RecursivelyPopulate(dbRow, node)
        End If
    Next
End Sub
Private Sub RecursivelyPopulate(ByVal dbRow As DataRow, ByVal node As RadTreeNode)
    For Each childRow As DataRow In dbRow.GetChildRows("NodeRelation")
        Dim childNode As RadTreeNode = CreateNode(childRow("Text").ToString(), True)
        node.Nodes.Add(childNode)
        RecursivelyPopulate(childRow, childNode)
    Next
End Sub
Private Function CreateNode(ByVal text As String, ByVal expanded As Boolean) As RadTreeNode
    Dim node As New RadTreeNode(text)
    node.Expanded = True
    Return node
End Function

Private Sub RadTree1_NodeEdit(ByVal o As Object, ByVal e As Telerik.Web.UI.RadTreeNodeEditEventArgs)
    Dim edit As RadTreeNode = e.Node
    Dim text As String = e.Text
    edit.Text = text
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("treeSave.mdb"))
    con.Open()
    command = New OleDbCommand("DELETE * from Links", con)
    command.ExecuteNonQuery()
    con.Close()
    UpdateNodes()
End Sub
Private Sub UpdateNodes()
    Dim con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DataSource=" + Server.MapPath("treeSave.mdb"))
    con.Open()
    Dim allNodes As IList(Of RadTreeNode) = RadTree1.GetAllNodes()
    Dim i As Integer = 0
    While i < allNodes.Count
        Dim node As RadTreeNode = DirectCast(allNodes(i), RadTreeNode)
        Dim parentId As Integer = IIf(node.ParentNode Is Nothing, -1, allNodes.IndexOf(node.ParentNode))
        command = New OleDbCommand("INSERT into Links([id],parentId,[Text]) values (@ID,@parentId,@Text)", con)
        command.Parameters.AddWithValue("ID", i.ToString())
        If parentId > -1 Then
            command.Parameters.AddWithValue("parentId", parentId)
        Else
            command.Parameters.AddWithValue("parentId", System.DBNull.Value)
        End If
        command.Parameters.AddWithValue("Text", node.Text)
        command.ExecuteNonQuery()
        System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
    End While
    con.Close()
End Sub
````

# See Also

 * [Overview]({%slug treeview/server-side-programming/events/overview%})


text:
package main.java.de.k4lly.enchant;

import main.java.de.k4lly.enchant.controller.ConfigController;
import main.java.de.k4lly.enchant.controller.PluginController;
import main.java.de.k4lly.enchant.listener.*;
import main.java.de.k4lly.enchant.listener.commands.*;
import main.java.de.k4lly.enchant.objects.*;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapelessRecipe;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin {

    private PluginController controller = new PluginController();
    private final String enable = "[" + this.getName() + "] Loaded " + this.getDescription().getName() + " in Version " + this.getDescription().getVersion() + " succesfully!";
    private final String regEnchant = "[" + this.getName() + "] Successfully registered all Enchantments";
    private final String regEvent = "[" + this.getName() + "] Successfully registered Events!";

    @Override
    public void onEnable() {
        controller.setMain(this);
        PluginManager pluginManager = getServer().getPluginManager();
        registerEvent(pluginManager);
        controller.setConfig(new ConfigController(controller));
        registerRecipe();
        System.out.print(enable);
    }

    private void registerEvent(PluginManager pluginManager) {
        Command command = new Command(controller);
        CommandVersion commandVersion = new CommandVersion(controller);
        CommandSafeMining commandSafeMining = new CommandSafeMining(controller);
        this.getCommand("k4llyEnchant").setExecutor(command);
        this.getCommand("kE").setExecutor(command);
        this.getCommand("kEVersion").setExecutor(commandVersion);
        //this.getCommand("kEsafemining").setExecutor(commandSafeMining);
        pluginManager.registerEvents(new Anvil(controller), this);
        pluginManager.registerEvents(new Crafting(controller), this);
        registerEnchantment(pluginManager);
        System.out.print(regEvent);
    }

    private void registerRecipe() {
        if (this.getConfig().getBoolean("enableTakeEnchantment")) {
            for (Material enchItem : UtilMaterial.getEnchantableMaterial()) {
                ShapelessRecipe sr = new ShapelessRecipe(new ItemStack(Material.ENCHANTED_BOOK, 1));
                sr.addIngredient(Material.BOOK);
                sr.addIngredient(Material.EXP_BOTTLE);
                sr.addIngredient(enchItem);
                this.getServer().addRecipe(sr);
            }
        }
    }

    public void registerEnchantment(PluginManager pluginManager) {
        //pluginManager.registerEvents(new Enchanting(controller), this);
        //pluginManager.registerEvents(new EnchantmentNightVision(controller), this);
        //pluginManager.registerEvents(new EnchantmentXPBoost(controller), this);
        //pluginManager.registerEvents(new EnchantmentWither(controller), this);
        //pluginManager.registerEvents(new EnchantmentPoisonTouch(controller), this);
        //pluginManager.registerEvents(new EnchantmentFireTouch(controller), this);
        //pluginManager.registerEvents(new EnchantmentRapidFire(controller), this);
        pluginManager.registerEvents(new InfiniteArrow(controller), this);
        System.out.print(regEnchant);
    }

    @Override
    public void onDisable() {
    }
}


text:
from tic.core import Interface

class CustomJsException(Exception):
    """
    raise this exception only if you know what your doing

    the message of this exception will be evaluated in the browser

    so if you raise CustomJsException('console.log("exception from python")')
    it will log it in the browser's console
    """
##
## JSON RPC
##
class IJsonRpcService(Interface):
    """
    Marker interface for all json rpc services
    """


text:
module Cobalt
  module Shared
    VERSION = '0.2.4'
  end
end


text:
using System;
using JetBrains.Annotations;

namespace BudgetAnalyser.Engine.Ledger.Data
{
    /// <summary>
    ///     A Dto for all subclasses of <see cref="LedgerTransaction" />.  All subclasses are flattened into this type.
    /// </summary>
    public class LedgerTransactionDto
    {
        /// <summary>
        ///     Gets or sets the account identifier.
        /// </summary>
        public string Account { get; set; }

        /// <summary>
        ///     Gets or sets the amount.
        /// </summary>
        public decimal Amount { get; set; }

        /// <summary>
        ///     Gets or sets the automatic matching reference.
        /// </summary>
        [UsedImplicitly]
        public string AutoMatchingReference { get; set; }

        /// <summary>
        ///     Gets or sets the date.
        /// </summary>
        [UsedImplicitly]
        public DateTime? Date { get; set; }

        /// <summary>
        ///     Gets or sets the transaction identifier.
        /// </summary>
        public Guid Id { get; set; }

        /// <summary>
        ///     Gets or sets the narrative.
        /// </summary>
        public string Narrative { get; set; }

        /// <summary>
        ///     Gets or sets the type of the transaction.
        /// </summary>
        public string TransactionType { get; set; }
    }
}


text:
<manifest package="com.dmitrymalkovich.android.materialdesigndimens">

    <application />

</manifest>


text:
package io.quarkus.smallrye.reactivemessaging.mutiny;

import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;

public class MultiTest {
    @RegisterExtension
    static final QuarkusUnitTest config = new QuarkusUnitTest()
            .withApplicationRoot((jar) -> jar
                    .addClasses(MultiIntBean.class, MultiStringBean.class, StringProducer.class));

    @Inject
    MultiIntBean multiIntBean;
    @Inject
    MultiStringBean multiStringBean;

    @Test
    public void shouldGatherEvenFromMultiBean() {
        await().atMost(5, TimeUnit.SECONDS)
                .until(() -> multiIntBean.getEvenNumbers().size() > 5);

        assertThat(multiIntBean.getEvenNumbers()).contains(2, 4, 6, 8, 10, 12);
    }

    @Test
    public void shouldGetHelloFromMultiBean() {
        List<String> strings = multiStringBean.getStrings(Duration.ofSeconds(5));
        assertThat(strings).containsExactly("hello", "world", "from", "smallrye", "reactive", "messaging");
    }
}


text:
package main

import (
	"flag"
	"os"
	"time"

	"github.com/golang/glog"
	"github.com/mishudark/eventhus/examples/bank"
	"github.com/mishudark/eventhus/utils"
)

func main() {
	flag.Parse()

	commandBus, err := getConfig()
	if err != nil {
		glog.Infoln(err)
		os.Exit(1)
	}

	end := make(chan bool)

	//Create Account
	for i := 0; i < 3; i++ {
		go func() {
			uuid, err := utils.UUID()
			if err != nil {
				return
			}

			//1) Create an account
			var account bank.CreateAccount
			account.AggregateID = uuid
			account.Owner = "mishudark"

			commandBus.HandleCommand(account)
			glog.Infof("account %s - account created", uuid)

			//2) Perform a deposit
			time.Sleep(time.Millisecond * 100)
			deposit := bank.PerformDeposit{
				Amount: 300,
			}

			deposit.AggregateID = uuid
			deposit.Version = 1

			commandBus.HandleCommand(deposit)
			glog.Infof("account %s - deposit performed", uuid)

			//3) Perform a withdrawl
			time.Sleep(time.Millisecond * 100)
			withdrawl := bank.PerformWithdrawal{
				Amount: 249,
			}

			withdrawl.AggregateID = uuid
			withdrawl.Version = 2

			commandBus.HandleCommand(withdrawl)
			glog.Infof("account %s - withdrawl performed", uuid)
		}()
	}
	<-end
}


text:
(function() {

	"use strict";

	var test = require('tap').test,
		NetEmitter;

	test('Load System Under Test', function(t) {
		NetEmitter = require('../lib/net-emitter');

		t.ok(NetEmitter, 'Module NetEmitter loaded');
		t.end();
	});

	test('', function(t) {
		t.skip('Need to implement tests for the createServer API');
		t.end();
	});
})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
First install the H2 driver using:
> install -s mvn:com.h2database/h2/1.3.163

Then copy this file to the deploy folder
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

  <bean id="dataSource" class="org.h2.jdbcx.JdbcDataSource">
      <property name="URL" value="jdbc:h2:~/test"/>
      <property name="user" value="sa"/>
      <property name="password" value=""/>
  </bean>

  <service interface="javax.sql.DataSource" ref="dataSource">
    <service-properties>
            <entry key="osgi.jndi.service.name" value="jdbc/h2ds"/>
    </service-properties>
  </service>
</blueprint>


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Types;

// ReSharper disable once CheckNamespace
namespace Telegram.Bot.Requests
{
    /// <summary>
    /// A simple method for testing your bot's auth token.
    /// </summary>
    [JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
    public class GetMeRequest : ParameterlessRequest<User>
    {
        /// <summary>
        /// Initializes a new request
        /// </summary>
        public GetMeRequest()
            : base("getMe")
        { }
    }
}


text:
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Drug } from './../drug';
import { DrugConsumableService } from './../../../services/drug-consumable.services';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-drug-consumable-edit',
  moduleId: module.id,
  templateUrl: './drug-consumable-edit.component.html',
  styleUrls: ['./drug-consumable-edit.component.css'],
  providers: [DrugConsumableService]
})
export class DrugConsumableEditComponent implements OnInit {

  id:number;
  drug: Drug = new Drug(0, "", "", "", 0, "", "");

  constructor(private router: Router, private route: ActivatedRoute, private drugService: DrugConsumableService) { }

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      this.id = +params['id'];
      this.drugService.getDrugConsumable(this.id).then((drug: Drug) => {
        this.drug = drug;
      })
    });
  }

  editDrug(drug: Drug) {
    this.drugService.updateDrug(drug).then((data) => {
      if(data.success) {
        alert("implement with backend");
        this.router.navigate(['drug-consumables', this.id]);
      }
    })
  }

}


text:
package org.wso2.carbon.core.services.callback;

/**
 * LoginSubscriptionManager, allows components
 * to subscribe a callback to be called when a user login happen
 */
public interface LoginSubscriptionManagerService {
    void subscribe(LoginListener listener);
}


text:
#ifndef _BOOST_UBLAS_NUMERICTYPE_DEDUCTION_
#define _BOOST_UBLAS_NUMERICTYPE_DEDUCTION_

// See original in boost-sandbox/boost/utility/type_deduction.hpp for comments

#include <boost/mpl/vector/vector20.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>

namespace boost { namespace numeric { namespace ublas {

struct error_cant_deduce_type {};

  namespace type_deduction_detail
  {
    typedef char(&bool_value_type)[1];
    typedef char(&float_value_type)[2];
    typedef char(&double_value_type)[3];
    typedef char(&long_double_value_type)[4];
    typedef char(&char_value_type)[5];
    typedef char(&schar_value_type)[6];
    typedef char(&uchar_value_type)[7];
    typedef char(&short_value_type)[8];
    typedef char(&ushort_value_type)[9];
    typedef char(&int_value_type)[10];
    typedef char(&uint_value_type)[11];
    typedef char(&long_value_type)[12];
    typedef char(&ulong_value_type)[13];

    typedef char(&x_value_type)[14];
    typedef char(&y_value_type)[15];

    typedef char(&cant_deduce_type)[16];

    template <typename T, typename PlainT = typename remove_cv<T>::type>
    struct is_basic
        : mpl::or_<
          typename mpl::or_<
              is_same<PlainT, bool>
            , is_same<PlainT, float>
            , is_same<PlainT, double>
            , is_same<PlainT, long double>
          > ::type,
          typename mpl::or_<
              is_same<PlainT, char>
            , is_same<PlainT, signed char>
            , is_same<PlainT, unsigned char>
            , is_same<PlainT, short>
            , is_same<PlainT, unsigned short>
            > ::type,
          typename mpl::or_<
              is_same<PlainT, int>
            , is_same<PlainT, unsigned int>
            , is_same<PlainT, long>
            , is_same<PlainT, unsigned long>
            > ::type
        > {};

    struct asymmetric;

    template <typename X, typename Y>
    cant_deduce_type
    test(...); // The black hole !!!

    template <typename X, typename Y>
    bool_value_type
    test(bool const&);

    template <typename X, typename Y>
    float_value_type
    test(float const&);

    template <typename X, typename Y>
    double_value_type
    test(double const&);

    template <typename X, typename Y>
    long_double_value_type
    test(long double const&);

    template <typename X, typename Y>
    char_value_type
    test(char const&);

    template <typename X, typename Y>
    schar_value_type
    test(signed char const&);

    template <typename X, typename Y>
    uchar_value_type
    test(unsigned char const&);

    template <typename X, typename Y>
    short_value_type
    test(short const&);

    template <typename X, typename Y>
    ushort_value_type
    test(unsigned short const&);

    template <typename X, typename Y>
    int_value_type
    test(int const&);

    template <typename X, typename Y>
    uint_value_type
    test(unsigned int const&);

    template <typename X, typename Y>
    long_value_type
    test(long const&);

    template <typename X, typename Y>
    ulong_value_type
    test(unsigned long const&);

    template <typename X, typename Y>
    typename boost::disable_if<
        is_basic<X>, x_value_type
    >::type
    test(X const&);

    template <typename X, typename Y>
    typename boost::disable_if<
        mpl::or_<
            is_basic<Y>
          , is_same<Y, asymmetric>
          , is_same<const X, const Y>
        >
      , y_value_type
    >::type
    test(Y const&);

    template <typename X, typename Y>
    struct base_result_of
    {
        typedef typename remove_cv<X>::type x_type;
        typedef typename remove_cv<Y>::type y_type;

        typedef mpl::vector16<
            mpl::identity<bool>
          , mpl::identity<float>
          , mpl::identity<double>
          , mpl::identity<long double>
          , mpl::identity<char>
          , mpl::identity<signed char>
          , mpl::identity<unsigned char>
          , mpl::identity<short>
          , mpl::identity<unsigned short>
          , mpl::identity<int>
          , mpl::identity<unsigned int>
          , mpl::identity<long>
          , mpl::identity<unsigned long>
          , mpl::identity<x_type>
          , mpl::identity<y_type>
          , mpl::identity<error_cant_deduce_type>
        >
        types;
    };

}}} } // namespace boost::numeric::ublas ::type_deduction_detail

#endif


text:
goog.module('jscomp.runtime_tests.polyfill_tests.object_setprototypeof_test');
goog.setTestOnly();

const testSuite = goog.require('goog.testing.testSuite');
const userAgent = goog.require('goog.userAgent');

/** @type {boolean} */
const LEGACY = userAgent.IE && !userAgent.isVersionOrHigher(11);

testSuite({
  shouldRunTests() {
    // Not polyfilled to ES3
    return !userAgent.IE || userAgent.isVersionOrHigher(9);
  },

  testSetPrototypeOf_modern() {
    if (LEGACY) return;

    const obj = {};
    const sub = {};
    Object.setPrototypeOf(sub, obj);
    obj.x = 23;
    assertObjectEquals({x: 23}, sub);
  },

  testSetPrototypeOf_legacy() {
    if (!LEGACY) return;
    assertFalse('setPrototypeOf' in Object);
  }
});


text:
<?php
class Kwc_Guestbook_ActivatePost_Component extends Kwc_Form_Success_Component
{
    protected $_newVisibleValue = 1;

    public static function getSettings($param = null)
    {
        $ret = parent::getSettings($param);
        $ret['placeholder']['success'] = trlKwfStatic('The entry in your guestbook has been acitvated.');
        $ret['placeholder']['toGuestbook'] = trlKwfStatic('Use this link to get to your guestbook:');
        $ret['flags']['processInput'] = true;
        $ret['flags']['passMailRecipient'] = true;
        return $ret;
    }

    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer)
    {
        $ret = parent::getTemplateVars($renderer);
        $ret['guestbookComponent'] = $this->getData()->parent;
        return $ret;
    }

    public function processInput(array $postData)
    {
        if (!isset($postData['recipient']) || !isset($postData['post_id'])) {
            throw new Kwf_Exception_NotFound();
        }
        $recipient = Kwc_Mail_Redirect_Component::parseRecipientParam($postData['recipient']); //do nothing with recipient, just make sure it is a valid one

        $post = explode('.', $postData['post_id']);
        $postId = $post[0];
        if (Kwf_Util_Hash::hash($postId) != $post[1]) {
            throw new Kwf_Exception_AccessDenied();
        }

        $model = $this->getData()->parent->getComponent()->getChildModel();
        $postRow = $model->getRow($postId);
        if (!$postRow) {
            throw new Kwf_ClientException(trlKwf("This post does not exist anymore."));
        }

        $postRow->visible = $this->_newVisibleValue;
        $postRow->save();
    }
}


text:
/**
 * Check if a value is defined
 * @ignore
 * @param {*} value
 * @return {boolean}
 */
export default function isDefined(value) {
  return value !== undefined && value !== null;
}


text:
package org.omg.CosTransactions;

/**
* org/omg/CosTransactions/TransactionFactoryOperations.java .
* Error reading Messages File.
* Error reading Messages File.
* Thursday, January 14, 2010 1:08:59 AM PST
*/

public interface TransactionFactoryOperations
{
  org.omg.CosTransactions.Control create (int time_out);
  org.omg.CosTransactions.Control recreate (org.omg.CosTransactions.PropagationContext ctx);
} // interface TransactionFactoryOperations


text:
package com.yammer.metrics.stats;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import static java.lang.Math.exp;

/**
 * An exponentially-weighted moving average.
 *
 * @see UNIX Load Average Part 1: How
 *      It Works
 * @see UNIX Load Average Part 2: Not
 *      Your Average Average
 */
public class EWMA {
    private static final int INTERVAL = 5;
    private static final double SECONDS_PER_MINUTE = 60.0;
    private static final int ONE_MINUTE = 1;
    private static final int FIVE_MINUTES = 5;
    private static final int FIFTEEN_MINUTES = 15;
    private static final double M1_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / ONE_MINUTE);
    private static final double M5_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIVE_MINUTES);
    private static final double M15_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIFTEEN_MINUTES);

    private volatile boolean initialized = false;
    private volatile double rate = 0.0;

    private final AtomicLong uncounted = new AtomicLong();
    private final double alpha, interval;

    /**
     * Creates a new EWMA which is equivalent to the UNIX one minute load average and which expects
     * to be ticked every 5 seconds.
     *
     * @return a one-minute EWMA
     */
    public static EWMA oneMinuteEWMA() {
        return new EWMA(M1_ALPHA, INTERVAL, TimeUnit.SECONDS);
    }

    /**
     * Creates a new EWMA which is equivalent to the UNIX five minute load average and which expects
     * to be ticked every 5 seconds.
     *
     * @return a five-minute EWMA
     */
    public static EWMA fiveMinuteEWMA() {
        return new EWMA(M5_ALPHA, INTERVAL, TimeUnit.SECONDS);
    }

    /**
     * Creates a new EWMA which is equivalent to the UNIX fifteen minute load average and which
     * expects to be ticked every 5 seconds.
     *
     * @return a fifteen-minute EWMA
     */
    public static EWMA fifteenMinuteEWMA() {
        return new EWMA(M15_ALPHA, INTERVAL, TimeUnit.SECONDS);
    }

    /**
     * Create a new EWMA with a specific smoothing constant.
     *
     * @param alpha        the smoothing constant
     * @param interval     the expected tick interval
     * @param intervalUnit the time unit of the tick interval
     */
    public EWMA(double alpha, long interval, TimeUnit intervalUnit) {
        this.interval = intervalUnit.toNanos(interval);
        this.alpha = alpha;
    }

    /**
     * Update the moving average with a new value.
     *
     * @param n the new value
     */
    public void update(long n) {
        uncounted.addAndGet(n);
    }

    /**
     * Mark the passage of time and decay the current rate accordingly.
     */
    public void tick() {
        final long count = uncounted.getAndSet(0);
        final double instantRate = count / interval;
        if (initialized) {
            rate += (alpha * (instantRate - rate));
        } else {
            rate = instantRate;
            initialized = true;
        }
    }

    /**
     * Returns the rate in the given units of time.
     *
     * @param rateUnit the unit of time
     * @return the rate
     */
    public double rate(TimeUnit rateUnit) {
        return rate * (double) rateUnit.toNanos(1);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
S-Index
</TITLE>

<META NAME="date" CONTENT="2013-05-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E G I L N O R S T W

S

sendData(String) -
Method in class com.ees.bluetooth.BTFacade

Send data.

setState(int) -
Method in class com.ees.bluetooth.ConnectionManager

start() -
Method in class com.ees.bluetooth.ConnectionManager

Starts channel listener.

startDiscovery() -
Method in class com.ees.bluetooth.BTFacade

Start discovery.

startServer() -
Method in class com.ees.bluetooth.BTFacade

Start server.

stopDiscovery() -
Method in class com.ees.bluetooth.BTFacade

Stop discovery.

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E G I L N O R S T W


text:
package stuff

func PublicString() string {
	return "public string"
}

func privateString() string {
	return "no one will see this"
}


text:
using System;
using System.IO;
using System.Web.Hosting;

namespace ImageResizer.FluentExtensions
{
    public static class PathUtils
    {
        /// <summary>
        /// Modifies the <paramref name="imagePath"/> with the specified <paramref name="prefix"/> and <paramref name="container"/> name.
        /// </summary>
        /// <param name="imagePath">The image path to modify</param>
        /// <param name="prefix">The prefix you would like to append to the path</param>
        /// <param name="container">The (optional) container (root directory) name</param>
        /// <exception cref="System.ArgumentNullException">If the <paramref name="imagePath"/> or <paramref name="prefix"/> are null or empty.</exception>
        public static string ModifyPath(string imagePath, string prefix, string container = null)
        {
            if (string.IsNullOrEmpty(imagePath))
                throw new ArgumentNullException("imagePath");

            if (string.IsNullOrEmpty(prefix))
                throw new ArgumentNullException("imagePath");

            prefix = Path.Combine(prefix, container ?? string.Empty);
            var fixedPath = Path.Combine(GetAppVirtualPath(), prefix, imagePath.TrimStart('/', '\\', '~'));

            return fixedPath.Replace('\\', '/');
        }

        public static string GetAppVirtualPath()
        {
            return HostingEnvironment.ApplicationVirtualPath ?? "/";
        }
    }
}


text:
/**************************************************************************************************
 *   File:     KitchenInventoryActivity.java
 *   Author:   Abigail Jones, Lauren Sullivan, Evan Heydemann
 *   Date:     10/28/15
 *   Class:    Capstone/Software Engineering
 *   Project:  PaperOrPlastic Application
 *   Purpose:  This activity will be the activity that is opened when the user selects the
 *             kitchen inventory button from the continue activity
 ***************************************************************************************************/

package edu.pacificu.cs493f15_1.paperorplasticapp.kitchenInventory;

import android.os.Bundle;

import edu.pacificu.cs493f15_1.paperorplasticapp.popList.PoPListActivity;
import edu.pacificu.cs493f15_1.paperorplasticapp.R;
import edu.pacificu.cs493f15_1.paperorplasticjava.KitchenInventories;

/***************************************************************************************************
 *   Class:         KitchenInventoryActivity
 *   Description:   Creates KitchenInventoryActivity class that controls what occurs when the user
 *                  selects the kitchen inventory option from the continue activity. Specifically
 *                  contains the list functionality.
 *   Parameters:    N/A
 *   Returned:      N/A
 **************************************************************************************************/
public class KitchenInventoryActivity  extends PoPListActivity {

    /********************************************************************************************
     * Function name: onCreate
     * Description:   Initializes all needed setup for objects in page
     * Parameters:    savedInstanceState  - a bundle object
     * Returns:       none
     ******************************************************************************************/
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        PoPOnCreate(savedInstanceState, new KitchenInventories(), R.layout.activity_lists,
         KitchenInventories.KITCHEN_FILE_NAME, false);
    }

}


text:
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// Demux API.
// Enables extraction of image and extended format data from WebP files.

// Code Example: Demuxing WebP data to extract all the frames, ICC profile
// and EXIF/XMP metadata.
/*
  WebPDemuxer* demux = WebPDemux(&webp_data);

  uint32_t width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH);
  uint32_t height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT);
  // ... (Get information about the features present in the WebP file).
  uint32_t flags = WebPDemuxGetI(demux, WEBP_FF_FORMAT_FLAGS);

  // ... (Iterate over all frames).
  WebPIterator iter;
  if (WebPDemuxGetFrame(demux, 1, &iter)) {
    do {
      // ... (Consume 'iter'; e.g. Decode 'iter.fragment' with WebPDecode(),
      // ... and get other frame properties like width, height, offsets etc.
      // ... see 'struct WebPIterator' below for more info).
    } while (WebPDemuxNextFrame(&iter));
    WebPDemuxReleaseIterator(&iter);
  }

  // ... (Extract metadata).
  WebPChunkIterator chunk_iter;
  if (flags & ICCP_FLAG) WebPDemuxGetChunk(demux, "ICCP", 1, &chunk_iter);
  // ... (Consume the ICC profile in 'chunk_iter.chunk').
  WebPDemuxReleaseChunkIterator(&chunk_iter);
  if (flags & EXIF_FLAG) WebPDemuxGetChunk(demux, "EXIF", 1, &chunk_iter);
  // ... (Consume the EXIF metadata in 'chunk_iter.chunk').
  WebPDemuxReleaseChunkIterator(&chunk_iter);
  if (flags & XMP_FLAG) WebPDemuxGetChunk(demux, "XMP ", 1, &chunk_iter);
  // ... (Consume the XMP metadata in 'chunk_iter.chunk').
  WebPDemuxReleaseChunkIterator(&chunk_iter);
  WebPDemuxDelete(demux);
*/

#ifndef WEBP_WEBP_DEMUX_H_
#define WEBP_WEBP_DEMUX_H_

#include "./mux_types.h"

#ifdef __cplusplus
extern "C" {
#endif

#define WEBP_DEMUX_ABI_VERSION 0x0102    // MAJOR(8b) + MINOR(8b)

// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
// typedef enum WebPDemuxState WebPDemuxState;
// typedef enum WebPFormatFeature WebPFormatFeature;
typedef struct WebPDemuxer WebPDemuxer;
typedef struct WebPIterator WebPIterator;
typedef struct WebPChunkIterator WebPChunkIterator;
typedef struct WebPAnimInfo WebPAnimInfo;

//------------------------------------------------------------------------------

// Returns the version number of the demux library, packed in hexadecimal using
// 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507.
WEBP_EXTERN(int) WebPGetDemuxVersion(void);

//------------------------------------------------------------------------------
// Life of a Demux object

typedef enum WebPDemuxState {
  WEBP_DEMUX_PARSE_ERROR    = -1,  // An error occurred while parsing.
  WEBP_DEMUX_PARSING_HEADER =  0,  // Not enough data to parse full header.
  WEBP_DEMUX_PARSED_HEADER  =  1,  // Header parsing complete,
                                   // data may be available.
  WEBP_DEMUX_DONE           =  2   // Entire file has been parsed.
} WebPDemuxState;

// Internal, version-checked, entry point
WEBP_EXTERN(WebPDemuxer*) WebPDemuxInternal(
    const WebPData*, int, WebPDemuxState*, int);

// Parses the full WebP file given by 'data'.
// Returns a WebPDemuxer object on successful parse, NULL otherwise.
static WEBP_INLINE WebPDemuxer* WebPDemux(const WebPData* data) {
  return WebPDemuxInternal(data, 0, NULL, WEBP_DEMUX_ABI_VERSION);
}

// Parses the possibly incomplete WebP file given by 'data'.
// If 'state' is non-NULL it will be set to indicate the status of the demuxer.
// Returns NULL in case of error or if there isn't enough data to start parsing;
// and a WebPDemuxer object on successful parse.
// Note that WebPDemuxer keeps internal pointers to 'data' memory segment.
// If this data is volatile, the demuxer object should be deleted (by calling
// WebPDemuxDelete()) and WebPDemuxPartial() called again on the new data.
// This is usually an inexpensive operation.
static WEBP_INLINE WebPDemuxer* WebPDemuxPartial(
    const WebPData* data, WebPDemuxState* state) {
  return WebPDemuxInternal(data, 1, state, WEBP_DEMUX_ABI_VERSION);
}

// Frees memory associated with 'dmux'.
WEBP_EXTERN(void) WebPDemuxDelete(WebPDemuxer* dmux);

//------------------------------------------------------------------------------
// Data/information extraction.

typedef enum WebPFormatFeature {
  WEBP_FF_FORMAT_FLAGS,  // Extended format flags present in the 'VP8X' chunk.
  WEBP_FF_CANVAS_WIDTH,
  WEBP_FF_CANVAS_HEIGHT,
  WEBP_FF_LOOP_COUNT,
  WEBP_FF_BACKGROUND_COLOR,
  WEBP_FF_FRAME_COUNT    // Number of frames present in the demux object.
                         // In case of a partial demux, this is the number of
                         // frames seen so far, with the last frame possibly
                         // being partial.
} WebPFormatFeature;

// Get the 'feature' value from the 'dmux'.
// NOTE: values are only valid if WebPDemux() was used or WebPDemuxPartial()
// returned a state > WEBP_DEMUX_PARSING_HEADER.
WEBP_EXTERN(uint32_t) WebPDemuxGetI(
    const WebPDemuxer* dmux, WebPFormatFeature feature);

//------------------------------------------------------------------------------
// Frame iteration.

struct WebPIterator {
  int frame_num;
  int num_frames;          // equivalent to WEBP_FF_FRAME_COUNT.
  int fragment_num;
  int num_fragments;
  int x_offset, y_offset;  // offset relative to the canvas.
  int width, height;       // dimensions of this frame or fragment.
  int duration;            // display duration in milliseconds.
  WebPMuxAnimDispose dispose_method;  // dispose method for the frame.
  int complete;   // true if 'fragment' contains a full frame. partial images
                  // may still be decoded with the WebP incremental decoder.
  WebPData fragment;  // The frame or fragment given by 'frame_num' and
                      // 'fragment_num'.
  int has_alpha;      // True if the frame or fragment contains transparency.
  WebPMuxAnimBlend blend_method;  // Blend operation for the frame.

  uint32_t pad[2];         // padding for later use.
  void* private_;          // for internal use only.
};

// Retrieves frame 'frame_number' from 'dmux'.
// 'iter->fragment' points to the first fragment on return from this function.
// Individual fragments may be extracted using WebPDemuxSelectFragment().
// Setting 'frame_number' equal to 0 will return the last frame of the image.
// Returns false if 'dmux' is NULL or frame 'frame_number' is not present.
// Call WebPDemuxReleaseIterator() when use of the iterator is complete.
// NOTE: 'dmux' must persist for the lifetime of 'iter'.
WEBP_EXTERN(int) WebPDemuxGetFrame(
    const WebPDemuxer* dmux, int frame_number, WebPIterator* iter);

// Sets 'iter->fragment' to point to the next ('iter->frame_num' + 1) or
// previous ('iter->frame_num' - 1) frame. These functions do not loop.
// Returns true on success, false otherwise.
WEBP_EXTERN(int) WebPDemuxNextFrame(WebPIterator* iter);
WEBP_EXTERN(int) WebPDemuxPrevFrame(WebPIterator* iter);

// Sets 'iter->fragment' to reflect fragment number 'fragment_num'.
// Returns true if fragment 'fragment_num' is present, false otherwise.
WEBP_EXTERN(int) WebPDemuxSelectFragment(WebPIterator* iter, int fragment_num);

// Releases any memory associated with 'iter'.
// Must be called before any subsequent calls to WebPDemuxGetChunk() on the same
// iter. Also, must be called before destroying the associated WebPDemuxer with
// WebPDemuxDelete().
WEBP_EXTERN(void) WebPDemuxReleaseIterator(WebPIterator* iter);

//------------------------------------------------------------------------------
// Chunk iteration.

struct WebPChunkIterator {
  // The current and total number of chunks with the fourcc given to
  // WebPDemuxGetChunk().
  int chunk_num;
  int num_chunks;
  WebPData chunk;    // The payload of the chunk.

  uint32_t pad[6];   // padding for later use
  void* private_;
};

// Retrieves the 'chunk_number' instance of the chunk with id 'fourcc' from
// 'dmux'.
// 'fourcc' is a character array containing the fourcc of the chunk to return,
// e.g., "ICCP", "XMP ", "EXIF", etc.
// Setting 'chunk_number' equal to 0 will return the last chunk in a set.
// Returns true if the chunk is found, false otherwise. Image related chunk
// payloads are accessed through WebPDemuxGetFrame() and related functions.
// Call WebPDemuxReleaseChunkIterator() when use of the iterator is complete.
// NOTE: 'dmux' must persist for the lifetime of the iterator.
WEBP_EXTERN(int) WebPDemuxGetChunk(const WebPDemuxer* dmux,
                                   const char fourcc[4], int chunk_number,
                                   WebPChunkIterator* iter);

// Sets 'iter->chunk' to point to the next ('iter->chunk_num' + 1) or previous
// ('iter->chunk_num' - 1) chunk. These functions do not loop.
// Returns true on success, false otherwise.
WEBP_EXTERN(int) WebPDemuxNextChunk(WebPChunkIterator* iter);
WEBP_EXTERN(int) WebPDemuxPrevChunk(WebPChunkIterator* iter);

// Releases any memory associated with 'iter'.
// Must be called before destroying the associated WebPDemuxer with
// WebPDemuxDelete().
WEBP_EXTERN(void) WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter);

//------------------------------------------------------------------------------
// WebPAnimDecoder API
//
// This API allows decoding (possibly) animated WebP images.
//
// Code Example:
/*
  WebPAnimDecoder* dec = WebPAnimDecoderNew(webp_data);
  WebPAnimInfo anim_info;
  WebPAnimDecoderGetInfo(dec, &anim_info);
  for (uint32_t i = 0; i < anim_info.loop_count; ++i) {
    while (WebPAnimDecoderHasMoreFrames(dec)) {
      uint8_t* frame_rgba;
      int timestamp;
      WebPAnimDecoderGetNext(dec, &frame_rgba, &timestamp);
      // ... (Render 'frame_rgba' based on 'timestamp').
    }
    WebPAnimDecoderReset(dec);
  }
  WebPAnimDecoderDelete(dec);
*/

typedef struct WebPAnimDecoder WebPAnimDecoder;  // Main opaque object.

// Internal, version-checked, entry point.
WEBP_EXTERN(WebPAnimDecoder*) WebPAnimDecoderNewInternal(const WebPData*, int);

// Creates and initializes a WebPAnimDecoder object.
// Parameters:
//   webp_data - (in) WebP bitstream. This should remain unchanged during the
//                    lifetime of the output WebPAnimDecoder object.
// Returns:
//   A pointer to the newly created WebPAnimDecoder object, or NULL in case of
//   parsing/memory error.
static WEBP_INLINE WebPAnimDecoder* WebPAnimDecoderNew(
    const WebPData* webp_data) {
  return WebPAnimDecoderNewInternal(webp_data, WEBP_DEMUX_ABI_VERSION);
}

// Global information about the animation..
struct WebPAnimInfo {
  uint32_t canvas_width;
  uint32_t canvas_height;
  uint32_t loop_count;
  uint32_t bgcolor;
  uint32_t frame_count;
  uint32_t pad[4];   // padding for later use
};

// Get global information about the animation.
// Parameters:
//   dec - (in) decoder instance to get information from.
//   info - (out) global information fetched from the animation.
// Returns:
//   True on success.
WEBP_EXTERN(int) WebPAnimDecoderGetInfo(const WebPAnimDecoder* dec,
                                        WebPAnimInfo* info);

// Fetch the next frame from 'dec' in RGBA format. This will be a fully
// reconstructed canvas of size 'canvas_width * 4 * canvas_height', and not just
// the frame sub-rectangle.
// The returned 'rgba' buffer is valid only until the next call to
// WebPAnimDecoderGetNext(), WebPAnimDecoderReset() or WebPAnimDecoderDelete().
// Parameters:
//   dec - (in/out) decoder instance from which the next frame is to be fetched.
//   rgba - (out) decoded frame in RGBA format.
//   timestamp - (out) timestamp of the frame in milliseconds.
// Returns:
//   False if any of the arguments are NULL, or if there is a parsing or
//   decoding error, or if there are no more frames. Otherwise, returns true.
WEBP_EXTERN(int) WebPAnimDecoderGetNext(WebPAnimDecoder* dec,
                                        uint8_t** rgba, int* timestamp);

// Check if there are more frames left to decode.
// Parameters:
//   dec - (in) decoder instance to be checked.
// Returns:
//   True if 'dec' is not NULL and some frames are yet to be decoded.
//   Otherwise, returns false.
WEBP_EXTERN(int) WebPAnimDecoderHasMoreFrames(const WebPAnimDecoder* dec);

// Resets the WebPAnimDecoder object, so that next call to
// WebPAnimDecoderGetNext() will restart decoding from 1st frame. This would be
// helpful when all frames need to be decoded multiple times (e.g.
// info.loop_count times) without destroying and recreating the 'dec' object.
// Parameters:
//   dec - (in/out) decoder instance to be reset
WEBP_EXTERN(void) WebPAnimDecoderReset(WebPAnimDecoder* dec);

// Deletes the WebPAnimDecoder object.
// Parameters:
//   dec - (in/out) decoder instance to be deleted
WEBP_EXTERN(void) WebPAnimDecoderDelete(WebPAnimDecoder* dec);

#ifdef __cplusplus
}    // extern "C"
#endif

#endif  /* WEBP_WEBP_DEMUX_H_ */


text:
module Jekyll
  module Converters
    class AsciiDocConverter < Converter
      safe true

      highlighter_prefix "\n"
      highlighter_suffix "\n"

      def initialize(config)
        @config = config
        @config['asciidoc'] ||= 'asciidoctor'
        @config['asciidoc_ext'] ||= 'asciidoc,adoc,ad'
        @asciidoctor_config = (@config['asciidoctor'] ||= {})
        # convert keys to symbols
        @asciidoctor_config.keys.each do |key|
          @asciidoctor_config[key.to_sym] = @asciidoctor_config.delete(key)
        end
        @asciidoctor_config[:safe] ||= 'safe'
        user_defined_attributes = @asciidoctor_config[:attributes]
        @asciidoctor_config[:attributes] = %w(notitle hardbreaks idprefix= idseparator=- linkattrs)
        unless user_defined_attributes.nil?
          @asciidoctor_config[:attributes].concat(user_defined_attributes)
        end
        @asciidoctor_config[:attributes].push('env-jekyll')
      end

      def setup
        return if @setup
        case @config['asciidoc']
          when 'asciidoctor'
            begin
              require 'asciidoctor'
              @setup = true
            rescue LoadError
              STDERR.puts 'You are missing a library required to convert AsciiDoc files. Please run:'
              STDERR.puts '  $ [sudo] gem install asciidoctor'
              raise FatalException.new("Missing dependency: asciidoctor")
            end
          else
            STDERR.puts "Invalid AsciiDoc processor: #{@config['asciidoc']}"
            STDERR.puts "  Valid options are [ asciidoctor ]"
            raise FatalException.new("Invalid AsciiDoc process: #{@config['asciidoc']}")
        end
        @setup = true
      end

      def matches(ext)
        rgx = "\.(#{@config['asciidoc_ext'].tr ',', '|'})$"
        ext =~ Regexp.new(rgx, Regexp::IGNORECASE)
      end

      def output_ext(ext)
        '.html'
      end

      def convert(content)
        setup
        case @config['asciidoc']
        when 'asciidoctor'
          Asciidoctor.render(content, @config['asciidoctor'])
        else
          warn 'Unknown AsciiDoc converter. Passing through raw content.'
          content
        end
      end

      def load(content)
        setup
        case @config['asciidoc']
        when 'asciidoctor'
          Asciidoctor.load(content, :parse_header_only => true)
        else
          warn 'Unknown AsciiDoc converter. Cannot load document header.'
          nil
        end
      end
    end
  end

  module Generators
    # Promotes select AsciiDoc attributes to Jekyll front matter
    class AsciiDocPreprocessor < Generator
      def generate(site)
        asciidoc_converter = site.getConverterImpl(Jekyll::Converters::AsciiDocConverter)
        asciidoc_converter.setup
        key_prefix = (site.config['asciidoc_key_prefix'] || 'jekyll-')
        key_prefix_len = key_prefix.length
        site.pages.each do |page|
          if asciidoc_converter.matches(page.ext)
            doc = asciidoc_converter.load(page.content)
            next if doc.nil?

            page.data['title'] ||= doc.doctitle
            page.data['author'] = doc.author unless doc.author.nil?

            doc.attributes.each do |key, val|
              if key.start_with?(key_prefix)
                page.data[key[key_prefix_len..-1]] ||= val
              end
            end

            unless page.data.has_key? 'layout'
              if doc.attr? 'page-layout'
                page.data['layout'] ||= doc.attr 'page-layout'
              else
                page.data['layout'] ||= 'default'
              end
            end
          end
        end
        site.posts.each do |post|
          if asciidoc_converter.matches(post.ext)
            doc = asciidoc_converter.load(post.content)
            next if doc.nil?

            post.data['title'] ||= doc.doctitle
            post.data['author'] = doc.author unless doc.author.nil?
            # TODO carry over date
            # setting categories doesn't work here, we lose the post
            #post.data['categories'] ||= (doc.attr 'categories') if (doc.attr? 'categories')

            doc.attributes.each do |key, val|
              if key.start_with?(key_prefix)
                post.data[key[key_prefix_len..-1]] ||= val
              end
            end

            unless post.data.has_key? 'layout'
              if doc.attr? 'page-layout'
                post.data['layout'] ||= doc.attr 'page-layout'
              else
                post.data['layout'] ||= 'post'
              end
            end
          end
        end
      end
    end
  end

  module Filters
    # Convert an AsciiDoc string into HTML output.
    #
    # input - The AsciiDoc String to convert.
    #
    # Returns the HTML formatted String.
    def asciidocify(input)
      site = @context.registers[:site]
      converter = site.getConverterImpl(Jekyll::Converters::AsciiDocConverter)
      converter.convert(input)
    end
  end
end


text:
+++
draft = false
image = "https://i.ytimg.com/vi_webp/-dG-LJHxkAY/maxresdefault.webp"
showonlyimage = false
date = "2017-08-25T20:22:08"
title = "Le TestNET ou comment expérimenter avant de publier"
weight = 38
steem = "fr/@roxane/le-testnet-ou-comment-experimenter-avant-de-publier"
+++

<!--more-->


text:
package com.chhuang.novel.data.articles;

import com.android.volley.Request;
import com.android.volley.Response;
import com.chhuang.novel.data.Article;
import com.chhuang.novel.data.GBKRequest;
import com.google.inject.Singleton;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Date: 2014/6/5
 * Time: 22:26
 *
 * @author chhuang@microsoft.com
 */
public class BenghuaiNovel implements INovel {
    public static final  Pattern ARTICLE_HREF_PATTERN = Pattern.compile("/5_5133/(\\d+).html",
                                                                        Pattern.CASE_INSENSITIVE);
    private static final String BASE_URL = "http://www.biquge.com/5_5133/";
    private final static String TAG      = BenghuaiNovel.class.getName();
    private final static INovelRequestFactory factory = new INovelRequestFactory() {
        @Override
        public Request<String> create(
                String url, Response.Listener<String> responseListener, Response.ErrorListener errorListener) {
            return new GBKRequest(url, responseListener, errorListener);
        }
    };

    @Override
    public String getBaseUrl() {
        return BASE_URL;
    }

    @Override
    public String toString() {
        return getBookName();
    }

    @Override
    public String getBookName() {
        return "崩坏世界的传奇大冒险";
    }

    @Override
    public INovelRequestFactory getFactory() {
        return factory;
    }

    @Override
    public ArrayList<Article> parseHomePageToArticles(String response) {
        ArrayList<Article> articles = new ArrayList<Article>();
        Document document = Jsoup.parse(response);
        Elements dds = document.select("dd").select("a");
        for (Element a : dds) {
            String href = a.attr("href");
            Matcher matcher = ARTICLE_HREF_PATTERN.matcher(href);
            if (matcher.matches()) {
                int id = Integer.parseInt(matcher.group(1));
                String title = a.text();
                String url = BASE_URL + id + ".html";
                Article article = new Article(id, title, url);
                article.setBookName(getBookName());
                articles.add(article);
            }
        }
        return articles;
    }

    @Override
    public String parseArticle(String response) {
        Document document = Jsoup.parse(response);
        Element content = document.select("div#content").first();
        StringBuilder buffer = new StringBuilder();
        for (TextNode p : content.textNodes()) {
            buffer.append(p.getWholeText()).append("\r\n");
        }
        return buffer.toString();
    }
}


text:
//
//  LQSHuiFuPingLunViewController.m
//  myOrgForum
//
//  Created by bhsj_imac on 2017/3/22.
//  Copyright © 2017年 SkyAndSea. All rights reserved.
//  左上角按钮为取消,右上角为发布。中间标题为回复。一个textview,placeholder为:说两句吧。。。,下面一栏为添加图片的按钮。再下面是显示所在位置。

#import "LQSHuiFuPingLunViewController.h"
#import "LQSTextView.h"
@interface LQSHuiFuPingLunViewController ()
@property (nonatomic,strong)UIButton *cancleBtn;
@property (nonatomic,strong)UIButton *sendBtn;
@property (nonatomic,strong)LQSTextView *saySomethingTV;
@property (nonatomic,strong)UIButton *addPicBtn;
@property (nonatomic,strong)UIButton *locateBtn;
@property (nonatomic,strong)UIScrollView *containerScrollView;
@end

@implementation LQSHuiFuPingLunViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupViews];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 布局左边的取消按钮
    self.cancleBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 40)];
    [self.cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancleBtn addTarget:self action:@selector(cancleReply:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:self.cancleBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    // 布局右边发布按钮
    self.sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 40)];
    [self.sendBtn setTitle:@"发布" forState:UIControlStateNormal];
    [self.sendBtn addTarget:self action:@selector(sendReply:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.sendBtn];
    self.navigationItem.rightBarButtonItem = rightItem;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - custom methods
- (void)setupViews{
    self.view.backgroundColor = [UIColor whiteColor];
        // 布局scrollView
    self.containerScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64)];
    self.containerScrollView.contentSize = CGSizeMake(0, kScreenHeight *1.2);
    self.containerScrollView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.containerScrollView];
    // 布局textview
    self.saySomethingTV = [[LQSTextView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 120)];
    self.saySomethingTV.backgroundColor = [UIColor whiteColor];
    self.saySomethingTV.placehoder = @"说两句吧...";
    [self.containerScrollView addSubview:self.saySomethingTV];
    // 布局添加照片按钮
    UIView *addPicContainerView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.saySomethingTV.frame)+5,kScreenWidth, 80)];
    addPicContainerView.backgroundColor = [UIColor whiteColor];
    [self.containerScrollView addSubview:addPicContainerView];
    self.addPicBtn = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 70, 70)];
    [self.addPicBtn setImage:[UIImage imageNamed:@"dz_publish_add_picture_n"] forState:UIControlStateNormal];
    [self.addPicBtn setImage:[UIImage imageNamed:@"dz_publish_add_picture_h"] forState:UIControlStateSelected];
    [addPicContainerView addSubview:self.addPicBtn];
    // 旁边的添加照片label
    UILabel *addPicLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.addPicBtn.frame)+5, 0, kScreenWidth - 100, 80)];
    addPicLabel.text = @"添加照片";
    [addPicContainerView addSubview:addPicLabel];

    // 定位按钮
    self.locateBtn = [[UIButton alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(addPicContainerView.frame)+10, 120, 50)];
    [self.containerScrollView addSubview:self.locateBtn];
    [self.locateBtn setImage:[UIImage imageNamed:@"dz_toolbar_reply_location_n"] forState:UIControlStateNormal];
    [self.locateBtn addTarget:self action:@selector(locateAct:) forControlEvents:UIControlEventTouchUpInside];

//    self.navigationItem.rightBarButtonItem =
}
- (void)locateAct:(UIButton *)sender{
    NSLog(@"定位按钮点击事件");
}
- (void)sendReply:(UIButton *)sender{
    NSLog(@"发布按钮的点击事件,在这里确定发送回复消息");
}
- (void)cancleReply:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
// This sub-API supports the following functionalities:
//
//  - Long-term speech and noise level metrics.
//  - Long-term echo metric statistics.
//  - Round Trip Time (RTT) statistics.
//  - Dead-or-Alive connection summary.
//  - Generation of call reports to text files.
//
// Usage example, omitting error checking:
//
//  using namespace webrtc;
//  VoiceEngine* voe = VoiceEngine::Create();
//  VoEBase* base = VoEBase::GetInterface(voe);
//  VoECallReport report = VoECallReport::GetInterface(voe);
//  base->Init();
//  LevelStatistics stats;
//  report->GetSpeechAndNoiseSummary(stats);
//  ...
//  base->Terminate();
//  base->Release();
//  report->Release();
//  VoiceEngine::Delete(voe);
//
#ifndef WEBRTC_VOICE_ENGINE_VOE_CALL_REPORT_H
#define WEBRTC_VOICE_ENGINE_VOE_CALL_REPORT_H

#include "webrtc/common_types.h"

namespace webrtc {

class VoiceEngine;

// VoECallReport
class WEBRTC_DLLEXPORT VoECallReport
{
public:
    // Factory for the VoECallReport sub-API. Increases an internal
    // reference counter if successful. Returns NULL if the API is not
    // supported or if construction fails.
    static VoECallReport* GetInterface(VoiceEngine* voiceEngine);

    // Releases the VoECallReport sub-API and decreases an internal
    // reference counter. Returns the new reference count. This value should
    // be zero for all sub-API:s before the VoiceEngine object can be safely
    // deleted.
    virtual int Release() = 0;

    // Performs a combined reset of all components involved in generating
    // the call report for a specified |channel|. Pass in -1 to reset
    // all channels.
    virtual int ResetCallReportStatistics(int channel) = 0;

    // Gets minimum, maximum and average levels for long-term echo metrics.
    virtual int GetEchoMetricSummary(EchoStatistics& stats) = 0;

    // Gets minimum, maximum and average levels for Round Trip Time (RTT)
    // measurements.
    virtual int GetRoundTripTimeSummary(int channel,
                                        StatVal& delaysMs) = 0;

    // Gets the total amount of dead and alive connection detections
    // during a VoIP session.
    virtual int GetDeadOrAliveSummary(int channel, int& numOfDeadDetections,
                                      int& numOfAliveDetections) = 0;

    // Creates a text file in ASCII format, which contains a summary
    // of all the statistics that can be obtained by the call report sub-API.
    virtual int WriteReportToFile(const char* fileNameUTF8) = 0;

protected:
    VoECallReport() { }
    virtual ~VoECallReport() { }
};

}  // namespace webrtc

#endif  //  WEBRTC_VOICE_ENGINE_VOE_CALL_REPORT_H


text:
<?php
namespace GrottoPress\Jentil\Setups\Customizer;

use GrottoPress\Jentil\Setups\Customizer;
use GrottoPress\Jentil\Setups\Customizer\AbstractPanel;
use WP_Customize_Manager as WPCustomizer;

final class Posts extends AbstractPanel
{
    public function __construct(Customizer $customizer)
    {
        parent::__construct($customizer);

        $this->id = 'posts';

        $this->args['title'] = \esc_html__('Posts', 'jentil');
        // $this->args['description'] = \esc_html__('Description here', 'jentil');
    }

    public function add(WPCustomizer $wp_customizer)
    {
        $this->setSections();

        parent::add($wp_customizer);
    }

    private function setSections()
    {
        $this->sections['Author'] = new Posts\Author($this);
        $this->sections['Date'] = new Posts\Date($this);
        $this->sections['Search'] = new Posts\Search($this);

        if ($taxonomies = $this->customizer->app->utilities
            ->page->posts->taxonomies()
        ) {
            foreach ($taxonomies as $taxonomy) {
                $this->sections["Taxonomy_{$taxonomy->name}"] =
                    new Posts\Taxonomy($this, $taxonomy);
            }
        }

        if ($post_types = $this->customizer->app->utilities
            ->page->posts->archive->postTypes()
        ) {
            foreach ($post_types as $post_type) {
                $this->sections["Sticky_{$post_type->name}"] =
                    new Posts\Sticky($this, $post_type);
                $this->sections["PostType_{$post_type->name}"] =
                    new Posts\PostType($this, $post_type);
            }
        }

        if ($post_types = $this->customizer->app->utilities
            ->page->posts->postTypes()
        ) {
            foreach ($post_types as $post_type) {
                $this->sections["Singular_{$post_type->name}"] =
                    new Posts\Singular($this, $post_type);
                $this->sections["Related_{$post_type->name}"] =
                    new Posts\Related($this, $post_type);
            }
        }
    }
}


text:
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace Mono.Debugging.Client
{
	public class DebuggerStatistics
	{
		static readonly int[] UpperTimeLimits = { 10, 50, 100, 250, 500, 1000, 1500, 2000, 5000, 10000 };

		readonly int[] buckets = new int[UpperTimeLimits.Length + 1];
		readonly object mutex = new object ();
		TimeSpan minTime = TimeSpan.MaxValue;
		TimeSpan maxTime, totalTime;

		public DebuggerStatistics(string name)
		{
			Name = name;
		}

		public double MaxTime {
			get { return maxTime.TotalMilliseconds; }
		}

		public double MinTime {
			get { return minTime.TotalMilliseconds; }
		}

		public double AverageTime {
			get {
				if (TimingsCount > 0)
					return totalTime.TotalMilliseconds / TimingsCount;

				return 0;
			}
		}

		public int TimingsCount { get; private set; }

		public int FailureCount { get; private set; }
		public string Name { get; }

		public DebuggerTimer StartTimer (string name)
		{
			return new DebuggerTimer (this, name);
		}

		int GetBucketIndex (TimeSpan duration)
		{
			var ms = (long) duration.TotalMilliseconds;

			for (var bucket = 0; bucket < UpperTimeLimits.Length; bucket++) {
				if (ms <= UpperTimeLimits[bucket])
					return bucket;
			}

			return buckets.Length - 1;
		}

		public void AddTime (TimeSpan duration)
		{
			lock (mutex) {
				if (duration > maxTime)
					maxTime = duration;

				if (duration < minTime)
					minTime = duration;

				buckets[GetBucketIndex (duration)]++;

				totalTime += duration;
				TimingsCount++;
			}
		}

		public void IncrementFailureCount ()
		{
			lock (mutex) {
				FailureCount++;
			}
		}

		public void Serialize (Dictionary<string, object> metadata)
		{
			metadata["AverageDuration"] = AverageTime;
			metadata["MaximumDuration"] = MaxTime;
			metadata["MinimumDuration"] = MinTime;
			metadata["FailureCount"] = FailureCount;
			metadata["SuccessCount"] = TimingsCount;

			for (int i = 0; i < buckets.Length; i++)
				metadata[$"Bucket{i}"] = buckets[i];
		}
	}

	public class DebuggerTimer : IDisposable
	{
		readonly DebuggerStatistics stats;
		readonly Stopwatch stopwatch;

		static readonly TraceListener traceListener = new TraceSource (nameof (DebuggerTimer)).Listeners.OfType<TraceListener> ().FirstOrDefault (l => l.Name == nameof (DebuggerTimer));
		static int traceSeq = 0;
		int traceId;

		public DebuggerTimer (DebuggerStatistics stats, string name)
		{
			stopwatch = Stopwatch.StartNew ();
			this.stats = stats;
			if (stats != null && traceListener != null) {
				traceId = Interlocked.Increment (ref traceSeq);
				traceListener.TraceEvent (null, stats.Name, TraceEventType.Start, traceId, name);
			}
		}

		/// <summary>
		/// Indicates if the debugger operation was successful. If this is false the
		/// timing will not be reported and a failure will be indicated.
		/// </summary>
		public bool Success { get; set; }

		public TimeSpan Elapsed {
			get { return stopwatch.Elapsed; }
		}

		public void Stop (bool success)
		{
			stopwatch.Stop ();
			Success = success;

			if (stats == null)
				return;
			traceListener?.TraceEvent (null, stats.Name, TraceEventType.Stop, traceId, "Stop1");

			if (success)
				stats.AddTime (stopwatch.Elapsed);
			else
				stats.IncrementFailureCount ();
		}

		public void Stop (ObjectValue val)
		{
			stopwatch.Stop ();
			if (stats == null)
				return;
			traceListener?.TraceEvent (null, stats.Name, TraceEventType.Stop, traceId, "Stop2");

			if (val.IsEvaluating || val.IsEvaluatingGroup) {
				// Do not capture timing - evaluation not finished.
			} else if (val.IsError || val.IsImplicitNotSupported || val.IsNotSupported || val.IsUnknown) {
				stats.IncrementFailureCount ();
			} else {
				// Success
				stats.AddTime (stopwatch.Elapsed);
			}
		}

		public void Dispose ()
		{
			if (stopwatch.IsRunning) {
				stopwatch.Stop ();

				if (stats == null)
					return;
				traceListener?.TraceEvent (null, stats.Name, TraceEventType.Stop, traceId, "Dispose");

				if (Success)
					stats.AddTime (stopwatch.Elapsed);
				else
					stats.IncrementFailureCount ();
			}
		}
	}
}


text:
package org.cfr.capsicum.spring.support;

import java.util.List;

import org.apache.cayenne.QueryResponse;
import org.apache.cayenne.query.Query;
import org.apache.cayenne.query.SelectQuery;
import org.cfr.capsicum.support.SelectQueryResponse;
import org.springframework.dao.DataAccessException;

/**
 * A facade to Cayenne DataContext, adapting it for use with Spring DAO
 * exceptions, etc.
 */
public interface ICayenneOperations {

    /**
     * Flushes all changes to objects in this context to the parent DataChannel, cascading
     * flush operation all the way through the stack, ultimately saving data in the
     * database.
     * @throws DataAccessException
     */
    public void commitChanges() throws DataAccessException;

    /**
     * Runs an arbitrary DB operation defined as CayenneCallback.
     */
    public <R> R execute(ICayenneCallback callback) throws DataAccessException;

    /**
     *
     * @param query
     * @return
     * @throws DataAccessException
     */
    public <T> T getObjectForQuery(final Query query) throws DataAccessException;

    /**
     *
     * @param <T>
     * @param dataObjectClass
     * @param pk
     * @return
     * @throws DataAccessException
     */
    public <T> T objectForPK(Class<T> dataObjectClass, Object pk) throws DataAccessException;

    /**
     *
     * @param query
     * @return
     * @throws DataAccessException
     */
    public QueryResponse performQuery(final Query query) throws DataAccessException;

    /**
     *
     * @param query
     * @return
     * @throws DataAccessException
     */
    public <T> List<T> performSelectQuery(Query query) throws DataAccessException;

    /**
     *
     * @param dataObjectClass
     * @param query
     * @return
     * @throws DataAccessException
     */
    public <T> SelectQueryResponse<T> selectQuery(Class<T> dataObjectClass, SelectQuery<T> query)
            throws DataAccessException;

    /**
     *
     * @throws DataAccessException
     */
    public void rollbackChanges() throws DataAccessException;
}


text:
import * as loggingProviderTypes from '../loggingprovider/loggingprovider.types';
import * as CircularJSON from 'circular-json';

declare const freedom: freedom.FreedomInModuleEnv;

// Perform log message formatting. Formats an array of arguments to a
// single string.
// TODO: move this into the provider.
function formatStringMessageWithArgs_(args :Object[])
    : string {
  var msg = '';

  for (var i = 0; i < args.length; i++) {
    var arg = args[i];
    if ('string' !== typeof(arg) && !(arg instanceof String)) {
      try {
        arg = CircularJSON.stringify(arg);
      } catch (e) {
        if (arg && typeof(arg.toString) === 'function') {
          arg = arg.toString();
        } else {
          arg = e.message;
        }
      }
    }

    if (-1 !== msg.indexOf('%' + i)) {
      msg = msg.replace('%' + i, <string>arg);
    } else {
      if (msg.length > 0) {
        msg += ' ';
      }
      msg += arg;
    }
  }

  return msg;
}

export class Log {
  private logger :Promise<freedom.Logger>;

  // the minimum level at which we will issue IPCs for logging statements
  private minLevel :loggingProviderTypes.Level = loggingProviderTypes.Level.debug;

  constructor(private tag_:string) {
    this.logger = freedom.core().getLogger(this.tag_);

    if (freedom['logginglistener']) {
      freedom['logginglistener'](this.tag_).on('levelchange', this.setMinLevel_);
    } else {
      this.warn('Freedom module logginglistener is not available, IPCs will ' +
                'be issued for all logging statements');
    }
  }

  private setMinLevel_ = (level :loggingProviderTypes.Level) => {
    this.minLevel = level;
  }

  private shouldLog_ = (level :loggingProviderTypes.Level) => {
    return level >= this.minLevel;
  }

  private log_ = (level :loggingProviderTypes.Level, arg :Object, args :Object[]) :void => {
    if (!this.shouldLog_(level)) {
      return;
    }

    // arg exists to make sure at least one argument is given, we want to treat
    // all the arguments as a single array however
    args.unshift(arg);

    if (2 === args.length &&
        ('string' === typeof(args[0]) || args[0] instanceof String) &&
        Array.isArray(args[1])) {
      args = [args[0]].concat((<Object[]>args[1]).slice());
    }

    var message = formatStringMessageWithArgs_(args);

    this.logger.then((logger :freedom.Logger) => {
      // essentially do logger[loggingProviderTypes.Level[level]](message) minus the type warning
      switch (level) {
        case loggingProviderTypes.Level.debug:
          return logger.debug(message);
        case loggingProviderTypes.Level.info:
          return logger.info(message);
        case loggingProviderTypes.Level.warn:
          return logger.warn(message);
        case loggingProviderTypes.Level.error:
          return logger.error(message);
      }
    });
  }

  // Logs message in debug level.
  public debug = (arg :Object, ...args :Object[]) :void => {
    this.log_(loggingProviderTypes.Level.debug, arg, args);
  }
  // Logs message in info level.
  public info = (arg :Object, ...args :Object[]) :void => {
    this.log_(loggingProviderTypes.Level.info, arg, args);
  }
  // Logs message in warn level.
  public warn = (arg :Object, ...args :Object[]) :void => {
    this.log_(loggingProviderTypes.Level.warn, arg, args);
  }
  // Logs message in error level.
  public error = (arg :Object, ...args :Object[]) :void => {
    this.log_(loggingProviderTypes.Level.error, arg, args);
  }
}


text:
<?php

namespace UnitTests\PhpUnitGen\Parser\NodeParserUtil;

use PhpParser\Node\Stmt\ClassMethod;
use PHPUnit\Framework\TestCase;
use PhpUnitGen\Model\PropertyInterface\VisibilityInterface;
use PhpUnitGen\Parser\NodeParserUtil\MethodVisibilityHelper;

class MethodVisibilityHelperTest extends TestCase
{
    /**
     * @covers \PhpUnitGen\Parser\NodeParserUtil\MethodVisibilityHelper::getVisibility()
     */
    public function testDifferentVisibility(): void
    {
        $method = $this->createMock(ClassMethod::class);
        $method->expects($this->at(0))->method('isPrivate')
            ->with()->willReturn(true);
        $method->expects($this->at(1))->method('isPrivate')
            ->with()->willReturn(false);
        $method->expects($this->at(2))->method('isProtected')
            ->with()->willReturn(true);
        $method->expects($this->at(3))->method('isPrivate')
            ->with()->willReturn(false);
        $method->expects($this->at(4))->method('isProtected')
            ->with()->willReturn(false);

        $this->assertSame(VisibilityInterface::PRIVATE, MethodVisibilityHelper::getVisibility($method));
        $this->assertSame(VisibilityInterface::PROTECTED, MethodVisibilityHelper::getVisibility($method));
        $this->assertSame(VisibilityInterface::PUBLIC, MethodVisibilityHelper::getVisibility($method));
    }
}