text:
(function ( $ ) {
	$.fn.generateDropdownClick = function( options ) {
		// Set the default settings
		var settings = $.extend({
			item: 'menu-item'
		}, options );

		$( this ).on( 'click', function( e ) {
			e.preventDefault();
			// Get the clicked element
			var _this = $( this );

			// Bail if we're clicking a mega menu sub-menu item
			if ( _this.closest( '.sub-menu' ).closest( '.menu-item-has-children' ).hasClass( 'mega-menu' ) )
				return;

			// Get clicked parent
			var _parent = _this.closest( 'nav' );

			// If we're clicking on the main navigation, close the secondary navigation dropdown
			if ( 'main-navigation' == _parent.attr( 'class' ) ) {
				if ( $( '.secondary-navigation ul.toggled-on' ).is( ':visible' ) ) {
					$( '.secondary-navigation .main-nav .menu-item-has-children > a' ).parent().removeClass( 'sfHover' );
					$( '.secondary-navigation .main-nav .menu-item-has-children > a' ).siblings( '.children, .sub-menu' ).removeClass( 'toggled-on' );
				}
			}

			// If we're clicking on the secondary navigation, close the main navigation dropdown
			if ( 'secondary-navigation' == _parent.attr( 'class' ) ) {
				if ( $( '.main-navigation ul.toggled-on' ).is( ':visible' ) ) {
					$( '.main-navigation .main-nav .menu-item-has-children > a' ).parent().removeClass( 'sfHover' );
					$( '.main-navigation .main-nav .menu-item-has-children > a' ).siblings( '.children, .sub-menu' ).removeClass( 'toggled-on' );
				}
			}

			// Close other sub-menus
			_this.closest( 'li' ).siblings().find('.toggled-on').removeClass( 'toggled-on' );

			// Remove sfHover class from other menu items
			_this.closest( 'li' ).siblings( '.sfHover' ).removeClass( 'sfHover' );

			// Remove sfHover class from other sub menu items
			_this.closest( 'li' ).siblings().find( '.sfHover' ).removeClass( 'sfHover' );

			// Add sfHover class to parent li
			_this.closest( 'li' ).toggleClass( 'sfHover' );

			if ( 'menu-item' == settings.item ) {
				// Add toggled-on class to nearest sub-menus
				_this.siblings( '.children, .sub-menu' ).toggleClass( 'toggled-on' );

				// Change accessibility attributes
				_this.children( 'span' ).attr( 'aria-expanded', _this.attr( 'aria-expanded' ) === 'true' ? 'false' : 'true' );
			}

			if ( 'arrow' == settings.item ) {
				// Add toggled-on class to nearest sub-menus
				_this.parent().siblings( '.children, .sub-menu' ).toggleClass( 'toggled-on' );

				// Change accessibility attributes
				_this.attr( 'aria-expanded', _this.attr( 'aria-expanded' ) === 'true' ? 'false' : 'true' );
			}

			return false;
		} );

		$.fn.generateDropdownClick.close = function() {
			if ( $( 'ul.toggled-on' ).is( ':visible' ) ) {
				$( '.main-nav .menu-item-has-children > a' ).parent().removeClass( 'sfHover' );
				$( '.main-nav .menu-item-has-children > a' ).siblings( '.children, .sub-menu' ).removeClass( 'toggled-on' );
			}
        }

	};
}( jQuery ));

jQuery(document).ready(function($) {
	// Initiate dropdown click on the menu item
	if ( $( 'body' ).hasClass( 'dropdown-click-menu-item' ) ) {
		$( '.dropdown-click-menu-item .main-nav .menu-item-has-children > a' ).generateDropdownClick({
			item: 'menu-item'
		});
	}

	// Initiate dropdown click on the arrow
	if ( $( 'body' ).hasClass( 'dropdown-click-arrow' ) ) {
		// Set the dropdown click to the arrows
		$( '.dropdown-click-arrow .main-nav .menu-item-has-children > a .dropdown-menu-toggle' ).generateDropdownClick({
			item: 'arrow'
		});

		// If our parent item has # as the URL, add a class to it
		$( '.main-nav .menu-item-has-children > a' ).each( function() {
			if ( $( this ).attr( 'href' ) == '#' ) $( this ).addClass( 'menu-item-dropdown-click' );
		});

		// If our parent item has the menu-item-dropdown-click class, set the dropdown click to the whole item
		$( '.dropdown-click-arrow .main-nav .menu-item-has-children > a.menu-item-dropdown-click' ).generateDropdownClick({
			item: 'menu-item'
		});
	}

	// Close the search area on click outside of area
	$( document ).click( function( event ) {
		if ( $( 'ul.toggled-on' ).is( ':visible' ) ) {
			if ( $( event.target ).closest('ul.toggled-on').length ) {
				// do nothing
			} else {
				$( 'ul.toggled-on' ).generateDropdownClick.close();
			}
		}
	});

	// Close the dropdown menus when we click the navigation search or slideout button
	$( '.search-item a, .slideout-toggle a' ).on( 'click', function() {
		if ( $( 'ul.toggled-on' ).is( ':visible' ) ) {
			$( 'ul.toggled-on' ).generateDropdownClick.close();
		}
	});

});


text:
package com.tectonica.jonix.onix3;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.OnixComposite.OnixDataCompositeWithKey;
import com.tectonica.jonix.common.codelist.NameIdentifierTypes;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;
import com.tectonica.jonix.common.struct.JonixNameIdentifier;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Name identifier composite

 *

 * A group of data elements which together specify a name identifier, used here to carry an identifier for a person or
 * organization name given in an occurrence of the <Contributor> composite. Optional: see Group P.7
 * introductory text for valid options. Repeatable to specify name identifiers of different types for the same person or
 * organization name.
 *

 *

 *

 * Reference name
 * <tt><NameIdentifier></tt>
 *

 *

 * Short tag
 * <tt><nameidentifier></tt>
 *

 *

 * Cardinality
 * 0…n
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link AlternativeName}>

 *
<{@link ContributorReference}>

 *
<{@link Contributor}>

 *
<{@link NameAsSubject}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link DescriptiveDetail} ⯈ {@link Contributor} ⯈ {@link AlternativeName}
 * ⯈ {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ContentDetail} ⯈ {@link ContentItem} ⯈ {@link Contributor} ⯈
 * {@link AlternativeName} ⯈ {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link PromotionDetail} ⯈ {@link PromotionalEvent} ⯈ {@link Contributor}
 * ⯈ {@link AlternativeName} ⯈ {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link DescriptiveDetail} ⯈ {@link Collection} ⯈ {@link Contributor} ⯈
 * {@link AlternativeName} ⯈ {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link DescriptiveDetail} ⯈ {@link NameAsSubject} ⯈
 * {@link AlternativeName} ⯈ {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ContentDetail} ⯈ {@link ContentItem} ⯈ {@link NameAsSubject} ⯈
 * {@link AlternativeName} ⯈ {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link PromotionDetail} ⯈ {@link PromotionalEvent} ⯈
 * {@link ContributorReference} ⯈ {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link DescriptiveDetail} ⯈ {@link Contributor} ⯈
 * {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ContentDetail} ⯈ {@link ContentItem} ⯈ {@link Contributor} ⯈
 * {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link PromotionDetail} ⯈ {@link PromotionalEvent} ⯈ {@link Contributor}
 * ⯈ {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link DescriptiveDetail} ⯈ {@link Collection} ⯈ {@link Contributor} ⯈
 * {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link DescriptiveDetail} ⯈ {@link NameAsSubject} ⯈
 * {@link NameIdentifier}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ContentDetail} ⯈ {@link ContentItem} ⯈ {@link NameAsSubject} ⯈
 * {@link NameIdentifier}

 *

 */
public class NameIdentifier
    implements OnixDataCompositeWithKey<JonixNameIdentifier, NameIdentifierTypes>, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "NameIdentifier";
    public static final String shortname = "nameidentifier";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * (type: dt.DateOrDateTime)
     */
    public String datestamp;

    /**
     * (type: dt.NonEmptyString)
     */
    public String sourcename;

    public RecordSourceTypes sourcetype;

    /////////////////////////////////////////////////////////////////////////////////
    // CONSTRUCTION
    /////////////////////////////////////////////////////////////////////////////////

    private boolean initialized;
    private final boolean exists;
    private final org.w3c.dom.Element element;
    public static final NameIdentifier EMPTY = new NameIdentifier();

    public NameIdentifier() {
        exists = false;
        element = null;
        initialized = true; // so that no further processing will be done on this intentionally-empty object
    }

    public NameIdentifier(org.w3c.dom.Element element) {
        exists = true;
        initialized = false;
        this.element = element;
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcename = JPU.getAttribute(element, "sourcename");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));
    }

    @Override
    public void _initialize() {
        if (initialized) {
            return;
        }
        initialized = true;

        JPU.forElementsOf(element, e -> {
            final String name = e.getNodeName();
            switch (name) {
                case NameIDType.refname:
                case NameIDType.shortname:
                    nameIDType = new NameIDType(e);
                    break;
                case IDValue.refname:
                case IDValue.shortname:
                    idValue = new IDValue(e);
                    break;
                case IDTypeName.refname:
                case IDTypeName.shortname:
                    idTypeName = new IDTypeName(e);
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * @return whether this tag (<NameIdentifier> or <nameidentifier>) is explicitly provided in the ONIX
     *         XML
     */
    @Override
    public boolean exists() {
        return exists;
    }

    @Override
    public org.w3c.dom.Element getXmlElement() {
        return element;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // MEMBERS
    /////////////////////////////////////////////////////////////////////////////////

    private NameIDType nameIDType = NameIDType.EMPTY;

    /**
     *

     * An ONIX code which identifies the scheme from which the value in the <IDValue> element is taken. Mandatory
     * in each occurrence of the <NameIdentifier> composite, and non-repeating.
     *

     * Jonix-Comment: this field is required
     */
    public NameIDType nameIDType() {
        _initialize();
        return nameIDType;
    }

    private IDValue idValue = IDValue.EMPTY;

    /**
     *

     * A code value taken from the scheme specified in the <NameIDType> element. Mandatory in each occurrence of
     * the composite, and non-repeating.
     *

     * Jonix-Comment: this field is required
     */
    public IDValue idValue() {
        _initialize();
        return idValue;
    }

    private IDTypeName idTypeName = IDTypeName.EMPTY;

    /**
     *

     * A name which identifies a proprietary identifier scheme (ie a scheme which is not a standard and for which
     * there is no individual ID type code). Must be included when, and only when, the code in the <NameIDType>
     * element indicates a proprietary scheme. Optional and non-repeating.
     *

     * Jonix-Comment: this field is optional
     */
    public IDTypeName idTypeName() {
        _initialize();
        return idTypeName;
    }

    @Override
    public JonixNameIdentifier asStruct() {
        _initialize();
        JonixNameIdentifier struct = new JonixNameIdentifier();
        struct.nameIDType = nameIDType.value;
        struct.idTypeName = idTypeName.value;
        struct.idValue = idValue.value;
        return struct;
    }

    @Override
    public NameIdentifierTypes structKey() {
        return nameIDType().value;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package au.com.jakebarnes.JourneyPlanner;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class PTVAPI {
    /**
     * Generates a signature using the HMAC-SHA1 algorithm
     *
     * @param privateKey - Developer Key supplied by PTV
     * @param uri - request uri (Example :/v2/HealthCheck)
     * @param developerId - Developer ID supplied by PTV
     * @return Unique Signature Value
     */
    public static String generateSignature(final String privateKey, final String uri, final int developerId)
    {
        String encoding = "UTF-8";
        String HMAC_SHA1_ALGORITHM = "HmacSHA1";
        String signature;
        StringBuffer uriWithDeveloperID = new StringBuffer();
        uriWithDeveloperID.append(uri).append(uri.contains("?") ? "&" : "?").append("devid="+developerId);
        try
        {
            byte[] keyBytes = privateKey.getBytes(encoding);
            byte[] uriBytes = uriWithDeveloperID.toString().getBytes(encoding);
            Key signingKey = new SecretKeySpec(keyBytes, HMAC_SHA1_ALGORITHM);
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);
            byte[] signatureBytes = mac.doFinal(uriBytes);
            StringBuffer buf = new StringBuffer(signatureBytes.length * 2);
            for (byte signatureByte : signatureBytes)
            {
                int intVal = signatureByte & 0xff;
                if (intVal < 0x10)
                {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(intVal));
            }
            signature = buf.toString();
        }
        catch (UnsupportedEncodingException e)
        {
            throw new RuntimeException(e);
        }
        catch (NoSuchAlgorithmException e)
        {
            throw new RuntimeException(e);
        }
        catch (InvalidKeyException e)
        {
            throw new RuntimeException(e);
        }
        return signature.toString().toUpperCase();
    }

    /**
     * Generate full URL using generateSignature() method
     *
     * @param privateKey - Developer Key supplied by PTV (Example :  "92dknhh31-6a30-4cac-8d8b-8a1970834799");
     * @param uri - request uri (Example :"/v2/mode/2/line/787/stops-for-line)
     * @param developerId - Developer ID supplied by PTV( int developerId )
     * @return - Full URL with Signature
     */
    public static String generateCompleteURLWithSignature(final String privateKey, final String uri, final int developerId)
    {

        String baseURL="http://timetableapi.ptv.vic.gov.au";
        StringBuffer url = new StringBuffer(baseURL).append(uri).append(uri.contains("?") ? "&" : "?").append("devid="+developerId).append("&signature="+generateSignature(privateKey, uri, developerId));
//        System.out.println(url.toString());
        return url.toString();
    }
}


text:
@interface MainViewController : CDVViewController
// CUSTOM BEGIN
@property NSUInteger mySupportedInterfaceOrientations;
// CUSTOM END
@end

@interface MainCommandDelegate : CDVCommandDelegateImpl
@end

@interface MainCommandQueue : CDVCommandQueue
@end


text:
package com.lightbend.lagom.it.two;

import com.google.inject.AbstractModule;
import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport;

public class ServiceAModule extends AbstractModule implements ServiceGuiceSupport {
  @Override
  protected void configure() {
    bindService(ServiceA.class, ServiceAImpl.class);
    bindClient(ServiceB.class);
  }
}


text:
using LeagueSharp;
using LeagueSharp.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using SharpDX;
using Color = System.Drawing.Color;

namespace xSLx_Orbwalker
{
	// ReSharper disable once InconsistentNaming
	public class xSLxOrbwalker
	{

		private static readonly string[] AttackResets = { "dariusnoxiantacticsonh", "fioraflurry", "garenq", "hecarimrapidslash", "jaxempowertwo", "jaycehypercharge", "leonashieldofdaybreak" ,"monkeykingdoubleattack", "mordekaisermaceofspades", "nasusq", "nautiluspiercinggaze", "netherblade", "parley", "poppydevastatingblow", "powerfist", "renektonpreexecute", "rengarq", "shyvanadoubleattack", "sivirw", "takedown", "talonnoxiandiplomacy", "trundletrollsmash", "vaynetumble", "vie", "volibearq", "xenzhaocombotarget", "yorickspectral" };
		private static readonly string[] NoAttacks = { "jarvanivcataclysmattack", "monkeykingdoubleattack", "shyvanadoubleattack", "shyvanadoubleattackdragon", "zyragraspingplantattack", "zyragraspingplantattack2", "zyragraspingplantattackfire", "zyragraspingplantattack2fire" };
		private static readonly string[] Attacks = { "caitlynheadshotmissile", "frostarrow", "garenslash2", "kennenmegaproc", "lucianpassiveattack", "masteryidoublestrike", "quinnwenhanced", "renektonexecute", "renektonsuperexecute", "rengarnewpassivebuffdash", "trundleq", "xenzhaothrust", "viktorqbuff", "xenzhaothrust2", "xenzhaothrust3" };

		public static Menu Menu;
		public static Obj_AI_Hero MyHero = ObjectManager.Player;
		public static Obj_AI_Base ForcedTarget = null;
		public static IEnumerable<Obj_AI_Hero> AllEnemys = ObjectManager.Get<Obj_AI_Hero>().Where(hero => hero.IsEnemy);
		public static IEnumerable<Obj_AI_Hero> AllAllys = ObjectManager.Get<Obj_AI_Hero>().Where(hero => hero.IsAlly);
		public static bool CustomOrbwalkMode;

		public delegate void BeforeAttackEvenH(BeforeAttackEventArgs args);
		public delegate void OnTargetChangeH(Obj_AI_Base oldTarget, Obj_AI_Base newTarget);
		public delegate void AfterAttackEvenH(Obj_AI_Base unit, Obj_AI_Base target);
		public delegate void OnAttackEvenH(Obj_AI_Base unit, Obj_AI_Base target);

		public static event BeforeAttackEvenH BeforeAttack;
		public static event OnTargetChangeH OnTargetChange;
		public static event AfterAttackEvenH AfterAttack;
		public static event OnAttackEvenH OnAttack;

		public enum Mode
		{
			Combo,
			Harass,
			LaneClear,
			LaneFreeze,
			Lasthit,
			Flee,
			None,
		}

		private static bool _drawing = true;
		private static bool _attack = true;
		private static bool _movement = true;
		private static bool _disableNextAttack;
		private const float LaneClearWaitTimeMod = 2f;
		private static int _lastAATick;
		private static Obj_AI_Base _lastTarget;
		private static Spell _movementPrediction;
		private static int _lastMovement;
		private static int _windup;
		private static int lastRealAttack;
		public static void AddToMenu(Menu menu)
		{
			_movementPrediction = new Spell(SpellSlot.Unknown, GetAutoAttackRange());
			_movementPrediction.SetTargetted(MyHero.BasicAttack.SpellCastTime, MyHero.BasicAttack.MissileSpeed);

			Menu = menu;

			var menuDrawing = new Menu("Drawing", "orb_Draw");
			menuDrawing.AddItem(new MenuItem("orb_Draw_AARange", "AA Circle").SetValue(new Circle(true, Color.FloralWhite)));
			menuDrawing.AddItem(new MenuItem("orb_Draw_AARange_Enemy", "AA Circle Enemy").SetValue(new Circle(true, Color.Pink)));
			menuDrawing.AddItem(new MenuItem("orb_Draw_Holdzone", "Holdzone").SetValue(new Circle(true, Color.FloralWhite)));
			menuDrawing.AddItem(new MenuItem("orb_Draw_MinionHPBar", "Minion HPBar").SetValue(new Circle(true, Color.Black)));
			menuDrawing.AddItem(new MenuItem("orb_Draw_MinionHPBar_thickness", "^ HPBar Thickness").SetValue(new Slider(1, 1, 3)));
			menuDrawing.AddItem(new MenuItem("orb_Draw_hitbox", "Show HitBoxes").SetValue(new Circle(true, Color.FloralWhite)));
			menuDrawing.AddItem(new MenuItem("orb_Draw_Lasthit", "Minion Lasthit").SetValue(new Circle(true, Color.Lime)));
			menuDrawing.AddItem(new MenuItem("orb_Draw_nearKill", "Minion nearKill").SetValue(new Circle(true, Color.Gold)));
			menu.AddSubMenu(menuDrawing);

			var menuMisc = new Menu("Misc", "orb_Misc");
			menuMisc.AddItem(new MenuItem("orb_Misc_Holdzone", "Hold Position").SetValue(new Slider(50, 100, 0)));
			menuMisc.AddItem(new MenuItem("orb_Misc_Farmdelay", "Farm Delay").SetValue(new Slider(0, 200, 0)));
			menuMisc.AddItem(new MenuItem("orb_Misc_ExtraWindUp", "Extra Winduptime").SetValue(new Slider(80, 200, 0)));
			menuMisc.AddItem(new MenuItem("orb_Misc_AutoWindUp", "Autoset Windup").SetValue(false));
			menuMisc.AddItem(new MenuItem("orb_Misc_Priority_Unit", "Priority Unit").SetValue(new StringList(new[] { "Minion", "Hero" })));
			menuMisc.AddItem(new MenuItem("orb_Misc_Humanizer", "Humanizer Delay").SetValue(new Slider(80, 200, 15)));
			menuMisc.AddItem(new MenuItem("orb_Misc_AllMovementDisabled", "Disable All Movement").SetValue(false));
			menuMisc.AddItem(new MenuItem("orb_Misc_AllAttackDisabled", "Disable All Attacks").SetValue(false));

			menu.AddSubMenu(menuMisc);

			var menuMelee = new Menu("Melee", "orb_Melee");
			menuMelee.AddItem(new MenuItem("orb_Melee_Prediction", "Movement Prediction").SetValue(false));
			menu.AddSubMenu(menuMelee);

			var menuModes = new Menu("Orbwalk Mode", "orb_Modes");
			{
				var modeCombo = new Menu("Combo", "orb_Modes_Combo");
				modeCombo.AddItem(new MenuItem("Combo_Key", "Key").SetValue(new KeyBind(32, KeyBindType.Press)));
				modeCombo.AddItem(new MenuItem("Combo_move", "Movement").SetValue(true));
				modeCombo.AddItem(new MenuItem("Combo_attack", "Attack").SetValue(true));
				menuModes.AddSubMenu(modeCombo);

				var modeHarass = new Menu("Harass", "orb_Modes_Harass");
				modeHarass.AddItem(new MenuItem("Harass_Key", "Key").SetValue(new KeyBind("C".ToCharArray()[0], KeyBindType.Press)));
				modeHarass.AddItem(new MenuItem("Harass_move", "Movement").SetValue(true));
				modeHarass.AddItem(new MenuItem("Harass_attack", "Attack").SetValue(true));
				modeHarass.AddItem(new MenuItem("Harass_Lasthit", "Lasthit Minions").SetValue(true));
				menuModes.AddSubMenu(modeHarass);

				var modeLaneClear = new Menu("LaneClear", "orb_Modes_LaneClear");
				modeLaneClear.AddItem(new MenuItem("LaneClear_Key", "Key").SetValue(new KeyBind("V".ToCharArray()[0], KeyBindType.Press)));
				modeLaneClear.AddItem(new MenuItem("LaneClear_move", "Movement").SetValue(true));
				modeLaneClear.AddItem(new MenuItem("LaneClear_attack", "Attack").SetValue(true));
				menuModes.AddSubMenu(modeLaneClear);

				var modeLaneFreeze = new Menu("LaneFreeze", "orb_Modes_LaneFreeze");
				modeLaneFreeze.AddItem(new MenuItem("LaneFreeze_Key", "Key").SetValue(new KeyBind("Z".ToCharArray()[0], KeyBindType.Press)));
				modeLaneFreeze.AddItem(new MenuItem("LaneFreeze_move", "Movement").SetValue(true));
				modeLaneFreeze.AddItem(new MenuItem("LaneFreeze_attack", "Attack").SetValue(true));
				menuModes.AddSubMenu(modeLaneFreeze);

				var modeLasthit = new Menu("LastHit", "orb_Modes_LastHit");
				modeLasthit.AddItem(new MenuItem("LastHit_Key", "Key").SetValue(new KeyBind("X".ToCharArray()[0], KeyBindType.Press)));
				modeLasthit.AddItem(new MenuItem("LastHit_move", "Movement").SetValue(true));
				modeLasthit.AddItem(new MenuItem("LastHit_attack", "Attack").SetValue(true));
				menuModes.AddSubMenu(modeLasthit);

				var modeFlee = new Menu("Flee", "orb_Modes_Flee");
				modeFlee.AddItem(new MenuItem("Flee_Key", "Key").SetValue(new KeyBind("A".ToCharArray()[0], KeyBindType.Press)));
				menuModes.AddSubMenu(modeFlee);
			}
			menu.AddSubMenu(menuModes);
			menu.AddItem(new MenuItem("xSLx_info", "Copyright by xSLx"));
			menu.AddItem(new MenuItem("xSLx_info2", "Credits: xSLx & Esk0r"));

			Drawing.OnDraw += OnDraw;
			Game.OnGameUpdate += OnUpdate;
			Obj_AI_Base.OnProcessSpellCast += OnProcessSpell;
			GameObject.OnCreate += Obj_SpellMissile_OnCreate;
		}

		private static void Obj_SpellMissile_OnCreate(GameObject sender, EventArgs args)
		{
			if(sender.IsMe)
			{
				var obj = (Obj_AI_Hero)sender;
				if(obj.IsMelee())
					return;
			}
			if(!(sender is Obj_SpellMissile) || !sender.IsValid)
				return;
			var missile = (Obj_SpellMissile)sender;
			if(missile.SpellCaster is Obj_AI_Hero && missile.SpellCaster.IsValid && IsAutoAttack(missile.SData.Name))
			{
				FireAfterAttack(missile.SpellCaster, _lastTarget);
				if (sender.IsMe)
					lastRealAttack = Environment.TickCount;
			}
		}

		private static void OnUpdate(EventArgs args)
		{
			CheckAutoWindUp();
			if(CurrentMode == Mode.None || MenuGUI.IsChatOpen || CustomOrbwalkMode)
				return;
			var target = GetPossibleTarget();
			Orbwalk(Game.CursorPos, target);
		}

		private static void OnDraw(EventArgs args)
		{
			if(!_drawing)
				return;

			if(Menu.Item("orb_Draw_AARange").GetValue<Circle>().Active)
			{
				Utility.DrawCircle(MyHero.Position, GetAutoAttackRange(), Menu.Item("orb_Draw_AARange").GetValue<Circle>().Color);
			}

			if(Menu.Item("orb_Draw_AARange_Enemy").GetValue<Circle>().Active ||
				Menu.Item("orb_Draw_hitbox").GetValue<Circle>().Active)
			{
				foreach(var enemy in AllEnemys.Where(enemy => enemy.IsValidTarget(1500)))
				{
					if(Menu.Item("orb_Draw_AARange_Enemy").GetValue<Circle>().Active)
						Utility.DrawCircle(enemy.Position, GetAutoAttackRange(enemy, MyHero), Menu.Item("orb_Draw_AARange_Enemy").GetValue<Circle>().Color);
					if(Menu.Item("orb_Draw_hitbox").GetValue<Circle>().Active)
						Utility.DrawCircle(enemy.Position, enemy.BoundingRadius, Menu.Item("orb_Draw_hitbox").GetValue<Circle>().Color);
				}
			}

			if(Menu.Item("orb_Draw_AARange_Enemy").GetValue<Circle>().Active)
			{
				foreach(var enemy in AllEnemys.Where(enemy => enemy.IsValidTarget(1500)))
				{
					Utility.DrawCircle(enemy.Position, GetAutoAttackRange(enemy, MyHero), Menu.Item("orb_Draw_AARange_Enemy").GetValue<Circle>().Color);

				}
			}

			if(Menu.Item("orb_Draw_Holdzone").GetValue<Circle>().Active)
			{
				Utility.DrawCircle(MyHero.Position, Menu.Item("orb_Misc_Holdzone").GetValue<Slider>().Value, Menu.Item("orb_Draw_Holdzone").GetValue<Circle>().Color);
			}

			if(Menu.Item("orb_Draw_MinionHPBar").GetValue<Circle>().Active ||
				Menu.Item("orb_Draw_Lasthit").GetValue<Circle>().Active ||
				Menu.Item("orb_Draw_nearKill").GetValue<Circle>().Active)
			{
				var minionList = MinionManager.GetMinions(MyHero.Position, GetAutoAttackRange() + 500, MinionTypes.All, MinionTeam.Enemy, MinionOrderTypes.MaxHealth);
				foreach(var minion in minionList.Where(minion => minion.IsValidTarget(GetAutoAttackRange() + 500)))
				{
					var attackToKill = Math.Ceiling(minion.MaxHealth / MyHero.GetAutoAttackDamage(minion, true));
					var hpBarPosition = minion.HPBarPosition;
					var barWidth = minion.IsMelee() ? 75 : 80;
					if(minion.HasBuff("turretshield", true))
						barWidth = 70;
					var barDistance = (float)(barWidth / attackToKill);
					if(Menu.Item("orb_Draw_MinionHPBar").GetValue<Circle>().Active)
					{
						for(var i = 1; i < attackToKill; i++)
						{
							var startposition = hpBarPosition.X + 45 + barDistance * i;
							Drawing.DrawLine(
								new Vector2(startposition, hpBarPosition.Y + 18),
								new Vector2(startposition, hpBarPosition.Y + 23),
								Menu.Item("orb_Draw_MinionHPBar_thickness").GetValue<Slider>().Value,
								Menu.Item("orb_Draw_MinionHPBar").GetValue<Circle>().Color);
						}
					}
					if(Menu.Item("orb_Draw_Lasthit").GetValue<Circle>().Active &&
						minion.Health <= MyHero.GetAutoAttackDamage(minion, true))
						Utility.DrawCircle(minion.Position, minion.BoundingRadius, Menu.Item("orb_Draw_Lasthit").GetValue<Circle>().Color);
					else if(Menu.Item("orb_Draw_nearKill").GetValue<Circle>().Active &&
							 minion.Health <= MyHero.GetAutoAttackDamage(minion, true) * 2)
						Utility.DrawCircle(minion.Position, minion.BoundingRadius, Menu.Item("orb_Draw_nearKill").GetValue<Circle>().Color);
				}
			}
		}

		public static void Orbwalk(Vector3 goalPosition, Obj_AI_Base target)
		{
			if(target != null && (CanAttack()|| HaveCancled()) && IsAllowedToAttack() )
			{
				_disableNextAttack = false;
				FireBeforeAttack(target);
				if(!_disableNextAttack)
				{
					if(CurrentMode != Mode.Harass || !target.IsMinion || Menu.Item("Harass_Lasthit").GetValue<bool>())
					{
						MyHero.IssueOrder(GameObjectOrder.AttackUnit, target);
						_lastAATick = Environment.TickCount + Game.Ping / 2 ;
					}
				}
			}
			if(!CanMove() || !IsAllowedToMove())
				return;
			if(MyHero.IsMelee() && target != null && target.Distance(MyHero) < GetAutoAttackRange(MyHero, target) &&
				Menu.Item("orb_Melee_Prediction").GetValue<bool>() && target is Obj_AI_Hero && Game.CursorPos.Distance(target.Position) < 300)
			{
				_movementPrediction.Delay = MyHero.BasicAttack.SpellCastTime;
				_movementPrediction.Speed = MyHero.BasicAttack.MissileSpeed;
				MoveTo(_movementPrediction.GetPrediction(target).UnitPosition);
			}
			else
				MoveTo(goalPosition);
		}

		private static void MoveTo(Vector3 position)
		{
			var delay = Menu.Item("orb_Misc_Humanizer").GetValue<Slider>().Value;
			if(Environment.TickCount - _lastMovement < delay)
				return;
			_lastMovement = Environment.TickCount;

			var holdAreaRadius = Menu.Item("orb_Misc_Holdzone").GetValue<Slider>().Value;
			if(MyHero.ServerPosition.Distance(position) < holdAreaRadius)
			{
				if(MyHero.Path.Count() > 1)
					MyHero.IssueOrder(GameObjectOrder.HoldPosition, MyHero.Position);
				return;
			}
			var point = MyHero.ServerPosition +
			300 * (position.To2D() - MyHero.ServerPosition.To2D()).Normalized().To3D();
			MyHero.IssueOrder(GameObjectOrder.MoveTo, point);

		}

		private static bool IsAllowedToMove()
		{
			if(!_movement)
				return false;
			if(Menu.Item("orb_Misc_AllMovementDisabled").GetValue<bool>())
				return false;
			if(CurrentMode == Mode.Combo && !Menu.Item("Combo_move").GetValue<bool>())
				return false;
			if(CurrentMode == Mode.Harass && !Menu.Item("Harass_move").GetValue<bool>())
				return false;
			if(CurrentMode == Mode.LaneClear && !Menu.Item("LaneClear_move").GetValue<bool>())
				return false;
			if(CurrentMode == Mode.LaneFreeze && !Menu.Item("LaneFreeze_move").GetValue<bool>())
				return false;
			return CurrentMode != Mode.Lasthit || Menu.Item("LastHit_move").GetValue<bool>();
		}

		private static bool IsAllowedToAttack()
		{
			if(!_attack)
				return false;
			if(Menu.Item("orb_Misc_AllAttackDisabled").GetValue<bool>())
				return false;
			if(CurrentMode == Mode.Combo && !Menu.Item("Combo_attack").GetValue<bool>())
				return false;
			if(CurrentMode == Mode.Harass && !Menu.Item("Harass_attack").GetValue<bool>())
				return false;
			if(CurrentMode == Mode.LaneClear && !Menu.Item("LaneClear_attack").GetValue<bool>())
				return false;
			if(CurrentMode == Mode.LaneFreeze && !Menu.Item("LaneFreeze_attack").GetValue<bool>())
				return false;
			return CurrentMode != Mode.Lasthit || Menu.Item("LastHit_attack").GetValue<bool>();

		}

		private static void OnProcessSpell(Obj_AI_Base unit, GameObjectProcessSpellCastEventArgs spell)
		{
			if(IsAutoAttackReset(spell.SData.Name) && unit.IsMe)
				Utility.DelayAction.Add(100, ResetAutoAttackTimer);

			if(!IsAutoAttack(spell.SData.Name))
				return;
			if(unit.IsMe)
			{
				_lastAATick = Environment.TickCount - Game.Ping / 2; // need test todo
				// ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull
				if(spell.Target is Obj_AI_Base)
				{
					FireOnTargetSwitch((Obj_AI_Base)spell.Target);
					_lastTarget = (Obj_AI_Base)spell.Target;
				}
				if(unit.IsMelee())
					Utility.DelayAction.Add(
						(int)(unit.AttackCastDelay * 1000 + Game.Ping * 0.5) + 50, () => FireAfterAttack(unit, _lastTarget));

				FireOnAttack(unit, _lastTarget);
			}
			else
			{
				FireOnAttack(unit, (Obj_AI_Base)spell.Target);
			}
		}

		public static double GetAzirAASandwarriorDamage(Obj_AI_Base unit)
		{
			var damagelist = new List<int> { 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 110, 120, 130, 140, 150, 160, 170 };
			var dmg = damagelist[MyHero.Level - 1] + (MyHero.BaseAbilityDamage * 0.7);
			if(
				ObjectManager.Get<Obj_AI_Minion>()
					.Count(
						obj =>
							obj.Name == "AzirSoldier" && obj.IsAlly && obj.BoundingRadius < 66 && obj.AttackSpeedMod > 1 &&
							obj.Distance(unit) < 350) == 2)
				return MyHero.CalcDamage(unit, Damage.DamageType.Magical, dmg) +
					   (MyHero.CalcDamage(unit, Damage.DamageType.Magical, dmg) * 0.25);
			return MyHero.CalcDamage(unit, Damage.DamageType.Magical, dmg);
		}

		public static bool InSoldierAttackRange(Obj_AI_Base target)
		{
			return target != null && ObjectManager.Get<Obj_AI_Minion>().Any(obj => obj.Name == "AzirSoldier" && obj.IsAlly && obj.BoundingRadius < 66 && obj.AttackSpeedMod > 1 && obj.Distance(target) < 380);
		}

		public static Obj_AI_Base GetPossibleTarget()
		{
			if (ForcedTarget != null)
			{
				if (InAutoAttackRange(ForcedTarget))
					return ForcedTarget;
				ForcedTarget = null;
			}

		Obj_AI_Base tempTarget = null;

			if(Menu.Item("orb_Misc_Priority_Unit").GetValue<StringList>().SelectedIndex == 1 &&
				(CurrentMode == Mode.Harass || CurrentMode == Mode.LaneClear))
			{
				tempTarget = GetBestHeroTarget();
				if(tempTarget != null)
					return tempTarget;
			}

			if(CurrentMode == Mode.Harass || CurrentMode == Mode.Lasthit || CurrentMode == Mode.LaneClear || CurrentMode == Mode.LaneFreeze)
			{
				if(MyHero.ChampionName == "Azir")
				{
					foreach(
					var minion in
						from minion in
							ObjectManager.Get<Obj_AI_Minion>().Where(minion => minion.IsValidTarget()  && minion.Name != "Beacon" && InSoldierAttackRange(minion))
						let t = (int)(MyHero.AttackCastDelay * 1000) - 100 + Game.Ping / 2 +
								1000 * (int)MyHero.Distance(minion) / (int)MyProjectileSpeed()
						let predHealth = HealthPrediction.GetHealthPrediction(minion, t, FarmDelay(-125))
						where minion.Team != GameObjectTeam.Neutral && predHealth > 0 &&
							  predHealth <= GetAzirAASandwarriorDamage(minion)
						select minion)
						return minion;
				}

				foreach(
					var minion in
						from minion in
							ObjectManager.Get<Obj_AI_Minion>().Where(minion => minion.IsValidTarget() && minion.Name != "Beacon" && InAutoAttackRange(minion))
						let t = (int)(MyHero.AttackCastDelay * 1000) - 100 + Game.Ping / 2 +
								1000 * (int)MyHero.Distance(minion) / (int)MyProjectileSpeed()
						let predHealth = HealthPrediction.GetHealthPrediction(minion, t, FarmDelay())
						where minion.Team != GameObjectTeam.Neutral && predHealth > 0 &&
							  predHealth <= MyHero.GetAutoAttackDamage(minion, true)
						select minion)
					return minion;
			}

			if(CurrentMode != Mode.Lasthit)
			{
				tempTarget = GetBestHeroTarget();
				if(tempTarget != null)
					return tempTarget;
			}

			if(CurrentMode == Mode.Harass || CurrentMode == Mode.LaneClear || CurrentMode == Mode.LaneFreeze)
			{

				foreach(
					var turret in
						ObjectManager.Get<Obj_AI_Turret>().Where(turret => turret.IsValidTarget(GetAutoAttackRange(MyHero, turret))))
					return turret;
			}

			float[] maxhealth;
			if(CurrentMode == Mode.LaneClear || CurrentMode == Mode.Harass || CurrentMode == Mode.LaneFreeze)
			{
				if(MyHero.ChampionName == "Azir")
				{
					maxhealth = new float[] { 0 };
					var maxhealth1 = maxhealth;
					foreach(
						var minion in
							ObjectManager.Get<Obj_AI_Minion>()
								.Where(minion => InSoldierAttackRange(minion) && minion.Name != "Beacon" && minion.IsValidTarget() && minion.Team == GameObjectTeam.Neutral)
								.Where(minion => minion.MaxHealth >= maxhealth1[0] || Math.Abs(maxhealth1[0] - float.MaxValue) < float.Epsilon))
					{
						tempTarget = minion;
						maxhealth[0] = minion.MaxHealth;
					}
					if(tempTarget != null)
						return tempTarget;
				}

				maxhealth = new float[] { 0 };
				var maxhealth2 = maxhealth;
				foreach(var minion in ObjectManager.Get<Obj_AI_Minion>().Where(minion => minion.IsValidTarget(GetAutoAttackRange(MyHero, minion)) && minion.Name != "Beacon" && minion.Team == GameObjectTeam.Neutral).Where(minion => minion.MaxHealth >= maxhealth2[0] || Math.Abs(maxhealth2[0] - float.MaxValue) < float.Epsilon))
				{
					tempTarget = minion;
					maxhealth[0] = minion.MaxHealth;
				}
				if(tempTarget != null)
					return tempTarget;
			}

			if(CurrentMode != Mode.LaneClear || ShouldWait())
			{
				//ResetAutoAttackTimer();
				return null;
			}

			if(MyHero.ChampionName == "Azir")
			{
				maxhealth = new float[] { 0 };
				float[] maxhealth1 = maxhealth;
				foreach(var minion in from minion in ObjectManager.Get<Obj_AI_Minion>()
				   .Where(minion => minion.IsValidTarget() && minion.Name != "Beacon" && InSoldierAttackRange(minion))
									  let predHealth = HealthPrediction.LaneClearHealthPrediction(minion, (int)((MyHero.AttackDelay * 1000) * LaneClearWaitTimeMod), FarmDelay(-125))
									  where predHealth >=
											GetAzirAASandwarriorDamage(minion) + MyHero.GetAutoAttackDamage(minion, true) ||
											Math.Abs(predHealth - minion.Health) < float.Epsilon
									  where minion.Health >= maxhealth1[0] || Math.Abs(maxhealth1[0] - float.MaxValue) < float.Epsilon
									  select minion)
				{
					tempTarget = minion;
					maxhealth[0] = minion.MaxHealth;
				}
				if(tempTarget != null)
					return tempTarget;
			}

			maxhealth = new float[] { 0 };
			foreach(var minion in from minion in ObjectManager.Get<Obj_AI_Minion>()
			   .Where(minion => minion.IsValidTarget(GetAutoAttackRange(MyHero, minion)) && minion.Name != "Beacon")
								  let predHealth = HealthPrediction.LaneClearHealthPrediction(minion, (int)((MyHero.AttackDelay * 1000) * LaneClearWaitTimeMod), FarmDelay())
								  where predHealth >=
										2 * MyHero.GetAutoAttackDamage(minion, true) ||
										Math.Abs(predHealth - minion.Health) < float.Epsilon
								  where minion.Health >= maxhealth[0] || Math.Abs(maxhealth[0] - float.MaxValue) < float.Epsilon
								  select minion)
			{
				tempTarget = minion;
				maxhealth[0] = minion.MaxHealth;
			}
			if(tempTarget != null)
				return tempTarget;

			return null;
		}

		private static bool ShouldWait()
		{
			return ObjectManager.Get<Obj_AI_Minion>()
			.Any(
			minion =>
			minion.IsValidTarget() && minion.Team != GameObjectTeam.Neutral &&
			InAutoAttackRange(minion) &&
			HealthPrediction.LaneClearHealthPrediction(
			minion, (int)((MyHero.AttackDelay * 1000) * LaneClearWaitTimeMod), FarmDelay()) <= MyHero.GetAutoAttackDamage(minion));
		}

		public static bool IsAutoAttack(string name)
		{
			return (name.ToLower().Contains("attack") && !NoAttacks.Contains(name.ToLower())) ||
			Attacks.Contains(name.ToLower());
		}

		public static void ResetAutoAttackTimer()
		{
			_lastAATick = 0;
		}

		public static bool IsAutoAttackReset(string name)
		{
			return AttackResets.Contains(name.ToLower());
		}

		public static float GetNextAATime()
		{
			return (_lastAATick + MyHero.AttackDelay * 1000) - (Environment.TickCount + Game.Ping / 2 + 25);
		}
		public static bool CanAttack()
		{
			if (_lastAATick <= Environment.TickCount)
				return Environment.TickCount + Game.Ping/2 + 25 >= _lastAATick + MyHero.AttackDelay*1000 && _attack;
			return false;
		}

		private static bool HaveCancled()
		{
			if (_lastAATick - Environment.TickCount > MyHero.AttackCastDelay * 1000 + 25)
				return lastRealAttack < _lastAATick;
			return false;
		}

		public static bool CanMove()
		{
			if(_lastAATick <= Environment.TickCount)
				return Environment.TickCount + Game.Ping / 2 >= _lastAATick + MyHero.AttackCastDelay * 1000 + _windup && _movement;
			return false;
		}

		private static float MyProjectileSpeed()
		{
			return (MyHero.CombatType == GameObjectCombatType.Melee) ? float.MaxValue : MyHero.BasicAttack.MissileSpeed;
		}

		private static int FarmDelay(int offset = 0)
		{
			var ret = offset;
			if(MyHero.ChampionName == "Azir")
				ret += 125;
			return Menu.Item("orb_Misc_Farmdelay").GetValue<Slider>().Value + ret;
		}

		private static Obj_AI_Base GetBestHeroTarget()
		{
			Obj_AI_Hero killableEnemy = null;
			var hitsToKill = double.MaxValue;
			if(MyHero.ChampionName == "Azir")
			{
				foreach(var enemy in AllEnemys.Where(hero => hero.IsValidTarget() && InSoldierAttackRange(hero)))
				{
					var killHits = CountKillhitsAzirSoldier(enemy);
					if(killableEnemy != null && (!(killHits < hitsToKill) || enemy.HasBuffOfType(BuffType.Invulnerability)))
						continue;
					killableEnemy = enemy;
					hitsToKill = killHits;
				}
				if(hitsToKill <= 4)
					return killableEnemy;
				Obj_AI_Hero[] mostdmgenemy = { null };
				foreach(var enemy in AllEnemys.Where(hero => hero.IsValidTarget() && InSoldierAttackRange(hero)).Where(enemy => mostdmgenemy[0] == null || GetAzirAASandwarriorDamage(enemy) > GetAzirAASandwarriorDamage(mostdmgenemy[0])))
				{
					mostdmgenemy[0] = enemy;
				}
				if(mostdmgenemy[0] != null)
					return mostdmgenemy[0];
			}
			foreach(var enemy in AllEnemys.Where(hero => hero.IsValidTarget() && InAutoAttackRange(hero)))
			{
				var killHits = CountKillhits(enemy);
				if(killableEnemy != null && (!(killHits < hitsToKill) || enemy.HasBuffOfType(BuffType.Invulnerability)))
					continue;
				hitsToKill = killHits;
				killableEnemy = enemy;
			}
			return hitsToKill <= 3 ? killableEnemy : SimpleTs.GetTarget(GetAutoAttackRange(), SimpleTs.DamageType.Physical);
		}

		public static double CountKillhits(Obj_AI_Base enemy)
		{
			return enemy.Health / MyHero.GetAutoAttackDamage(enemy);
		}

		public static double CountKillhitsAzirSoldier(Obj_AI_Base enemy)
		{
			return enemy.Health / GetAzirAASandwarriorDamage(enemy);
		}

		private static void CheckAutoWindUp()
		{
			if(!Menu.Item("orb_Misc_AutoWindUp").GetValue<bool>())
			{
				_windup = GetCurrentWindupTime();
				return;
			}
			var additional = 0;
			if(Game.Ping >= 100)
				additional = Game.Ping / 100 * 5;
			else if(Game.Ping > 40 && Game.Ping < 100)
				additional = Game.Ping / 100 * 10;
			else if(Game.Ping <= 40)
				additional = +20;
			var windUp = Game.Ping + additional;
			if(windUp < 40)
				windUp = 40;
			Menu.Item("orb_Misc_ExtraWindUp").SetValue(windUp < 200 ? new Slider(windUp, 200, 0) : new Slider(200, 200, 0));
			_windup = windUp;
		}

		public static int GetCurrentWindupTime()
		{
			return Menu.Item("orb_Misc_ExtraWindUp").GetValue<Slider>().Value;
		}

		public static void EnableDrawing()
		{
			_drawing = true;
		}

		public static void DisableDrawing()
		{
			_drawing = false;
		}

		public static float GetAutoAttackRange(Obj_AI_Base source = null, Obj_AI_Base target = null)
		{
			if(source == null)
				source = MyHero;
			var ret = source.AttackRange + MyHero.BoundingRadius;
			if(target != null)
				ret += target.BoundingRadius;
			return ret;
		}

		public static bool InAutoAttackRange(Obj_AI_Base target)
		{
			if(target == null)
				return false;
			var myRange = GetAutoAttackRange(MyHero, target);
			return target.IsValidTarget(myRange);
		}

		public static Mode CurrentMode
		{
			get
			{
				if(Menu.Item("Combo_Key").GetValue<KeyBind>().Active)
					return Mode.Combo;
				if(Menu.Item("Harass_Key").GetValue<KeyBind>().Active)
					return Mode.Harass;
				if(Menu.Item("LaneClear_Key").GetValue<KeyBind>().Active)
					return Mode.LaneClear;
				if(Menu.Item("LaneFreeze_Key").GetValue<KeyBind>().Active)
					return Mode.LaneFreeze;
				if(Menu.Item("LastHit_Key").GetValue<KeyBind>().Active)
					return Mode.Lasthit;
				return Menu.Item("Flee_Key").GetValue<KeyBind>().Active ? Mode.Flee : Mode.None;
			}
		}

		public static void SetAttack(bool value)
		{
			_attack = value;
		}

		public static void SetMovement(bool value)
		{
			_movement = value;
		}

		public static bool GetAttack()
		{
			return _attack;
		}

		public static bool GetMovement()
		{
			return _movement;
		}

		public class BeforeAttackEventArgs
		{
			public Obj_AI_Base Target;
			public Obj_AI_Base Unit = ObjectManager.Player;
			private bool _process = true;
			public bool Process
			{
				get
				{
					return _process;
				}
				set
				{
					_disableNextAttack = !value;
					_process = value;
				}
			}
		}
		private static void FireBeforeAttack(Obj_AI_Base target)
		{
			if(BeforeAttack != null)
			{
				BeforeAttack(new BeforeAttackEventArgs
				{
					Target = target
				});
			}
			else
			{
				_disableNextAttack = false;
			}
		}

		private static void FireOnTargetSwitch(Obj_AI_Base newTarget)
		{
			if(OnTargetChange != null && (_lastTarget == null || _lastTarget.NetworkId != newTarget.NetworkId))
			{
				OnTargetChange(_lastTarget, newTarget);
			}
		}

		private static void FireAfterAttack(Obj_AI_Base unit, Obj_AI_Base target)
		{
			if(AfterAttack != null)
			{
				AfterAttack(unit, target);
			}
		}

		private static void FireOnAttack(Obj_AI_Base unit, Obj_AI_Base target)
		{
			if(OnAttack != null)
			{
				OnAttack(unit, target);
			}
		}
    }
}


text:
function [outlet] = join_strings(inlet, delim)
% Join strings using a delimiter.
%
%     [outlet] = join_strings(inlet, delim)
%
% `inlet` is a cell array with many strings that will become one sole string,
% separated by the `delim` string.
%
outlet = join_strings_loop(inlet{1}, inlet, delim, 2);

function [outlet]  = join_strings_loop(outlet, inlet, delim, index)
if index <= length(inlet)
    outlet = join_strings_loop(strcat(outlet, ...
                                      delim, ...
                                      inlet{index}), ...
                               inlet, ...
                               delim, ...
                               index+1);
end


text:
package cz.cesnet.meta.accounting.util;

import org.joda.time.LocalDate;

public class AcctCal {

  public static LocalDate createMonthYear(int month, int year) {
    return new LocalDate(year, month, 1);
  }

  public static LocalDate createThisMonthYear() {
    return new LocalDate().withDayOfMonth(1);
  }

  public static String toMonthYearString(LocalDate date) {
    return date.getMonthOfYear() + "/" + (date.getYearOfCentury()< 10 ? "0" + date.getYearOfCentury() : date.getYearOfCentury());
  }

  public static String toThreeMonthsYearString(LocalDate date) {
    return date.getMonthOfYear() + "-"  + (date.getMonthOfYear()+2) + "/" + (date.getYearOfCentury()< 10 ? "0" + date.getYearOfCentury() : date.getYearOfCentury());
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Attributes for RoundedImageView -->
    <declare-styleable name="RoundedImageView">

        <!--
        Size & Color to round image corners by. Default is zero, unrounded.
		<b>NOTE:</b> This only works for bitmap image sources.
        -->
        <attr name="corner_radius" format="dimension" />
        <attr name="corner_color" format="dimension" />
    </declare-styleable>

</resources>


text:
package BrickMosaic

import (
	"image"
	"image/color"
)

const (
	// Each pixel in image is blown up by this factor in paletted image
	scaleFactor = 5
)

// IdealImage is an object that implements both the Image interface and the Ideal interface
type IdealImage interface {
	image.Image
	Ideal
}

// Posterize is the interface for converting from images into DesiredMosaic objects.
type Posterize func(img image.Image, p color.Palette, rows int, cols int, o ViewOrientation) IdealImage

// BrickImage is an implementation of Ideal interface.
type BrickImage struct {
	img        image.Image
	palette    color.Palette
	rows, cols int

	colors map[Location]color.Color

	// Maps each grid cell to its color
	avgColors   map[Location]BrickColor
	orientation ViewOrientation

	// 0.0 = no dithering at all
	// 1.0 = standard amount of dithering. Scales the quantization error that is propagated
	// through the image.
	errorScalingFactor float32

	// Frames are snapshots of the process of creating the final image, for debuggin
	// purposes
	Frames []*image.Paletted
}

// AverageColor determines the 'average' color of the subimage whose coordinates are contained in the
// given bounds. The average is an arithmetic average in RGB color space.
// TODO(ndunn): try different color spaces.
func AverageColor(si image.Image, bounds image.Rectangle) color.Color {
	R, G, B, A := uint64(0), uint64(0), uint64(0), uint64(0)
	numPixels := uint64(0)
	for x := bounds.Min.X; x < bounds.Max.X; x++ {
		for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
			c := si.At(x, y)
			r, g, b, a := c.RGBA()
			R += uint64(r)
			G += uint64(g)
			B += uint64(b)
			A += uint64(a)
			numPixels++
		}
	}
	// Convert from range 0 ... 65535 -> 0 ... 255
	R /= (numPixels * 256)
	G /= (numPixels * 256)
	B /= (numPixels * 256)
	A /= (numPixels * 256)
	return color.RGBA{uint8(R), uint8(G), uint8(B), uint8(A)}
}

// NumRows returns the number of rows in the piece.
func (si *BrickImage) NumRows() int {
	return si.rows
}

// NumRows returns the number of columns in the piece.
func (si *BrickImage) NumCols() int {
	return si.cols
}

// Orientation returns the way in which the image is oriented.
func (si *BrickImage) Orientation() ViewOrientation {
	return si.orientation
}

// doMap converts a value from one range [low1, high1] into another [low2, high2].
func doMap(v, low1, high1, low2, high2 float64) float64 {
	diff := v - low1
	proportion := diff / (high1 - low1)
	return lerp(low2, high2, proportion)
}

// lerp performs linear interpolation between v1 and v2. If amt == 0, v1 is used. If amt == 1.0,
// v2 is used. At 0.5, the average of v1, v2 is used, and so on and so forth.
func lerp(v1, v2, amt float64) float64 {
	return ((v2 - v1) * amt) + v1
}

func (si *BrickImage) rowToY(row int) int {
	return int(doMap(float64(row), 0.0, float64(si.rows), float64(si.img.Bounds().Min.Y), float64(si.img.Bounds().Max.Y)))
}

func (si *BrickImage) colToX(col int) int {
	return int(doMap(float64(col), 0.0, float64(si.cols), float64(si.img.Bounds().Min.X), float64(si.img.Bounds().Max.X)))
}

func (si *BrickImage) ColorModel() color.Model {
	return si.palette
}

// FIXME ndunn base it on the orientation
func (si *BrickImage) Bounds() image.Rectangle {
	return image.Rectangle{image.Pt(0, 0), image.Pt(scaleFactor*si.cols, scaleFactor*si.rows)}
}

// Color returns the best palette.BrickColor for the given row/column
// in the image based on the palette this image was instantiated with.
func (si *BrickImage) Color(row, col int) BrickColor {
	loc := Location{row, col}
	if c, ok := si.avgColors[loc]; ok {
		return c
	}
	avgColor := si.IdealColor(row, col)
	bestMatch := si.palette.Convert(avgColor).(BrickColor)
	si.avgColors[loc] = bestMatch
	return bestMatch
}

// IdealColor returns the color that ideally we would use for the row / col combination
// if we had pieces of every color. Later this will be quantized into the nearest
// neighbor, into a BrickColor.
func (si *BrickImage) IdealColor(row, col int) color.Color {
	loc := Location{row, col}
	if c, ok := si.colors[loc]; ok {
		return c
	}

	// Convert rows/columns into x/y coordinates in the image
	y1 := si.rowToY(row)
	y2 := si.rowToY(row + 1)

	x1 := si.colToX(col)
	x2 := si.colToX(col + 1)

	bounds := image.Rect(x1, y1, x2, y2)
	avgColor := AverageColor(si.img, bounds)
	return avgColor
}

// Paletted renders the current state of the image as a Paletted image. Useful for debugging
// purposes
func (si *BrickImage) Paletted() *image.Paletted {
	p := image.NewPaletted(si.Bounds(), si.palette)
	for row := 0; row < si.NumRows(); row++ {
		for col := 0; col < si.NumCols(); col++ {
			for x := 0; x < scaleFactor; x++ {
				for y := 0; y < scaleFactor; y++ {
					x1 := col * scaleFactor
					y1 := row * scaleFactor
					p.Set(x1+x, y1+y, si.IdealColor(row, col))
				}
			}
		}
	}
	return p
}

// QuantizationError represents an error between a desired color and the best possible
// color that we can use to represent it.
type QuantizationError struct {
	// amount of error in r, g, b, a channels. Assumes 8 bit color.
	r, g, b, a int
}

// Error returns how much error is there from c1 relative to c0? High numbers means c1 has higher in that channel.
func Error(oldC, newC color.Color) QuantizationError {
	r0, g0, b0, a0 := oldC.RGBA()
	r1, g1, b1, a1 := newC.RGBA()

	// Avoid underflow when subtracting uints
	rdiff := int(int(r0) - int(r1))
	gdiff := int(int(g0) - int(g1))
	bdiff := int(int(b0) - int(b1))
	adiff := int(int(a0) - int(a1))
	return QuantizationError{
		r: rdiff / 256,
		g: gdiff / 256,
		b: bdiff / 256,
		a: adiff / 256,
	}
}

// Scale scales the given error by the given factor. For instance, Scale(2.0) doubles the
// error, while Scale(.5) halves it. This returns a new object.
func (e QuantizationError) Scale(factor float32) QuantizationError {
	return QuantizationError{
		r: int(float32(e.r) * factor),
		g: int(float32(e.g) * factor),
		b: int(float32(e.b) * factor),
		//a: int8(float32(e.a) * factor),
	}
}

// AddError adds the given amount of error to the given color, transforming it into a new color. For instance,
// if c is {R:100, G:100, B:100} and error is {r:-50,g:50,b:-50}, then the final result is
// {R:50, G:150, B:50}
func AddError(c color.Color, err QuantizationError) color.Color {
	// These are in 16 bit color; later one we convert back to 8 bit color through integer
	// division.
	r0, g0, b0, a0 := c.RGBA()

	// Avoid under and overflow.
	clamp := func(x int) uint8 {
		if x < 0 {
			return uint8(0)
		} else if x > 255 {
			return uint8(255)
		}
		return uint8(x)
	}

	return color.RGBA{
		R: clamp(int(r0/256) + err.r),
		G: clamp(int(g0/256) + err.g),
		B: clamp(int(b0/256) + err.b),
		A: clamp(int(a0/256) + err.a),
	}
}

// DitherPosterize converts the given image into an Ideal form using a standard amount of
// dithering (error propagation).
func DitherPosterize(img image.Image, p color.Palette, rows int, cols int, o ViewOrientation) Ideal {
	return NewBrickImage(img, rows, cols, p, o, 1.0)
}

// EucPosterize returns an Ideal representation of the image with no dithering.
func EucPosterize(img image.Image, p color.Palette, rows int, cols int, o ViewOrientation) Ideal {
	return NewBrickImage(img, rows, cols, p, o, 0.0)
}

// NewBrickImage returns a BrickImage based on the given inputs.
func NewBrickImage(img image.Image, rows, cols int, palette color.Palette, o ViewOrientation, errorScalingFactor float32) *BrickImage {
	brickImage := &BrickImage{
		img:                img,
		palette:            palette,
		rows:               rows,
		cols:               cols,
		colors:             make(map[Location]color.Color),
		avgColors:          make(map[Location]BrickColor),
		orientation:        o,
		errorScalingFactor: errorScalingFactor,
		Frames:             nil,
	}

	// Initialize the color map
	for row := 0; row < rows; row++ {
		for col := 0; col < cols; col++ {
			oldPixel := brickImage.IdealColor(row, col)
			brickImage.colors[Location{row, col}] = oldPixel
		}
	}
	//brickImage.Frames = append(brickImage.Frames, brickImage.Paletted())

	// Initialize the color map
	for row := 0; row < rows; row++ {
		for col := 0; col < cols; col++ {
			oldPixel := brickImage.IdealColor(row, col)
			bestMatch := brickImage.Color(row, col)
			err := Error(oldPixel, bestMatch)

			if col != cols-1 {
				// To the right
				brickImage.colors[Location{row, col + 1}] = AddError(brickImage.colors[Location{row, col + 1}], err.Scale(errorScalingFactor*7.0/16.0))
			}

			if col != 0 && row != rows-1 {
				// To Left, below
				brickImage.colors[Location{row + 1, col - 1}] = AddError(brickImage.colors[Location{row + 1, col - 1}], err.Scale(errorScalingFactor*3.0/16.0))
			}

			if row != rows-1 {
				// Center, below
				brickImage.colors[Location{row + 1, col}] = AddError(brickImage.colors[Location{row + 1, col}], err.Scale(errorScalingFactor*5.0/16.0))
			}

			if row != rows-1 && col != cols-1 {
				// To right, below
				brickImage.colors[Location{row + 1, col + 1}] = AddError(brickImage.colors[Location{row + 1, col + 1}], err.Scale(errorScalingFactor*1.0/16.0))
			}
			//brickImage.Frames = append(brickImage.Frames, brickImage.Paletted())
		}
	}
	// Final version
	brickImage.Frames = append(brickImage.Frames, brickImage.Paletted())
	return brickImage
}


text:
package li.strolch.job;

import li.strolch.agent.api.StrolchAgent;
import li.strolch.privilege.model.PrivilegeContext;

public class ReloadJobsJob extends StrolchJob {

	public ReloadJobsJob(StrolchAgent agent, String id, String name, JobMode mode) {
		super(agent, id, name, mode);
	}

	@Override
	protected void execute(PrivilegeContext ctx) throws Exception {
		StrolchJobsHandler jobsHandler = getContainer().getComponent(StrolchJobsHandler.class);
		jobsHandler.reloadJobs();
	}
}


text:
FloozChaser
===========

1. Analysing news sources and social media
This project first analyses news sources and possible social media to predict the sentiment for the varous industries etc.
Based on this sentiment result choices are made to invest in certain stocks.

2. Analyzing/Computing Fundamentals
Parse finacial statements from from data resources and compute ratio's. By querying various stock apis.

3. Engine
Based on the results in step 1 and 2, an engine computes whether a stock is good or a bad investment.


text:
package org.kwstudios.play.commands;

public class MiniGameSpectator {

	// TODO : Bukkit.getWorld("world").getPlayers() -> Loop through every time a player changes the world and if nobody
	//with gm 0 is left, teleport every Spectator to the lobby!

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v12/resources/asset_group_listing_group_filter.proto

package com.google.ads.googleads.v12.resources;

public interface AssetGroupListingGroupFilterOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v12.resources.AssetGroupListingGroupFilter)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Immutable. The resource name of the asset group listing group filter.
   * Asset group listing group filter resource name have the form:
   * `customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}`
   *

   *
   * string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The resourceName.
   */
  java.lang.String getResourceName();
  /**
   *

   * Immutable. The resource name of the asset group listing group filter.
   * Asset group listing group filter resource name have the form:
   * `customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}`
   *

   *
   * string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The bytes for resourceName.
   */
  com.google.protobuf.ByteString
      getResourceNameBytes();

  /**
   *

   * Immutable. The asset group which this asset group listing group filter is part of.
   *

   *
   * string asset_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The assetGroup.
   */
  java.lang.String getAssetGroup();
  /**
   *

   * Immutable. The asset group which this asset group listing group filter is part of.
   *

   *
   * string asset_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The bytes for assetGroup.
   */
  com.google.protobuf.ByteString
      getAssetGroupBytes();

  /**
   *

   * Output only. The ID of the ListingGroupFilter.
   *

   *
   * int64 id = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];
   * @return The id.
   */
  long getId();

  /**
   *

   * Immutable. Type of a listing group filter node.
   *

   *
   * .google.ads.googleads.v12.enums.ListingGroupFilterTypeEnum.ListingGroupFilterType type = 4 [(.google.api.field_behavior) = IMMUTABLE];
   * @return The enum numeric value on the wire for type.
   */
  int getTypeValue();
  /**
   *

   * Immutable. Type of a listing group filter node.
   *

   *
   * .google.ads.googleads.v12.enums.ListingGroupFilterTypeEnum.ListingGroupFilterType type = 4 [(.google.api.field_behavior) = IMMUTABLE];
   * @return The type.
   */
  com.google.ads.googleads.v12.enums.ListingGroupFilterTypeEnum.ListingGroupFilterType getType();

  /**
   *

   * Immutable. The vertical the current node tree represents. All nodes in the same tree
   * must belong to the same vertical.
   *

   *
   * .google.ads.googleads.v12.enums.ListingGroupFilterVerticalEnum.ListingGroupFilterVertical vertical = 5 [(.google.api.field_behavior) = IMMUTABLE];
   * @return The enum numeric value on the wire for vertical.
   */
  int getVerticalValue();
  /**
   *

   * Immutable. The vertical the current node tree represents. All nodes in the same tree
   * must belong to the same vertical.
   *

   *
   * .google.ads.googleads.v12.enums.ListingGroupFilterVerticalEnum.ListingGroupFilterVertical vertical = 5 [(.google.api.field_behavior) = IMMUTABLE];
   * @return The vertical.
   */
  com.google.ads.googleads.v12.enums.ListingGroupFilterVerticalEnum.ListingGroupFilterVertical getVertical();

  /**
   *

   * Dimension value with which this listing group is refining its parent.
   * Undefined for the root group.
   *

   *
   * .google.ads.googleads.v12.resources.ListingGroupFilterDimension case_value = 6;
   * @return Whether the caseValue field is set.
   */
  boolean hasCaseValue();
  /**
   *

   * Dimension value with which this listing group is refining its parent.
   * Undefined for the root group.
   *

   *
   * .google.ads.googleads.v12.resources.ListingGroupFilterDimension case_value = 6;
   * @return The caseValue.
   */
  com.google.ads.googleads.v12.resources.ListingGroupFilterDimension getCaseValue();
  /**
   *

   * Dimension value with which this listing group is refining its parent.
   * Undefined for the root group.
   *

   *
   * .google.ads.googleads.v12.resources.ListingGroupFilterDimension case_value = 6;
   */
  com.google.ads.googleads.v12.resources.ListingGroupFilterDimensionOrBuilder getCaseValueOrBuilder();

  /**
   *

   * Immutable. Resource name of the parent listing group subdivision. Null for the root
   * listing group filter node.
   *

   *
   * string parent_listing_group_filter = 7 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The parentListingGroupFilter.
   */
  java.lang.String getParentListingGroupFilter();
  /**
   *

   * Immutable. Resource name of the parent listing group subdivision. Null for the root
   * listing group filter node.
   *

   *
   * string parent_listing_group_filter = 7 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The bytes for parentListingGroupFilter.
   */
  com.google.protobuf.ByteString
      getParentListingGroupFilterBytes();
}


text:
require "google/cloud/dataflow/v1beta3"

##
# Example demonstrating basic usage of
# Google::Cloud::Dataflow::V1beta3::Metrics::Client#get_job_metrics
#
def get_job_metrics
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Dataflow::V1beta3::Metrics::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Dataflow::V1beta3::GetJobMetricsRequest.new

  # Call the get_job_metrics method.
  result = client.get_job_metrics request

  # The returned object is of type Google::Cloud::Dataflow::V1beta3::JobMetrics.
  p result
end
# [END dataflow_v1beta3_generated_Metrics_GetJobMetrics_sync]


text:
#import <Foundation/Foundation.h>
//#import <Cocoa/Cocoa.h>

@class DCMCalendarDate;
@class DCMTransferSyntax;

@interface DCMDataContainer : NSObject {
	NSMutableData *dicomData;
	BOOL isLittleEndian, isExplicitTS, dataRemaining;
	int offset, position;
	NSStringEncoding stringEncoding;
	DCMTransferSyntax	*transferSyntaxForDataset, *transferSyntaxForMetaheader, *transferSyntaxInUse;
	unsigned char *_ptr;
}

@property(readonly) int offset, position;
@property(readonly) unsigned int length;
@property(readonly) NSMutableData *dicomData;

+ (id)dataContainer;
+ (id)dataContainerWithBytes:(const void *)bytes length:(NSUInteger)length;
+ (id)dataContainerWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
+ (id)dataContainerWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)freeWhenDone;
+ (id)dataContainerWithContentsOfFile:(NSString *)path;
//+ (id)dataContainerWithContentsOfMappedFile:(NSString *)path;
+ (id)dataContainerWithContentsOfURL:(NSURL *)aURL;
+ (id)dataContainerWithData:(NSData *)aData;
+ (id)dataContainerWithData:(NSData *)aData transferSyntax:(DCMTransferSyntax *)syntax;
+ (id)dataContainerWithMutableData:(NSMutableData *)aData transferSyntax:(DCMTransferSyntax *)syntax;

- (id)initWithData:(NSData *)data;
- (id)initWithData:(NSData *)data transferSyntax:(DCMTransferSyntax *)syntax;
- (id)initWithMutableData:(NSMutableData *)data transferSyntax:(DCMTransferSyntax *)syntax;
- (id)initWithContentsOfFile:(NSString *)path;
- (id)initWithContentsOfURL:(NSURL *)aURL;
- (id)initWithBytes:(const void *)bytes length:(NSUInteger)length;
- (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;
- (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)flag;

- (void)initValues;

- (BOOL)isLittleEndian;
- (BOOL)isExplicitTS;
- (BOOL)isEncapsulated;
- (BOOL)dataRemaining;
- (NSStringEncoding) stringEncoding;
- (void)setLittleEndian:(BOOL)value;
- (void)setExplicitTS:(BOOL)value;

- (void)setStringEncoding:(NSStringEncoding)encoding;

- (unsigned char)nextUnsignedChar;
- (unsigned short)nextUnsignedShort;
- (short)nextSignedShort;
- (unsigned int)nextUnsignedLong;
- (int)nextSignedLong;
- (unsigned long long)nextUnsignedLongLong;
- (long long)nextSignedLongLong;
- (float)nextFloat;
- (double)nextDouble;

- (NSString *)nextStringWithLength:(int)length;
- (NSString *)nextStringWithLength:(int)length encoding:(NSStringEncoding)encoding;
- (NSString *)nextStringWithLength:(int)length encodings:(NSStringEncoding*)encodings;
- (NSCalendarDate *)nextDate;
- (NSMutableArray *)nextDatesWithLength:(int)length;
- (NSCalendarDate *)nextTimeWithLength:(int)length;
- (NSMutableArray *)nextTimesWithLength:(int)length;
- (NSCalendarDate *)nextDateTimeWithLength:(int)length;
- (NSMutableArray *)nextDateTimesWithLength:(int)length;
- (NSMutableData *)nextDataWithLength:(int)length;
- (BOOL)skipLength:(int)length;

- (void)addUnsignedChar:(unsigned char)uChar;
- (void)addSignedChar:(signed char)sChar;
- (void)addUnsignedShort:(unsigned short)uShort;
- (void)addSignedShort:(signed short)sShort;
- (void)addUnsignedLong:(unsigned long)uLong;
- (void)addSignedLong:(signed long)sLong;
- (void)addUnsignedLongLong:(unsigned long long)uLongLong;
- (void)addSignedLongLong:(signed long long)sLongLong;
- (void)addFloat:(float)f;
- (void)addDouble:(double)d;

- (void)addString:(NSString *)string;
- (void)addStringWithZeroPadding:(NSString *)string;
- (void)addString:(NSString *)string withEncoding:(NSStringEncoding)encoding;
- (void)addString:(NSString *)string withEncodings:(NSStringEncoding*)encoding;
- (void)addStringWithoutPadding:(NSString *)string;
- (void)addDate:(DCMCalendarDate *)date;
- (void)addTime:(DCMCalendarDate *)time;
- (void)addDateTime:(DCMCalendarDate *)dateTime;
- (void)addData:(NSData *)data;

- (DCMTransferSyntax *) transferSyntaxForDataset;
- (DCMTransferSyntax *) transferSyntaxForMetaheader;
- (DCMTransferSyntax *) transferSyntaxInUse;
- (void)setUseMetaheaderTS:(BOOL)flag;
- (BOOL)determineTransferSyntax;
- (void)setTransferSyntaxForDataset:(DCMTransferSyntax *)ts;
- (void)setTransferSyntaxForMetaheader:(DCMTransferSyntax *)ts;

- (NSException *)testForLength: (int)elementLength;

- (void)startReadingMetaHeader;
- (void)startReadingDataSet;

- (void)addPremable;

@end


text:
import { path } from '../../core/path.js';

import { GlbParser } from '../parsers/glb-parser.js';

/** @typedef {import('./handler.js').ResourceHandler} ResourceHandler */

/**
 * @interface
 * @name ContainerResource
 * @description Container for a list of animations, textures, materials, renders and a model.
 */
class ContainerResource {
    /**
     * Instantiates an entity with a model component.
     *
     * @param {object} [options] - The initialization data for the model component type
     * {@link ModelComponent}.
     * @returns {import('../entity.js').Entity} A single entity with a model component. Model
     * component internally contains a hierarchy based on {@link GraphNode}.
     * @example
     * // load a glb file and instantiate an entity with a model component based on it
     * app.assets.loadFromUrl("statue.glb", "container", function (err, asset) {
     *     var entity = asset.resource.instantiateModelEntity({
     *         castShadows: true
     *     });
     *     app.root.addChild(entity);
     * });
     */
    instantiateModelEntity(options) {
        return null;
    }

    /**
     * Instantiates an entity with a render component.
     *
     * @param {object} [options] - The initialization data for the render component type
     * {@link RenderComponent}.
     * @returns {import('../entity.js').Entity} A hierarchy of entities with render components on
     * entities containing renderable geometry.
     * @example
     * // load a glb file and instantiate an entity with a render component based on it
     * app.assets.loadFromUrl("statue.glb", "container", function (err, asset) {
     *     var entity = asset.resource.instantiateRenderEntity({
     *         castShadows: true
     *     });
     *     app.root.addChild(entity);
     *
     *     // find all render components containing mesh instances, and change blend mode on their materials
     *     var renders = entity.findComponents("render");
     *     renders.forEach(function (render) {
     *         render.meshInstances.forEach(function (meshInstance) {
     *             meshInstance.material.blendType = pc.BLEND_MULTIPLICATIVE;
     *             meshInstance.material.update();
     *         });
     *     });
     * });
     */
    instantiateRenderEntity(options) {
        return null;
    }

    /**
     * Queries the list of available material variants.
     *
     * @returns {string[]} An array of variant names.
     */
    getMaterialVariants() {
        return null;
    }

    /**
     * Applies a material variant to an entity hierarchy.
     *
     * @param {import('../entity.js').Entity} entity - The entity root to which material variants
     * will be applied.
     * @param {string} [name] - The name of the variant, as queried from getMaterialVariants,
     * if null the variant will be reset to the default.
     * @example
     * // load a glb file and instantiate an entity with a render component based on it
     * app.assets.loadFromUrl("statue.glb", "container", function (err, asset) {
     *     var entity = asset.resource.instantiateRenderEntity({
     *         castShadows: true
     *     });
     *     app.root.addChild(entity);
     *     var materialVariants = asset.resource.getMaterialVariants();
     *     asset.resource.applyMaterialVariant(entity, materialVariants[0]);
     */
    applyMaterialVariant(entity, name) {}

    /**
     * Applies a material variant to a set of mesh instances. Compared to the applyMaterialVariant,
     * this method allows for setting the variant on a specific set of mesh instances instead of the
     * whole entity.
     *
     * @param {import('../../scene/mesh-instance').MeshInstance[]} instances - An array of mesh
     * instances.
     * @param {string} [name] - The the name of the variant, as quered from getMaterialVariants,
     * if null the variant will be reset to the default
     * @example
     * // load a glb file and instantiate an entity with a render component based on it
     * app.assets.loadFromUrl("statue.glb", "container", function (err, asset) {
     *     var entity = asset.resource.instantiateRenderEntity({
     *         castShadows: true
     *     });
     *     app.root.addChild(entity);
     *     var materialVariants = asset.resource.getMaterialVariants();
     *     var renders = entity.findComponents("render");
     *     for (var i = 0; i < renders.length; i++) {
     *         var renderComponent = renders[i];
     *         asset.resource.applyMaterialVariantInstances(renderComponent.meshInstances, materialVariants[0]);
     *     }
     */
    applyMaterialVariantInstances(instances, name) {}
}

/**
 * Loads files that contain multiple resources. For example glTF files can contain textures, models
 * and animations.
 *
 * For glTF files, the asset options object can be used to pass load time callbacks for handling
 * the various resources at different stages of loading. The table below lists the resource types
 * and the corresponding supported process functions.
 *
 * ```
 * |---------------------------------------------------------------------|
 * |  resource   |  preprocess |   process   |processAsync | postprocess |
 * |-------------+-------------+-------------+-------------+-------------|
 * | global      |      x      |             |             |      x      |
 * | node        |      x      |      x      |             |      x      |
 * | light       |      x      |      x      |             |      x      |
 * | camera      |      x      |      x      |             |      x      |
 * | animation   |      x      |             |             |      x      |
 * | material    |      x      |      x      |             |      x      |
 * | image       |      x      |             |      x      |      x      |
 * | texture     |      x      |             |      x      |      x      |
 * | buffer      |      x      |             |      x      |      x      |
 * | bufferView  |      x      |             |      x      |      x      |
 * |---------------------------------------------------------------------|
 * ```
 *
 * Additional options that can be passed for glTF files:
 * [options.morphPreserveData] - When true, the morph target keeps its data passed using the options,
 * allowing the clone operation.
 *
 * For example, to receive a texture preprocess callback:
 *
 * ```javascript
 * var containerAsset = new pc.Asset(filename, 'container', { url: url, filename: filename }, null, {
 *     texture: {
 *         preprocess(gltfTexture) { console.log("texture preprocess"); }
 *     },
 * });
 * ```
 *
 * @implements {ResourceHandler}
 */
class ContainerHandler {
    /**
     * Type of the resource the handler handles.
     *
     * @type {string}
     */
    handlerType = "container";

    /**
     * Create a new ContainerResource instance.
     *
     * @param {import('../app-base.js').AppBase} app - The running {@link AppBase}.
     * @hideconstructor
     */
    constructor(app) {
        this.glbParser = new GlbParser(app.graphicsDevice, app.assets, 0);
        this.parsers = { };
    }

    set maxRetries(value) {
        this.glbParser.maxRetries = value;
        for (const parser in this.parsers) {
            if (this.parsers.hasOwnProperty(parser)) {
                this.parsers[parser].maxRetries = value;
            }
        }
    }

    get maxRetries() {
        return this.glbParser.maxRetries;
    }

    /**
     * @param {string} url - The resource URL.
     * @returns {string} The URL with query parameters removed.
     * @private
     */
    _getUrlWithoutParams(url) {
        return url.indexOf('?') >= 0 ? url.split('?')[0] : url;
    }

    /**
     * @param {string} url - The resource URL.
     * @returns {*} A suitable parser to parse the resource.
     * @private
     */
    _getParser(url) {
        const ext = url ? path.getExtension(this._getUrlWithoutParams(url)).toLowerCase().replace('.', '') : null;
        return this.parsers[ext] || this.glbParser;
    }

    /**
     * @param {string|object} url - Either the URL of the resource to load or a structure
     * containing the load and original URL.
     * @param {string} [url.load] - The URL to be used for loading the resource.
     * @param {string} [url.original] - The original URL to be used for identifying the resource
     * format. This is necessary when loading, for example from blob.
     * @param {import('./handler.js').ResourceHandlerCallback} callback - The callback used when
     * the resource is loaded or an error occurs.
     * @param {import('../asset/asset.js').Asset} [asset] - Optional asset that is passed by
     * ResourceLoader.
     */
    load(url, callback, asset) {
        if (typeof url === 'string') {
            url = {
                load: url,
                original: url
            };
        }

        this._getParser(url.original).load(url, callback, asset);
    }

    /**
     * @param {string} url - The URL of the resource to open.
     * @param {*} data - The raw resource data passed by callback from {@link ResourceHandler#load}.
     * @param {import('../asset/asset.js').Asset} [asset] - Optional asset that is passed by
     * ResourceLoader.
     * @returns {*} The parsed resource data.
     */
    open(url, data, asset) {
        return this._getParser(url).open(url, data, asset);
    }

    /**
     * @param {import('../asset/asset.js').Asset} asset - The asset to patch.
     * @param {import('../asset/asset-registry.js').AssetRegistry} assets - The asset registry.
     */
    patch(asset, assets) {

    }
}

export { ContainerResource, ContainerHandler };