text:
module IX.Reactive.Input
   (playerInput
   ,eUpdatePmap
   ,eHypTravel
   ,timer
   ,toEPair)
   where

import DataStructures.Atomic
import DataStructures.Composite
import IX.Universe.Combat
import IX.Universe.HyperSpace
import IX.Universe.Input
import IX.Universe.Utils
import IX.Universe.Output
import IX.Reactive.Utils
import IX.Universe.Market

import Data.Either (isLeft,isRight,lefts,rights)
import Data.Maybe
import Reactive.Banana (apply,unionWith,Behavior,Event,filterJust,filterE
                       ,(<@),(<@>),(<$),(<$>),(<*>))
import qualified Data.Map.Strict as M
import Prelude hiding (unionWith)

playerInput :: GameMaps        ->
               DieRolls        ->
               Event GameState ->
               Buffer          ->
              (Event [DAgentMap],  Event (Maybe (M.Map AID ToPlanetName)))
playerInput gMaps bDieRolls eGameState eBuffer =

   let bAMap'          = bAMap gMaps
       (bLMap',eLMap') = beLMap gMaps

       eClearOut   = [(Just $ ClearOut)] <$ eGameState
       eLook       = apply (lookToAgt <$> bAMap') $
                     unionWith (M.union) eHypAction ePlanetAction

       eDamage     = apply (dmgToAgt <$> bAMap') $ ePlanetAction

       eTransition = (commTransitions <$> bLMap') <@ eLMap'

       eCError     = apply (cErrToAgt <$> bAMap') $
                     unionWith (M.union) eHypAction ePlanetAction

       eChangeShip = apply (changeShip <$> bAMap') $
                     unionWith (M.union) eHypAction ePlanetAction

       eLocalMarket = apply (marketToAgt <$> bAMap') $ ePlanetAction

       eCommerce = apply (commerceToAgt <$> bAMap') $ ePlanetAction

--       eAInput     = filterJust ( eClearOut   `unionWith`
--                                  eLook       `unionWith`
--                                  eDamage     `unionWith`
--                                  eTransition `unionWith`
--                                  eChangeShip `unionWith`
--                                  eCommerce   `unionWith`
--                                  eLocalMarket `unionWith`
--                                  eCError)
       eAInput = catMaybes <$> eLook
--         catMaybes <$>
--         (unionWith (++)
--         (unionWith (++) eLook
--                         ( unionWith (++) eDamage eTransition ))

--         (unionWith (++) ( unionWith (++) eChangeShip eCommerce )
--                         ( unionWith (++) eLocalMarket eCError )))
       ePlanetAction = psAction actions
       eHypAction    = hsAction actions
       eMove = moveAction actions

   in (eAInput,eMove)
   where
      actions = partitionedActions gMaps bDieRolls eBuffer

partitionedActions  :: GameMaps ->
                       DieRolls ->
                       Buffer   ->
                       ActionPartitions
partitionedActions gMaps bDieRolls eBuffer =
   let eMove           = Just <$> M.fromList <$> rights <$> eEvalPComm
       ePSaction       = M.fromList <$> lefts <$> eEvalPComm
       eHSaction       = evalHypComm <$>
                         bLMap'      <*>
                         bAMap'      <@>
                         filterJust eHypComm
   in ActionPartitions eMove ePSaction eHSaction
   where
      bAMap'             = bAMap gMaps
      bLMap'             = fst $ beLMap gMaps
      bPMap'             = bPMap gMaps
      bRMap'             = bRMap gMaps

      (eUPComm,eHypComm) =
         toEPair $ apply (whichLoc <$> bLMap') eBuffer
      eEvalPComm         =
         (evalPComm <$> bPMap' <*> bAMap' <*> bRMap' <*> bDieRolls) `apply`
         ePComm
      ePComm             =
         apply (orderUPComm <$> bLMap') $ filterJust eUPComm

eUpdatePmap :: (Behavior LocationMap, Event ()) ->
               Behavior AgentMap                ->
               Event (PlanetMap -> PlanetMap)
eUpdatePmap (bLMap,eLMap) bAMap' =
   (updatePmap <$> bLMap <*> bAMap') <@ eLMap

eHypTravel :: Event GameState -> Event (Maybe (M.Map AID ToPlanetName))
eHypTravel eGameState = Nothing <$ eGameState

-- much like split

toEPair :: Event (a, b) -> (Event a, Event b)
toEPair epair = (extractFst <$> epair, extractSnd <$> epair)
   where
      extractFst (x, _) = x
      extractSnd (_, y) = y

filterRight :: Event (Either a b) -> Event b
filterRight e = filterJust $ fromRight <$> filterE isRight e

filterLeft :: Event (Either a b) -> Event a
filterLeft e = filterJust $ fromLeft <$> filterE isLeft e


text:
package com.javaq.mixins;

import com.javaq.construct.GroupBy;

/**
 * @author Vivek Mittal
 */
public interface Groupable extends JavaQContext {
    public default GroupBy groupBy(String variable) {
        return new GroupBy(this, variable);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.giraph.comm.netty.handler;

import org.apache.giraph.comm.netty.NettyServer;
import org.apache.giraph.comm.netty.SaslNettyServer;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**
 * Authorize or deny client requests based on existence and completeness
 * of client's SASL authentication.
 */
public class AuthorizeServerHandler extends
    SimpleChannelUpstreamHandler {
  /** Class logger */
  private static final Logger LOG =
      Logger.getLogger(AuthorizeServerHandler.class);

  /**
   * Constructor.
   */
  public AuthorizeServerHandler() {
  }

  @Override
  public void messageReceived(
      ChannelHandlerContext ctx, MessageEvent e) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("messageReceived: Got " + e.getMessage().getClass());
    }
    // Authorize: client is allowed to doRequest() if and only if the client
    // has successfully authenticated with this server.
    SaslNettyServer saslNettyServer =
        NettyServer.CHANNEL_SASL_NETTY_SERVERS.get(ctx.getChannel());
    if (saslNettyServer == null) {
      LOG.warn("messageReceived: This client is *NOT* authorized to perform " +
          "this action since there's no saslNettyServer to " +
          "authenticate the client: " +
          "refusing to perform requested action: " + e.getMessage());
      return;
    }

    if (!saslNettyServer.isComplete()) {
      LOG.warn("messageReceived: This client is *NOT* authorized to perform " +
          "this action because SASL authentication did not complete: " +
          "refusing to perform requested action: " + e.getMessage());
      // Return now *WITHOUT* sending upstream here, since client
      // not authorized.
      return;
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("messageReceived: authenticated client: " +
          saslNettyServer.getUserName() + " is authorized to do request " +
          "on server.");
    }
    // We call sendUpstream() since the client is allowed to perform this
    // request. The client's request will now proceed to the next
    // pipeline component, namely, RequestServerHandler.
    ctx.sendUpstream(e);
  }
}


text:
export interface IPackageJson {
  name: string;
  dependencies: Record<string, string>;
  devDependencies: Record<string, string>;
  peerDependencies?: Record<string, string>;
  transitiveDependencies?: Record<string, string>;
}


text:
package io.github.jeddict.db.modeler.widget;

import io.github.jeddict.db.modeler.spec.DBColumn;
import io.github.jeddict.db.modeler.initializer.DBModelerScene;
import org.netbeans.modeler.widget.node.IPNodeWidget;
import org.netbeans.modeler.widget.pin.info.PinWidgetInfo;

public class BasicColumnWidget extends ColumnWidget<DBColumn> {

    public BasicColumnWidget(DBModelerScene scene, IPNodeWidget nodeWidget, PinWidgetInfo pinWidgetInfo) {
        super(scene, nodeWidget, pinWidgetInfo);
    }

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Project>
    <MasterNode>
        <Processor Name="MainProcessor">
            <ComputingUnits>4</ComputingUnits>
        </Processor>
    </MasterNode>
</Project>


text:
package jintgen.jigir;

import cck.parser.SourcePoint;
import cck.text.StringUtil;
import jintgen.isdl.parser.Token;
import jintgen.types.Type;
import jintgen.types.Typeable;

/**
 * The Expr class represents an expression in the IR. Expressions are evaluated and produce a
 * value that can be assigned to locals, globalMap, maps, used in if statements, and passed as parameters.
 *
 * @author Ben L. Titzer
 */
public abstract class Expr implements Typeable {

    public static final int PREC_L_OR = 0;
    public static final int PREC_L_XOR = 1;
    public static final int PREC_L_AND = 2;
    public static final int PREC_A_OR = 3;
    public static final int PREC_A_XOR = 4;
    public static final int PREC_A_AND = 5;
    public static final int PREC_L_EQU = 6;
    public static final int PREC_L_REL = 7;
    public static final int PREC_A_SHIFT = 8;
    public static final int PREC_A_ADD = 9;
    public static final int PREC_A_MUL = 10;
    public static final int PREC_UN = 11;
    public static final int PREC_TERM = 12;

    protected Type type;

    /**
     * The getType() method returns the type of this expression as computed by the
     * TypeChecker.
     * @return a reference to a Type object that represents the type of this expression.
     */
    public Type getType() {
        return type;
    }

    /**
     * The setType() method sets the type of this expression. This is meant to be called
     * by the TypeChecker as it visits the program and computes the type of each expression.
     * @param t the new type of this expression
     */
    public void setType(Type t) {
        type = t;
    }

    /**
     * The isVariable() method tests whether this expression is a single variable use.
     *
     * @return true if this expression is a direct use of a variable; false otherwise
     */
    public boolean isVariable() {
        return false;
    }

    /**
     * The isLiteral() method tests whether this expression is a known constant directly (i.e. a
     * literal).
     *
     * @return true if this expression is a literal; false otherwise
     */
    public boolean isLiteral() {
        return false;
    }

    /**
     * The isConstantExpr() method tests whether this expression is a constant expression (i.e.
     * it is reducable to a constant and has no references to variables, maps, etc).
     *
     * @return true if this expression can be evaluated to a constant; false otherwise
     */
    public boolean isConstantExpr() {
        return false;
    }

    /**
     * The isBitRangeExpr() method tests whether the expression is an access of a range of bits.
     * This is used in pattern matching in some parts of the code.
     *
     * @return true if this expression is a bit range expression; false otherwise
     */
    public boolean isBitRangeExpr() {
        return false;
    }

    /**
     * The getPrecedence() method gets the binding precedence for this expression. This is used
     * to compute when inner expressions must be nested within parentheses in order to preserve the implied
     * order of evaluation.
     *
     * @return an integer representing the precedence of this expression; higher numbers are higher
     *         precedence
     */
    public abstract int getPrecedence();

    /**
     * The tokenToInt() static method is a utility to evaluate a token as an integer.
     *
     * @param i the value of the integer as a token
     * @return the integer value of the token if it exists
     */
    public static int tokenToInt(Token i) {
        if (i == null) return -1;
        return StringUtil.evaluateIntegerLiteral(i.image);
    }

    /**
     * The tokenToBool() static method is a utility to evaluate a token as a boolean literal.
     *
     * @param i the value of the boolean as a token
     * @return the boolean value of the token if it exists
     */
    public static boolean tokenToBool(Token i) {
        return Boolean.valueOf(i.image);
    }

    /**
     * The accept() method implements one half of the visitor pattern so that client visitors can
     * traverse the syntax tree easily and in an extensible way.
     *
     * @param v the visitor to accept
     */
    public abstract void accept(CodeVisitor v);

    /**
     * The accept() method implements one half of the visitor pattern for rebuilding of
     * expressions. This visitor allows code to be slightly modified while only writing visit methods for the
     * parts of the syntax tree affected.
     *
     * @param r the accumulator to accept
     * @return the result of calling the appropriate visit() method of the rebuilder
     */
    public abstract <Res, Env> Res accept(CodeAccumulator<Res, Env> r, Env env);

    /**
     * The innerString() method is a utility to embed an expression in parentheses only if its
     * precedence is less than the precedence of this expression. This is useful in converting nested
     * expressions into strings
     *
     * @param e the expression nested inside of this expression
     * @return a string that is the result of converting the specified expression to a string and nesting it
     *         in parentheses if necessary
     */
    public String innerString(Expr e) {
        if (e.getPrecedence() < this.getPrecedence())
            return StringUtil.embed(e.toString());
        else
            return e.toString();
    }

    public boolean isLvalue() {
        return false;
    }

    /**
     * The getSourcePoint() method returns a reference to a SourcePoint
     * instance that represents the location in the source program of this expression.
     * @return a SourcePoint instance that represents this expression in the
     * source program
     */
    public abstract SourcePoint getSourcePoint();
}


text:
<?php

namespace Google\Service\Directory\Resource;

use Google\Service\Directory\OrgUnit;
use Google\Service\Directory\OrgUnits as OrgUnitsModel;

/**
 * The "orgunits" collection of methods.
 * Typical usage is:
 *  <code>
 *   $adminService = new Google\Service\Directory(...);
 *   $orgunits = $adminService->orgunits;
 *  </code>
 */
class Orgunits extends \Google\Service\Resource
{
  /**
   * Removes an organizational unit. (orgunits.delete)
   *
   * @param string $customerId The unique ID for the customer's Google Workspace
   * account. As an account administrator, you can also use the `my_customer`
   * alias to represent your account's `customerId`. The `customerId` is also
   * returned as part of the [Users resource](/admin-
   * sdk/directory/v1/reference/users).
   * @param string $orgUnitPath The full path of the organizational unit (minus
   * the leading `/`) or its unique ID.
   * @param array $optParams Optional parameters.
   */
  public function delete($customerId, $orgUnitPath, $optParams = [])
  {
    $params = ['customerId' => $customerId, 'orgUnitPath' => $orgUnitPath];
    $params = array_merge($params, $optParams);
    return $this->call('delete', [$params]);
  }
  /**
   * Retrieves an organizational unit. (orgunits.get)
   *
   * @param string $customerId The unique ID for the customer's Google Workspace
   * account. As an account administrator, you can also use the `my_customer`
   * alias to represent your account's `customerId`. The `customerId` is also
   * returned as part of the [Users resource](/admin-
   * sdk/directory/v1/reference/users).
   * @param string $orgUnitPath The full path of the organizational unit (minus
   * the leading `/`) or its unique ID.
   * @param array $optParams Optional parameters.
   * @return OrgUnit
   */
  public function get($customerId, $orgUnitPath, $optParams = [])
  {
    $params = ['customerId' => $customerId, 'orgUnitPath' => $orgUnitPath];
    $params = array_merge($params, $optParams);
    return $this->call('get', [$params], OrgUnit::class);
  }
  /**
   * Adds an organizational unit. (orgunits.insert)
   *
   * @param string $customerId The unique ID for the customer's Google Workspace
   * account. As an account administrator, you can also use the `my_customer`
   * alias to represent your account's `customerId`. The `customerId` is also
   * returned as part of the [Users resource](/admin-
   * sdk/directory/v1/reference/users).
   * @param OrgUnit $postBody
   * @param array $optParams Optional parameters.
   * @return OrgUnit
   */
  public function insert($customerId, OrgUnit $postBody, $optParams = [])
  {
    $params = ['customerId' => $customerId, 'postBody' => $postBody];
    $params = array_merge($params, $optParams);
    return $this->call('insert', [$params], OrgUnit::class);
  }
  /**
   * Retrieves a list of all organizational units for an account.
   * (orgunits.listOrgunits)
   *
   * @param string $customerId The unique ID for the customer's Google Workspace
   * account. As an account administrator, you can also use the `my_customer`
   * alias to represent your account's `customerId`. The `customerId` is also
   * returned as part of the [Users resource](/admin-
   * sdk/directory/v1/reference/users).
   * @param array $optParams Optional parameters.
   *
   * @opt_param string orgUnitPath The full path to the organizational unit or its
   * unique ID. Returns the children of the specified organizational unit.
   * @opt_param string type Whether to return all sub-organizations or just
   * immediate children.
   * @return OrgUnitsModel
   */
  public function listOrgunits($customerId, $optParams = [])
  {
    $params = ['customerId' => $customerId];
    $params = array_merge($params, $optParams);
    return $this->call('list', [$params], OrgUnitsModel::class);
  }
  /**
   * Updates an organizational unit. This method supports [patch semantics
   * ](/admin-sdk/directory/v1/guides/performance#patch) (orgunits.patch)
   *
   * @param string $customerId The unique ID for the customer's Google Workspace
   * account. As an account administrator, you can also use the `my_customer`
   * alias to represent your account's `customerId`. The `customerId` is also
   * returned as part of the [Users resource](/admin-
   * sdk/directory/v1/reference/users).
   * @param string $orgUnitPath The full path of the organizational unit (minus
   * the leading `/`) or its unique ID.
   * @param OrgUnit $postBody
   * @param array $optParams Optional parameters.
   * @return OrgUnit
   */
  public function patch($customerId, $orgUnitPath, OrgUnit $postBody, $optParams = [])
  {
    $params = ['customerId' => $customerId, 'orgUnitPath' => $orgUnitPath, 'postBody' => $postBody];
    $params = array_merge($params, $optParams);
    return $this->call('patch', [$params], OrgUnit::class);
  }
  /**
   * Updates an organizational unit. (orgunits.update)
   *
   * @param string $customerId The unique ID for the customer's Google Workspace
   * account. As an account administrator, you can also use the `my_customer`
   * alias to represent your account's `customerId`. The `customerId` is also
   * returned as part of the [Users resource](/admin-
   * sdk/directory/v1/reference/users).
   * @param string $orgUnitPath The full path of the organizational unit (minus
   * the leading `/`) or its unique ID.
   * @param OrgUnit $postBody
   * @param array $optParams Optional parameters.
   * @return OrgUnit
   */
  public function update($customerId, $orgUnitPath, OrgUnit $postBody, $optParams = [])
  {
    $params = ['customerId' => $customerId, 'orgUnitPath' => $orgUnitPath, 'postBody' => $postBody];
    $params = array_merge($params, $optParams);
    return $this->call('update', [$params], OrgUnit::class);
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Orgunits::class, 'Google_Service_Directory_Resource_Orgunits');


text:
require "/scripts/util.lua"
require "/scripts/vec2.lua"
require "/scripts/versioningutils.lua"
require "/scripts/staticrandom.lua"
require "/items/buildscripts/abilities.lua"

function build(directory, config, parameters, level, seed)
  local configParameter = function(keyName, defaultValue)
    if parameters[keyName] ~= nil then
      return parameters[keyName]
    elseif config[keyName] ~= nil then
      return config[keyName]
    else
      return defaultValue
    end
  end

  if level and not configParameter("fixedLevel", false) then
    parameters.level = level
  end

  -- initialize randomization
  if seed then
    parameters.seed = seed
  else
    seed = configParameter("seed")
    if not seed then
      math.randomseed(util.seedTime())
      seed = math.random(1, 4294967295)
      parameters.seed = seed
    end
  end

  -- select the generation profile to use
  local builderConfig = {}
  if config.builderConfig then
    builderConfig = randomFromList(config.builderConfig, seed, "builderConfig")
  end

  -- select, load and merge abilities
  setupAbility(config, parameters, "alt", builderConfig, seed)
  setupAbility(config, parameters, "primary", builderConfig, seed)

  -- elemental type
  if not parameters.elementalType and builderConfig.elementalType then
    parameters.elementalType = randomFromList(builderConfig.elementalType, seed, "elementalType")
  end
  local elementalType = configParameter("elementalType", "physical")

  -- elemental config
  if builderConfig.elementalConfig then
    util.mergeTable(config, builderConfig.elementalConfig[elementalType])
  end
  if config.altAbility and config.altAbility.elementalConfig then
    util.mergeTable(config.altAbility, config.altAbility.elementalConfig[elementalType])
  end

  -- elemental tag
  replacePatternInData(config, nil, "<elementalType>", elementalType)
  replacePatternInData(config, nil, "<elementalName>", elementalType:gsub("^%l", string.upper))

  -- name
  if not parameters.shortdescription and builderConfig.nameGenerator then
    parameters.shortdescription = root.generateName(util.absolutePath(directory, builderConfig.nameGenerator), seed)
  end

  -- merge damage properties
  if builderConfig.damageConfig then
    util.mergeTable(config.damageConfig or {}, builderConfig.damageConfig)
  end

  -- preprocess shared primary attack config
  parameters.primaryAbility = parameters.primaryAbility or {}
  parameters.primaryAbility.fireTimeFactor = valueOrRandom(parameters.primaryAbility.fireTimeFactor, seed, "fireTimeFactor")
  parameters.primaryAbility.baseDpsFactor = valueOrRandom(parameters.primaryAbility.baseDpsFactor, seed, "baseDpsFactor")
  parameters.primaryAbility.energyUsageFactor = valueOrRandom(parameters.primaryAbility.energyUsageFactor, seed, "energyUsageFactor")

  config.primaryAbility.fireTime = scaleConfig(parameters.primaryAbility.fireTimeFactor, config.primaryAbility.fireTime)
  config.primaryAbility.baseDps = scaleConfig(parameters.primaryAbility.baseDpsFactor, config.primaryAbility.baseDps)
  config.primaryAbility.energyUsage = scaleConfig(parameters.primaryAbility.energyUsageFactor, config.primaryAbility.energyUsage) or 0

  -- preprocess melee primary attack config
  if config.primaryAbility.damageConfig and config.primaryAbility.damageConfig.knockbackRange then
    config.primaryAbility.damageConfig.knockback = scaleConfig(parameters.primaryAbility.fireTimeFactor, config.primaryAbility.damageConfig.knockbackRange)
  end

  -- preprocess ranged primary attack config
  if config.primaryAbility.projectileParameters then
    config.primaryAbility.projectileType = randomFromList(config.primaryAbility.projectileType, seed, "projectileType")
    config.primaryAbility.projectileCount = randomIntInRange(config.primaryAbility.projectileCount, seed, "projectileCount") or 1
    config.primaryAbility.fireType = randomFromList(config.primaryAbility.fireType, seed, "fireType") or "auto"
    config.primaryAbility.burstCount = randomIntInRange(config.primaryAbility.burstCount, seed, "burstCount")
    config.primaryAbility.burstTime = randomInRange(config.primaryAbility.burstTime, seed, "burstTime")
    if config.primaryAbility.projectileParameters.knockbackRange then
      config.primaryAbility.projectileParameters.knockback = scaleConfig(parameters.primaryAbility.fireTimeFactor, config.primaryAbility.projectileParameters.knockbackRange)
    end
  end

  -- calculate damage level multiplier
  config.damageLevelMultiplier = root.evalFunction("weaponDamageLevelMultiplier", configParameter("level", 1))

  -- build palette swap directives
  config.paletteSwaps = ""
  if builderConfig.palette then
    local palette = root.assetJson(util.absolutePath(directory, builderConfig.palette))
    local selectedSwaps = randomFromList(palette.swaps, seed, "paletteSwaps")
    for k, v in pairs(selectedSwaps) do
      config.paletteSwaps = string.format("%s?replace=%s=%s", config.paletteSwaps, k, v)
    end
  end

  -- merge extra animationCustom
  if builderConfig.animationCustom then
    util.mergeTable(config.animationCustom or {}, builderConfig.animationCustom)
  end

  -- animation parts
  if builderConfig.animationParts then
    config.animationParts = config.animationParts or {}
    if parameters.animationPartVariants == nil then parameters.animationPartVariants = {} end
    for k, v in pairs(builderConfig.animationParts) do
      if type(v) == "table" then
        if v.variants and (not parameters.animationPartVariants[k] or parameters.animationPartVariants[k] > v.variants) then
          parameters.animationPartVariants[k] = randomIntInRange({1, v.variants}, seed, "animationPart"..k)
        end
        config.animationParts[k] = util.absolutePath(directory, string.gsub(v.path, "<variant>", parameters.animationPartVariants[k] or ""))
        if v.paletteSwap then
          config.animationParts[k] = config.animationParts[k] .. config.paletteSwaps
        end
      else
        config.animationParts[k] = v
      end
    end
  end

  -- set gun part offsets
  local partImagePositions = {}
  if builderConfig.gunParts then
    construct(config, "animationCustom", "animatedParts", "parts")
    local imageOffset = {0,0}
    local gunPartOffset = {0,0}
    for _,part in ipairs(builderConfig.gunParts) do
      local imageSize = root.imageSize(config.animationParts[part])
      construct(config.animationCustom.animatedParts.parts, part, "properties")

      imageOffset = vec2.add(imageOffset, {imageSize[1] / 2, 0})
      config.animationCustom.animatedParts.parts[part].properties.offset = {config.baseOffset[1] + imageOffset[1] / 8, config.baseOffset[2]}
      partImagePositions[part] = copy(imageOffset)
      imageOffset = vec2.add(imageOffset, {imageSize[1] / 2, 0})
    end
    config.muzzleOffset = vec2.add(config.baseOffset, vec2.add(config.muzzleOffset or {0,0}, vec2.div(imageOffset, 8)))
  end

  -- elemental fire sounds
  if config.fireSounds then
    construct(config, "animationCustom", "sounds", "fire")
    local sound = randomFromList(config.fireSounds, seed, "fireSound")
    config.animationCustom.sounds.fire = type(sound) == "table" and sound or { sound }
  end

  -- build inventory icon
  if not config.inventoryIcon and config.animationParts then
    config.inventoryIcon = jarray()
    local parts = builderConfig.iconDrawables or {}
    for _,partName in pairs(parts) do
      local drawable = {
        image = config.animationParts[partName] .. config.paletteSwaps,
        position = partImagePositions[partName]
      }
      table.insert(config.inventoryIcon, drawable)
    end
  end

  -- populate tooltip fields
  config.tooltipFields = {}
  local fireTime = parameters.primaryAbility.fireTime or config.primaryAbility.fireTime or 1.0
  local baseDps = parameters.primaryAbility.baseDps or config.primaryAbility.baseDps or 0
  local energyUsage = parameters.primaryAbility.energyUsage or config.primaryAbility.energyUsage or 0
  config.tooltipFields.levelLabel = util.round(configParameter("level", 1), 1)
  config.tooltipFields.dpsLabel = util.round(baseDps * config.damageLevelMultiplier, 1)
  config.tooltipFields.speedLabel = util.round(1 / fireTime, 1)
  config.tooltipFields.damagePerShotLabel = util.round(baseDps * fireTime * config.damageLevelMultiplier, 1)
  config.tooltipFields.energyPerShotLabel = util.round(energyUsage * fireTime, 1)
  if elementalType ~= "physical" then
    config.tooltipFields.damageKindImage = "/interface/elements/"..elementalType..".png"
  end
  if config.primaryAbility then
    config.tooltipFields.primaryAbilityTitleLabel = "Осн. атака:"
    config.tooltipFields.primaryAbilityLabel = config.primaryAbility.name or "unknown"
  end
  if config.altAbility then
    config.tooltipFields.altAbilityTitleLabel = "Способность:"
    config.tooltipFields.altAbilityLabel = config.altAbility.name or "unknown"
  end

  -- set price
  config.price = (config.price or 0) * root.evalFunction("itemLevelPriceMultiplier", configParameter("level", 1))

  return config, parameters
end

function scaleConfig(ratio, value)
  if type(value) == "table" then
    return util.lerp(ratio, value[1], value[2])
  else
    return value
  end
end


text:
package com.darkhouse.gdefence.Level.Path;

import com.badlogic.gdx.graphics.Texture;
import com.darkhouse.gdefence.GDefence;
import com.darkhouse.gdefence.Level.Mob.Way;

public class Grass extends MapTile{
    private int id;

    public Grass(int id) {
        this.id = id;
//        initTexture();
    }

    @Override
    public void initTexture() {
        switch (id){
            case 0:setRegion(GDefence.getInstance().assetLoader.get("Path/grass.png", Texture.class)); break;
            case 1:setRegion(GDefence.getInstance().assetLoader.get("Path/sand.png", Texture.class)); break;
            case 2:setRegion(GDefence.getInstance().assetLoader.get("Path/sand2.png", Texture.class)); break;
            case 3:setRegion(GDefence.getInstance().assetLoader.get("Path/neotile.png", Texture.class)); break;
        }

    }

    @Override
    public boolean isBuildable() {
        return true;
    }

}


text:
from ncclient.xml_ import to_ele, new_ele
from netaddr import IPAddress, IPNetwork

from netman.adapters.switches.juniper.base import first, Juniper, Update, one_interface, parse_range, to_range, \
    first_text
from netman.adapters.switches.juniper.qfx_copper import JuniperQfxCopperCustomStrategies
from netman.core.objects.exceptions import BadVlanName, BadVlanNumber, VlanAlreadyExist, UnknownVlan, IPAlreadySet, \
    UnknownIP, AccessVlanNotSet, UnknownInterface, VrrpDoesNotExistForVlan
from netman.core.objects.vrrp_group import VrrpGroup

IRB = "irb"
PREEMPT_HOLD_TIME = 60

class MxJuniper(Juniper):
    def unset_interface_access_vlan(self, interface_id):
        config = self.query(one_interface(interface_id))
        if len(config.xpath("data/configuration/interfaces/interface")) < 1:
            raise UnknownInterface(interface_id)

        if len(config.xpath("data/configuration/interfaces/interface/unit/family/bridge/vlan-id")) < 1:
            raise AccessVlanNotSet(interface_id)

        update = Update()
        update.add_interface(self.custom_strategies.interface_update(interface_id, "0", [to_ele('<vlan-id operation="delete" />')]))
        self._push(update)

    def set_interface_state(self, interface_id, state):
        raise NotImplementedError()

    def unset_interface_state(self, interface_id):
        raise NotImplementedError()

    def set_interface_auto_negotiation_state(self, interface_id, negotiation_state):
        raise NotImplementedError()

    def unset_interface_auto_negotiation_state(self, interface_id):
        raise NotImplementedError()

    def set_interface_native_vlan(self, interface_id, vlan):
        raise NotImplementedError()

    def unset_interface_native_vlan(self, interface_id):
        raise NotImplementedError()

    def reset_interface(self, interface_id):
        raise NotImplementedError()

    def get_vlan_interfaces(self, vlan_number):
        raise NotImplementedError()

    def add_ip_to_vlan(self, vlan_number, ip_network):
        config = self.query(self.custom_strategies.one_vlan_by_vlan_id(vlan_number), one_interface_vlan(vlan_number))
        self.custom_strategies.vlan_node(config, vlan_number)

        update = Update()
        self.custom_strategies.add_update_vlan_interface(update, vlan_number, name=None)

        for addr_node in config.xpath("data/configuration/interfaces/interface/unit/family/inet/address/name"):
            address = IPNetwork(addr_node.text)
            if ip_network in address:
                raise IPAlreadySet(ip_network)

        update.add_interface(irb_address_update(vlan_number, ip_network))

        self._push(update)

    def remove_ip_from_vlan(self, vlan_number, ip_network):
        config = self.query(one_interface_vlan(vlan_number))

        if len(config.xpath("data/configuration/interfaces/interface/unit")) < 1:
            raise UnknownVlan(vlan_number)

        for addr_node in config.xpath("data/configuration/interfaces/interface/unit/family/inet/address/name"):
            address = IPNetwork(addr_node.text)
            if ip_network in address:
                update = Update()
                update.add_interface(irb_address_update(vlan_number, ip_network, operation="delete"))

                self._push(update)
                return

        raise UnknownIP(ip_network)

    def set_vlan_access_group(self, vlan_number, direction, name):
        raise NotImplementedError()

    def unset_vlan_access_group(self, vlan_number, direction):
        raise NotImplementedError()

    def set_vlan_vrf(self, vlan_number, vrf_name):
        raise NotImplementedError()

    def unset_vlan_vrf(self, vlan_number):
        raise NotImplementedError()

    def set_interface_description(self, interface_id, description):
        raise NotImplementedError()

    def unset_interface_description(self, interface_id):
        raise NotImplementedError()

    def edit_interface_spanning_tree(self, interface_id, edge=None):
        raise NotImplementedError()

    def add_bond(self, number):
        raise NotImplementedError()

    def remove_bond(self, number):
        raise NotImplementedError()

    def get_bond(self, number):
        raise NotImplementedError()

    def get_bonds(self):
        raise NotImplementedError()

    def add_interface_to_bond(self, interface, bond_number):
        raise NotImplementedError()

    def remove_interface_from_bond(self, interface):
        raise NotImplementedError()

    def set_bond_link_speed(self, number, speed):
        raise NotImplementedError()

    def set_bond_description(self, number, description):
        raise NotImplementedError()

    def unset_bond_description(self, number):
        raise NotImplementedError()

    def set_bond_native_vlan(self, number, vlan):
        raise NotImplementedError()

    def unset_bond_native_vlan(self, number):
        raise NotImplementedError()

    def edit_bond_spanning_tree(self, number, edge=None):
        raise NotImplementedError()

    def add_vrrp_group(self, vlan_number, group_id, ips=None, priority=None, hello_interval=None, dead_interval=None,
                       track_id=None, track_decrement=None):
        config = self.query(one_interface_vlan(vlan_number))

        if len(config.xpath("data/configuration/interfaces/interface/unit")) < 1:
            raise UnknownVlan(vlan_number)

        adresses = [IPNetwork(addr_node.text) for addr_node in config.xpath(
            "data/configuration/interfaces/interface/unit/family/inet/address/name")]

        parent_address = self._get_address_that_contains_all_ips(adresses, ips)

        vrrp_node = to_ele("""
            <vrrp-group>
              <name>{group_id}</name>
              <priority>{priority}</priority>
              <preempt>
                <hold-time>{preempt_hold_time}</hold-time>
              </preempt>
              <accept-data/>
              <authentication-type>simple</authentication-type>
              <authentication-key>{auth}</authentication-key>
              <track>
                <route>
                  <route_address>{tracking}</route_address>
                  <routing-instance>default</routing-instance>
                  <priority-cost>{tracking_decrement}</priority-cost>
                </route>
              </track>
            </vrrp-group>""".format(vlan_number=vlan_number,
                                    parent_address=parent_address,
                                    group_id=group_id,
                                    vip=ips[0],
                                    preempt_hold_time=PREEMPT_HOLD_TIME,
                                    priority=priority,
                                    auth="VLAN{}".format(vlan_number),
                                    tracking=track_id,
                                    tracking_decrement=track_decrement))

        for ip in ips:
            vrrp_node.append(to_ele("<virtual-address>{}</virtual-address>".format(ip)))

        update = Update()
        update.add_interface(irb_address_update(vlan_number, parent_address, children=[vrrp_node]))

        self._push(update)

    def _get_address_that_contains_all_ips(self, subnets, ips):
        def subnet_contains_all_ips(ips, subnet):
            return all(ip in subnet for ip in ips)

        subnet_found = None
        for subnet in subnets:
            if subnet_contains_all_ips(ips, subnet):
                subnet_found = subnet

        if not subnet_found:
            raise UnknownIP(",".join(map(str, ips)))

        return subnet_found

    def remove_vrrp_group(self, vlan_id, group_id):
        config = self.query(one_interface_vlan(vlan_id))

        if len(config.xpath("data/configuration/interfaces/interface/unit")) < 1:
            raise UnknownVlan(vlan_id)

        address_node = first(config.xpath("data/configuration/interfaces/interface/unit/family"
                                          "/inet/address/vrrp-group/name[text()=\"{}\"]/../..".format(group_id)))

        if address_node is None:
            raise VrrpDoesNotExistForVlan(vlan=vlan_id, vrrp_group_id=group_id)

        vrrp_node = to_ele("""
            <vrrp-group operation="delete">
              <name>{group_id}</name>
            </vrrp-group>""".format(group_id=group_id))

        update = Update()
        update.add_interface(irb_address_update(vlan_id, first_text(address_node.xpath("name")), children=[vrrp_node]))

        self._push(update)

    def add_dhcp_relay_server(self, vlan_number, ip_address):
        raise NotImplementedError()

    def remove_dhcp_relay_server(self, vlan_number, ip_address):
        raise NotImplementedError()

    def set_interface_lldp_state(self, interface_id, enabled):
        raise NotImplementedError()

    def set_vlan_arp_routing_state(self, vlan_number, state):
        raise NotImplementedError()

    def set_vlan_icmp_redirects_state(self, vlan_number, state):
        config = self.query(self.custom_strategies.one_vlan_by_vlan_id(vlan_number),
                            one_interface_vlan(vlan_number, extra_path="""<family>
                                                                            <inet>
                                                                              <no-redirects />
                                                                            </inet>
                                                                          </family>"""))
        self.custom_strategies.vlan_node(config, vlan_number)

        no_redirects_node = first(config.xpath("data/configuration/interfaces/interface/unit/family/inet/no-redirects"))

        update = Update()

        if no_redirects_node is None and state is False:
            self.custom_strategies.add_update_vlan_interface(update, vlan_number, name=None)
            update.add_interface(no_redirects(vlan_number=vlan_number))
            self._push(update)
        elif no_redirects_node is not None and state is True:
            update.add_interface(no_redirects(vlan_number=vlan_number, operation="delete"))
            self._push(update)

    def set_vlan_unicast_rpf_mode(self, vlan_number, mode):
        raise NotImplementedError()

    def unset_vlan_unicast_rpf_mode(self, vlan_number):
        raise NotImplementedError()

    def get_versions(self):
        raise NotImplementedError()

    def set_interface_mtu(self, interface_id, size):
        raise NotImplementedError()

    def unset_interface_mtu(self, interface_id):
        raise NotImplementedError()

    def set_bond_mtu(self, number, size):
        raise NotImplementedError()

    def unset_bond_mtu(self, number):
        raise NotImplementedError()

def netconf(switch_descriptor):
    return MxJuniper(switch_descriptor, custom_strategies=JuniperMXCustomStrategies())

class JuniperMXCustomStrategies(JuniperQfxCopperCustomStrategies):
    def get_port_mode_node_in_inteface_node(self, interface_node):
        return interface_node.xpath("unit/family/bridge/interface-mode")

    def get_vlan_member_update_element(self, vlan):
        return to_ele("<vlan-id-list>{}</vlan-id-list>".format(vlan))

    def add_update_vlans(self, update, number, name):
        update.add_vlan(self.vlan_update(number, name), "bridge-domains")

    def add_update_vlan_interface(self, update, number, name):
        update.add_vlan(self.vlan_interface_update(number, name), "bridge-domains")

    def remove_update_vlans(self, update, vlan_name):
        update.add_vlan(self.vlan_removal(vlan_name), "bridge-domains")

    def all_vlans(self):
        return new_ele("bridge-domains")

    def one_vlan_by_vlan_id(self, vlan_id):
        def m():
            return to_ele("""
                <bridge-domains>
                    <domain>
                        <vlan-id>{}</vlan-id>
                    </domain>
                </bridge-domains>
            """.format(vlan_id))

        return m

    def vlan_update(self, number, description):
        content = to_ele("""
            <domain>
                <name>VLAN{0}</name>
                <vlan-id>{0}</vlan-id>
            </domain>
        """.format(number))

        if description is not None:
            content.append(to_ele("<description>{}</description>".format(description)))
        return content

    def vlan_interface_update(self, vlan_id, description):
        vlan_node = self.vlan_update(vlan_id, description)
        vlan_node.append(to_ele("<routing-interface>irb.{}</routing-interface>".format(vlan_id)))
        return vlan_node

    def vlan_removal(self, name):
        return to_ele("""
        <domain operation="delete">
            <name>{}</name>
        </domain>""".format(name))

    def vlan_nodes(self, config):
        return config.xpath("data/configuration/bridge-domains/domain")

    def vlan_node(self, config, number):
        vlan_node = first(config.xpath("data/configuration/bridge-domains/domain/vlan-id[text()=\"{}\"]/.."
                                       .format(number)))

        if vlan_node is None:
            raise UnknownVlan(number)
        return vlan_node

    def manage_update_vlan_exception(self, message, number):
        if "being used by" in message:
            raise VlanAlreadyExist(number)
        elif "not within range" in message:
            if message.startswith("Value"):
                raise BadVlanNumber()
        elif "Must be a string" in message:
            raise BadVlanName()

    def interface_update(self, name, unit, attributes=None, vlan_members=None):
        content = to_ele("""
            <interface>
                <name>{interface}</name>
                <unit>
                    <name>{unit}</name>
                    <family>
                        <bridge>
                        </bridge>
                    </family>
                </unit>
            </interface>
            """.format(interface=name, unit=unit))
        bridge = first(content.xpath("//bridge"))

        for attribute in (attributes if attributes is not None else []):
            bridge.append(attribute)

        if vlan_members:
            for attribute in vlan_members:
                bridge.append(attribute)

        return content

    def get_l3_interface(self, vlan_node):
        if_name_node = first(vlan_node.xpath("routing-interface"))
        if if_name_node is not None:
            return if_name_node.text.split(".")
        else:
            return None, None

    def list_vlan_members(self, interface_node, config):
        vlans = set()

        vlan_id_list = interface_node.xpath("unit/family/bridge/vlan-id-list") + interface_node.xpath("unit/family/bridge/vlan-id")

        for members in vlan_id_list:
            vlans = vlans.union(parse_range(members.text))

        return sorted(vlans)

    def update_vlan_members(self, interface_node, vlan_members, vlan):
        if interface_node is not None:
            if interface_node.xpath("unit/family/bridge/vlan-id-list"):
                vlan_members.append(to_ele('<vlan-id-list operation="delete"/>'))

        vlan_members.append(to_ele("<vlan-id>{}</vlan-id>".format(vlan)))

    def craft_members_modification_to_remove_vlan(self, interface_node, vlan_name, number):
        members_modifications = []

        vlan_id_list = interface_node.xpath("unit/family/bridge/vlan-id-list") + interface_node.xpath("unit/family/bridge/vlan-id")

        for vlan_members_node in vlan_id_list:
            if vlan_members_node.text == vlan_name:
                members_modifications.append(to_ele("<{tag} operation=\"delete\">{id}</{tag}>".format(
                    tag=vlan_members_node.tag,
                    id=vlan_members_node.text)
                ))
            else:
                vlan_list = parse_range(vlan_members_node.text)
                if number in vlan_list:
                    members_modifications.append(to_ele("<vlan-id-list operation=\"delete\">{}</vlan-id-list>".format(vlan_members_node.text)))

                    below = vlan_list[:vlan_list.index(number)]
                    if len(below) > 0:
                        members_modifications.append(to_ele("<vlan-id-list>{}</vlan-id-list>".format(to_range(below))))

                    above = vlan_list[vlan_list.index(number) + 1:]
                    if len(above) > 0:
                        members_modifications.append(to_ele("<vlan-id-list>{}</vlan-id-list>".format(to_range(above))))

        return members_modifications

    def interface_vlan_members_update(self, name, unit, members_modification):
        content = to_ele("""
        <interface>
            <name>{}</name>
            <unit>
                <name>{}</name>
                <family>
                    <bridge/>
                </family>
            </unit>
        </interface>
        """.format(name, unit))

        vlan_node = first(content.xpath("//bridge"))
        for m in members_modification:
            vlan_node.append(m)

        return content

    def parse_vrrp_groups(self, interface_unit):
        return [_to_vrrp_group(vrrp_node)
                for vrrp_node in interface_unit.xpath("family/inet/address/vrrp-group")]

    def parse_icmp_redirects(self, interface_unit):
        return first(interface_unit.xpath("family/inet/no-redirects")) is None

    def get_delete_trunk_vlan_element(self):
        return to_ele('<vlan-id-list operation="delete" />')

    def get_delete_vlan_element(self):
        return to_ele('<vlan-id operation="delete" />')

    def parse_mac_address_table(self, mac_table):
        raise NotImplementedError()

def one_interface_vlan(vlan_number, extra_path=""):
    def m():
        return to_ele("""
            <interfaces>
                <interface>
                    <name>{interface}</name>
                    <unit>
                        <name>{unit}</name>
                        {extra_path}
                    </unit>
                </interface>
            </interfaces>
        """.format(interface=IRB, unit=vlan_number, extra_path=extra_path))

    return m

def irb_address_update(vlan_number, ip_network, operation=None, children=None):
    content = to_ele("""
        <interface>
            <name>irb</name>
            <unit>
              <name>{vlan_number}</name>
              <family>
                <inet>
                  <address{operation}>
                    <name>{ip_network}</name>
                  </address>
                </inet>
              </family>
            </unit>
        </interface>""".format(vlan_number=vlan_number,
                               ip_network=ip_network,
                               operation=' operation="{}"'.format(operation) if operation else ""))

    if children is not None:
        address = first(content.xpath("//address"))
        for child in children:
            address.append(child)

    return content

def no_redirects(vlan_number, operation=None):
    return to_ele("""
        <interface>
            <name>irb</name>
            <unit>
              <name>{vlan_number}</name>
              <family>
                <inet>
                  <no-redirects{operation} />
                </inet>
              </family>
            </unit>
        </interface>""".format(vlan_number=vlan_number,
                               operation=' operation="{}"'.format(operation) if operation else ""))

def _to_vrrp_group(vrrp_node):
    priority = first_text(vrrp_node.xpath("priority"))
    track_decrement = first_text(vrrp_node.xpath("track/route/priority-cost"))

    return VrrpGroup(
        id=int(first_text(vrrp_node.xpath("name"))),
        ips=[IPAddress(ip.text) for ip in vrrp_node.xpath("virtual-address")],
        priority=int(priority) if priority is not None else None,
        track_id=first_text(vrrp_node.xpath("track/route/route_address")),
        track_decrement=int(track_decrement) if track_decrement is not None else None,
    )


text:
import httplib
import time
import json

from pyleanrtm.error import InvalidArgumentException, AppAccessDisabledException, AppNotFoundOrDisabledException

class RouteRecord(object):
    def __init__(self, addr, ttl, secondary=None):
        self.server = addr
        self.valid_until = time.time() + ttl
        self.secondary = secondary

    def is_valid(self):
        return self.valid_until >= time.time()

class RouteManager(object):
    def __init__(self, app_id, region='cn'):
        if region == 'cn':
            self.host = 'router.g0.push.avoscloud.com'
        elif region == 'us':
            self.host = 'router.a0.push.avoscloud.com'
        else:
            raise InvalidArgumentException('unsupported region')
        self.app_id = app_id
        self.cached_record = None

    def fetch(self):
        if self.cached_record:
            return self.cached_record

        path = '/v1/route?&secure=1&appId=%s' % self.app_id
        conn = httplib.HTTPConnection(self.host)
        conn.request('GET', path)
        r = conn.getresponse()
        if r.status == 200:
            route = json.loads(r.read())
            return RouteRecord(route['server'], route['ttl'], route['secondary'])
        elif r.status == 404:
            raise AppNotFoundOrDisabledException(self.app_id)
        elif r.status == 403:
            raise AppAccessDisabledException(self.app_id)

    def cache(self, record, secondary):
        if secondary:
            record.addr = record.secondary
        self.cached_record = record

    def invalid_cache(self):
        self.cached_record = None


text:
bool
FileHeader::Allocate(PersistentBitmap *freeMap, int fileSize)
{
    numBytes = fileSize;
    numSectors  = divRoundUp(fileSize, SectorSize);
    if (freeMap->NumClear() < numSectors)
	return FALSE;		// not enough space

    for (int i = 0; i < numSectors; i++) {
	dataSectors[i] = freeMap->FindAndSet();
	// since we checked that there was enough free space,
	// we expect this to succeed
	ASSERT(dataSectors[i] >= 0);
    }
    return TRUE;
}

//----------------------------------------------------------------------
// FileHeader::Deallocate
// 	De-allocate all the space allocated for data blocks for this file.
//
//	"freeMap" is the bit map of free disk sectors
//----------------------------------------------------------------------

void
FileHeader::Deallocate(PersistentBitmap *freeMap)
{
    for (int i = 0; i < numSectors; i++) {
	ASSERT(freeMap->Test((int) dataSectors[i]));  // ought to be marked!
	freeMap->Clear((int) dataSectors[i]);
    }
}

//----------------------------------------------------------------------
// FileHeader::FetchFrom
// 	Fetch contents of file header from disk.
//
//	"sector" is the disk sector containing the file header
//----------------------------------------------------------------------

void
FileHeader::FetchFrom(int sector)
{
    kernel->synchDisk->ReadSector(sector, (char *)this);
}

//----------------------------------------------------------------------
// FileHeader::WriteBack
// 	Write the modified contents of the file header back to disk.
//
//	"sector" is the disk sector to contain the file header
//----------------------------------------------------------------------

void
FileHeader::WriteBack(int sector)
{
    kernel->synchDisk->WriteSector(sector, (char *)this);
}

//----------------------------------------------------------------------
// FileHeader::ByteToSector
// 	Return which disk sector is storing a particular byte within the file.
//      This is essentially a translation from a virtual address (the
//	offset in the file) to a physical address (the sector where the
//	data at the offset is stored).
//
//	"offset" is the location within the file of the byte in question
//----------------------------------------------------------------------

int
FileHeader::ByteToSector(int offset)
{
    return(dataSectors[offset / SectorSize]);
}

//----------------------------------------------------------------------
// FileHeader::FileLength
// 	Return the number of bytes in the file.
//----------------------------------------------------------------------

int
FileHeader::FileLength()
{
    return numBytes;
}

//----------------------------------------------------------------------
// FileHeader::Print
// 	Print the contents of the file header, and the contents of all
//	the data blocks pointed to by the file header.
//----------------------------------------------------------------------

void
FileHeader::Print()
{
    int i, j, k;
    char *data = new char[SectorSize];

    printf("FileHeader contents.  File size: %d.  File blocks:\n", numBytes);
    for (i = 0; i < numSectors; i++)
	printf("%d ", dataSectors[i]);
    printf("\nFile contents:\n");
    for (i = k = 0; i < numSectors; i++) {
	kernel->synchDisk->ReadSector(dataSectors[i], data);
        for (j = 0; (j < SectorSize) && (k < numBytes); j++, k++) {
	    if ('\040' <= data[j] && data[j] <= '\176')   // isprint(data[j])
		printf("%c", data[j]);
            else
		printf("\\%x", (unsigned char)data[j]);
	}
        printf("\n");
    }
    delete [] data;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.12">
	<MobileDeviceCommandBarContent>
		<xr:Item>
			<xr:Presentation/>
			<xr:CheckState>0</xr:CheckState>
			<xr:Value xsi:type="xs:string">КоманднаяПанель</xr:Value>
		</xr:Item>
	</MobileDeviceCommandBarContent>
	<AutoCommandBar name="Форма_КоманднаяПанель" id="-1">
		<Autofill>false</Autofill>
	</AutoCommandBar>
	<Events>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
	</Events>
	<ChildItems>
		<UsualGroup name="ГруппаПользовательскихНастроек" id="27">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа пользовательских настроек</v8:content>
				</v8:item>
			</Title>
			<Group>Vertical</Group>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаПользовательскихНастроекРасширеннаяПодсказка" id="28"/>
		</UsualGroup>
		<CommandBar name="КоманднаяПанель" id="29">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Командная панель</v8:content>
				</v8:item>
			</Title>
			<CommandSource>Form</CommandSource>
			<ExtendedTooltip name="КоманднаяПанельРасширеннаяПодсказка" id="30"/>
		</CommandBar>
		<Table name="Список" id="1">
			<Representation>List</Representation>
			<CommandBarLocation>None</CommandBarLocation>
			<SkipOnInput>false</SkipOnInput>
			<DefaultItem>true</DefaultItem>
			<UseAlternationRowColor>true</UseAlternationRowColor>
			<FileDragMode>AsFile</FileDragMode>
			<DataPath>Список</DataPath>
			<RowPictureDataPath>Список.DefaultPicture</RowPictureDataPath>
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Список</v8:content>
				</v8:item>
			</Title>
			<AutoRefresh>false</AutoRefresh>
			<AutoRefreshPeriod>60</AutoRefreshPeriod>
			<Period>
				<v8:variant xsi:type="v8:StandardPeriodVariant">Custom</v8:variant>
				<v8:startDate>0001-01-01T00:00:00</v8:startDate>
				<v8:endDate>0001-01-01T00:00:00</v8:endDate>
			</Period>
			<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
			<RestoreCurrentRow>false</RestoreCurrentRow>
			<TopLevelParent xsi:nil="true"/>
			<ShowRoot>true</ShowRoot>
			<AllowRootChoice>false</AllowRootChoice>
			<UpdateOnDataChange>Auto</UpdateOnDataChange>
			<UserSettingsGroup>ГруппаПользовательскихНастроек</UserSettingsGroup>
			<ContextMenu name="Список_КонтекстноеМеню" id="2"/>
			<AutoCommandBar name="Список_КоманднаяПанель" id="3"/>
			<ExtendedTooltip name="СписокExtendedTooltip" id="10"/>
			<SearchStringAddition name="СписокСтрокаПоиска" id="31">
				<AdditionSource>
					<Item>Список</Item>
					<Type>SearchStringRepresentation</Type>
				</AdditionSource>
				<ContextMenu name="СписокСтрокаПоискаКонтекстноеМеню" id="32"/>
				<ExtendedTooltip name="СписокСтрокаПоискаРасширеннаяПодсказка" id="33"/>
			</SearchStringAddition>
			<ViewStatusAddition name="СписокСостояниеПросмотра" id="34">
				<AdditionSource>
					<Item>Список</Item>
					<Type>ViewStatusRepresentation</Type>
				</AdditionSource>
				<ContextMenu name="СписокСостояниеПросмотраКонтекстноеМеню" id="35"/>
				<ExtendedTooltip name="СписокСостояниеПросмотраРасширеннаяПодсказка" id="36"/>
			</ViewStatusAddition>
			<SearchControlAddition name="СписокУправлениеПоиском" id="37">
				<AdditionSource>
					<Item>Список</Item>
					<Type>SearchControl</Type>
				</AdditionSource>
				<ContextMenu name="СписокУправлениеПоискомКонтекстноеМеню" id="38"/>
				<ExtendedTooltip name="СписокУправлениеПоискомРасширеннаяПодсказка" id="39"/>
			</SearchControlAddition>
			<ChildItems>
				<LabelField name="Наименование" id="4">
					<DataPath>Список.Наименование</DataPath>
					<DefaultItem>true</DefaultItem>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Наименование</v8:content>
						</v8:item>
					</Title>
					<Width>30</Width>
					<HorizontalStretch>true</HorizontalStretch>
					<ContextMenu name="Наименование_КонтекстноеМеню" id="5"/>
					<ExtendedTooltip name="НаименованиеExtendedTooltip" id="11"/>
				</LabelField>
				<LabelField name="ИмяПользователя" id="6">
					<DataPath>Список.ИмяПользователя</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Имя пользователя</v8:content>
						</v8:item>
					</Title>
					<Width>20</Width>
					<ContextMenu name="ИмяПользователя_КонтекстноеМеню" id="7"/>
					<ExtendedTooltip name="ИмяПользователяExtendedTooltip" id="12"/>
				</LabelField>
				<LabelField name="АдресЭлектроннойПочты" id="8">
					<DataPath>Список.АдресЭлектроннойПочты</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Адрес электронной почты</v8:content>
						</v8:item>
					</Title>
					<Width>20</Width>
					<ContextMenu name="АдресЭлектроннойПочты_КонтекстноеМеню" id="9"/>
					<ExtendedTooltip name="АдресЭлектроннойПочтыExtendedTooltip" id="13"/>
				</LabelField>
				<LabelField name="ВладелецУчетнойЗаписи" id="43">
					<DataPath>Список.ВладелецУчетнойЗаписи</DataPath>
					<ContextMenu name="ВладелецУчетнойЗаписиКонтекстноеМеню" id="44"/>
					<ExtendedTooltip name="ВладелецУчетнойЗаписиРасширеннаяПодсказка" id="45"/>
				</LabelField>
				<LabelField name="Ссылка" id="24">
					<DataPath>Список.Ссылка</DataPath>
					<UserVisible>
						<xr:Common>false</xr:Common>
					</UserVisible>
					<ContextMenu name="СсылкаКонтекстноеМеню" id="25"/>
					<ExtendedTooltip name="СсылкаРасширеннаяПодсказка" id="26"/>
				</LabelField>
			</ChildItems>
		</Table>
		<UsualGroup name="Отборы" id="49">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Отборы</v8:content>
				</v8:item>
			</Title>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ОтборыРасширеннаяПодсказка" id="50"/>
			<ChildItems>
				<CheckBoxField name="ПоказыватьПерсональныеУчетныеЗаписиПользователей" id="40">
					<DataPath>ПоказыватьПерсональныеУчетныеЗаписиПользователей</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Показывать персональные</v8:content>
						</v8:item>
					</Title>
					<TitleLocation>Right</TitleLocation>
					<CheckBoxType>Auto</CheckBoxType>
					<ContextMenu name="ПоказыватьПерсональныеУчетныеЗаписиПользователейКонтекстноеМеню" id="41"/>
					<ExtendedTooltip name="ПоказыватьПерсональныеУчетныеЗаписиПользователейРасширеннаяПодсказка" id="42"/>
					<Events>
						<Event name="OnChange">ПоказыватьПерсональныеУчетныеЗаписиПользователейПриИзменении</Event>
					</Events>
				</CheckBoxField>
				<CheckBoxField name="ПоказыватьНедействительные" id="46">
					<DataPath>ПоказыватьНедействительные</DataPath>
					<TitleLocation>Right</TitleLocation>
					<CheckBoxType>Auto</CheckBoxType>
					<ContextMenu name="ПоказыватьНедействительныеКонтекстноеМеню" id="47"/>
					<ExtendedTooltip name="ПоказыватьНедействительныеРасширеннаяПодсказка" id="48"/>
					<Events>
						<Event name="OnChange">ПоказыватьНедействительныеПриИзменении</Event>
					</Events>
				</CheckBoxField>
			</ChildItems>
		</UsualGroup>
	</ChildItems>
	<Attributes>
		<Attribute name="Список" id="1">
			<Type>
				<v8:Type>cfg:DynamicList</v8:Type>
			</Type>
			<MainAttribute>true</MainAttribute>
			<UseAlways>
				<Field>~Список.Ref</Field>
				<Field>Список.Ссылка</Field>
			</UseAlways>
			<Settings xsi:type="DynamicList">
				<ManualQuery>true</ManualQuery>
				<DynamicDataRead>true</DynamicDataRead>
				<QueryText>ВЫБРАТЬ
	СправочникУчетныеЗаписиЭлектроннойПочты.Ссылка КАК Ссылка,
	СправочникУчетныеЗаписиЭлектроннойПочты.ПометкаУдаления КАК ПометкаУдаления,
	СправочникУчетныеЗаписиЭлектроннойПочты.Наименование КАК Наименование,
	СправочникУчетныеЗаписиЭлектроннойПочты.SMTPАутентификация КАК SMTPАутентификация,
	СправочникУчетныеЗаписиЭлектроннойПочты.АдресЭлектроннойПочты КАК АдресЭлектроннойПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.ВремяОжидания КАК ВремяОжидания,
	СправочникУчетныеЗаписиЭлектроннойПочты.ИмяПользователя КАК ИмяПользователя,
	СправочникУчетныеЗаписиЭлектроннойПочты.ИспользоватьБезопасныйВходНаСерверВходящейПочты КАК ИспользоватьБезопасныйВходНаСерверВходящейПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.ИспользоватьБезопасныйВходНаСерверИсходящейПочты КАК ИспользоватьБезопасныйВходНаСерверИсходящейПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.ИспользоватьДляОтправки КАК ИспользоватьДляОтправки,
	СправочникУчетныеЗаписиЭлектроннойПочты.ИспользоватьДляПолучения КАК ИспользоватьДляПолучения,
	СправочникУчетныеЗаписиЭлектроннойПочты.ИспользоватьЗащищенноеСоединениеДляВходящейПочты КАК ИспользоватьЗащищенноеСоединениеДляВходящейПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.ИспользоватьЗащищенноеСоединениеДляИсходящейПочты КАК ИспользоватьЗащищенноеСоединениеДляИсходящейПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.ОставлятьКопииСообщенийНаСервере КАК ОставлятьКопииСообщенийНаСервере,
	СправочникУчетныеЗаписиЭлектроннойПочты.ПериодХраненияСообщенийНаСервере КАК ПериодХраненияСообщенийНаСервере,
	СправочникУчетныеЗаписиЭлектроннойПочты.Пользователь КАК Пользователь,
	СправочникУчетныеЗаписиЭлектроннойПочты.ПользовательSMTP КАК ПользовательSMTP,
	СправочникУчетныеЗаписиЭлектроннойПочты.ПортСервераВходящейПочты КАК ПортСервераВходящейПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.ПортСервераИсходящейПочты КАК ПортСервераИсходящейПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.ПротоколВходящейПочты КАК ПротоколВходящейПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.СерверВходящейПочты КАК СерверВходящейПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.СерверИсходящейПочты КАК СерверИсходящейПочты,
	СправочникУчетныеЗаписиЭлектроннойПочты.СпособPOP3Аутентификации КАК СпособPOP3Аутентификации,
	СправочникУчетныеЗаписиЭлектроннойПочты.СпособSMTPАутентификации КАК СпособSMTPАутентификации,
	СправочникУчетныеЗаписиЭлектроннойПочты.ТребуетсяВходНаСерверПередОтправкой КАК ТребуетсяВходНаСерверПередОтправкой,
	СправочникУчетныеЗаписиЭлектроннойПочты.УдалитьВПредставлениеВключатьИмяПользователя КАК УдалитьВПредставлениеВключатьИмяПользователя,
	СправочникУчетныеЗаписиЭлектроннойПочты.УдалитьОтветственныйЗаОбработкуПисем КАК УдалитьОтветственныйЗаОбработкуПисем,
	СправочникУчетныеЗаписиЭлектроннойПочты.УдалитьПароль КАК УдалитьПароль,
	СправочникУчетныеЗаписиЭлектроннойПочты.УдалитьПарольSMTP КАК УдалитьПарольSMTP,
	СправочникУчетныеЗаписиЭлектроннойПочты.ОтправлятьСкрытыеКопииПисемНаЭтотАдрес КАК ОтправлятьСкрытыеКопииПисемНаЭтотАдрес,
	СправочникУчетныеЗаписиЭлектроннойПочты.ВладелецУчетнойЗаписи КАК ВладелецУчетнойЗаписи,
	СправочникУчетныеЗаписиЭлектроннойПочты.Предопределенный КАК Предопределенный,
	СправочникУчетныеЗаписиЭлектроннойПочты.ИмяПредопределенныхДанных КАК ИмяПредопределенныхДанных,
	ЕСТЬNULL(Пользователи.Недействителен, ЛОЖЬ) КАК ВладелецНедействителен
ИЗ
	Справочник.УчетныеЗаписиЭлектроннойПочты КАК СправочникУчетныеЗаписиЭлектроннойПочты
		ЛЕВОЕ СОЕДИНЕНИЕ Справочник.Пользователи КАК Пользователи
		ПО СправочникУчетныеЗаписиЭлектроннойПочты.ВладелецУчетнойЗаписи = Пользователи.Ссылка</QueryText>
				<MainTable>Catalog.УчетныеЗаписиЭлектроннойПочты</MainTable>
				<ListSettings>
					<dcsset:filter>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>dfcece9d-5077-440b-b6b3-45a5cb4538eb</dcsset:userSettingID>
					</dcsset:filter>
					<dcsset:order>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>88619765-ccb3-46c6-ac52-38e9c992ebd4</dcsset:userSettingID>
					</dcsset:order>
					<dcsset:conditionalAppearance>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>b75fecce-942b-4aed-abc9-e6a02e460fb3</dcsset:userSettingID>
					</dcsset:conditionalAppearance>
					<dcsset:itemsViewMode>Normal</dcsset:itemsViewMode>
					<dcsset:itemsUserSettingID>911b6018-f537-43e8-a417-da56b22f9aec</dcsset:itemsUserSettingID>
				</ListSettings>
			</Settings>
		</Attribute>
		<Attribute name="ПоказыватьПерсональныеУчетныеЗаписиПользователей" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Показывать персональные учетные записи пользователей</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
		<Attribute name="ПоказыватьНедействительные" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Показывать недействительные</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
	</Attributes>
</Form>


text:
from modules.file.upload2web import Upload2web
from modules.file.upload import WARN_NO_SUCH_FILE
from core.moduleexception import ModuleException, ProbeException
from core.argparse import ArgumentParser
from core.argparse import SUPPRESS
import re, os
from core.utils import randstr

class Phpproxy(Upload2web):
    '''Install remote PHP proxy'''

    def _set_args(self):
        self.argparser.add_argument('rpath', help='Optional, upload as rpath', nargs='?')

        self.argparser.add_argument('-startpath', help='Upload in first writable subdirectory', metavar='STARTPATH', default='.')
        self.argparser.add_argument('-chunksize', type=int, default=1024, help=SUPPRESS)
        self.argparser.add_argument('-vector', choices = self.vectors.keys(), help=SUPPRESS)
        self.argparser.add_argument('-force', action='store_true')

    def _get_proxy_path(self):
        return os.path.join(self.modhandler.path_modules, 'net', 'external', 'phpproxy.php')

    def _prepare(self):

        proxy_path = self._get_proxy_path()

        if not self.args['rpath']:

            # If no rpath, set content and remote final filename as random
            try:
                content = open(proxy_path, 'r').read()
            except Exception, e:
                raise ProbeException(self.name,  '\'%s\' %s' % (self.args['lpath'], WARN_NO_SUCH_FILE))

            self.args['lpath'] = randstr(4) + '.php'
            self.args['content'] = content

        else:

            # Else, set lpath as proxy filename

            self.args['lpath'] = proxy_path
            self.args['content'] = None

        Upload2web._prepare(self)

    def _stringify_result(self):

        Upload2web._stringify_result(self)

        sess_filename = os.path.join(*(self.args['rpath'].split('/')[:-1] + [ 'sess_*']))

        self._output = """Php proxy installed, point your browser to %s?u=http://www.google.com .
Delete '%s' and '%s' at session end.""" % ( self.args['url'], self.args['rpath'], sess_filename )


text:
package com.github.osm.sax;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.github.osm.domain.MetaInfo;
import com.github.osm.domain.Node;
import com.github.osm.domain.OSM;
import com.github.osm.domain.OsmEntity.Type;
import com.github.osm.domain.Relation;
import com.github.osm.domain.Member;
import com.github.osm.domain.Way;

/**
 * An abstract event handler for OSM XML parsing events.
 */
public abstract class OsmSaxHandler extends DefaultHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(OsmSaxHandler.class);

    public static final String ENTITY_ATTR_ID = "id";

    public static final String ENTITY_ATTR_VERSION = "version";
    public static final String ENTITY_ATTR_CHANGESET = "changeset";
    public static final String ENTITY_ATTR_TIMESTAMP = "timestamp";
    public static final String ENTITY_ATTR_USER = "user";
    public static final String ENTITY_ATTR_USERID = "uid";

    public static final String META_ATTR_VISIBLE = "visible";

    public static final String TAG_ELEMENT = "tag";
    public static final String TAG_ATTR_KEY = "k";
    public static final String TAG_ATTR_VALUE = "v";

    public static final String NODE_ELEMENT = "node";
    public static final String NODE_ATTR_LAT = "lat";
    public static final String NODE_ATTR_LONG = "lon";

    public static final String WAY_ELEMENT = "way";

    public static final String WAY_ND_ELEMENT = "nd";
    public static final String WAY_ND_ATTR_REF = "ref";

    public static final String RELATION_ELEMENT = "relation";

    public static final String MEMBER_ELEMENT = "member";
    public static final String MEMBER_ATTR_TYPE = "type";
    public static final String MEMBER_ATTR_REF = "ref";
    public static final String MEMBER_ATTR_ROLE = "role";

    // Entity temp variables
    private long osmId;
    private MetaInfo metaInfo;
    private Map<String, String> tagsMap = new HashMap<>();

    private double latitude;
    private double longitude;

    private List<Long> nodeIds = new ArrayList<>();

    private List<Member> members = new ArrayList<>();

    // Constructors
    // ------------------------------------------------------------------------

    public OsmSaxHandler() {
        super();
    }

    // SAX DefaultHandler methods
    // ------------------------------------------------------------------------

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();

        LOGGER.info("Document parsing started ...");
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();

        LOGGER.info("Document parsing completed ...");

        // Trigger callback
        this.documentCompleted();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
        super.startElement(uri, localName, qName, attrs);

        // read metaInfo
        if (attrs != null && attrs.getIndex(ENTITY_ATTR_ID) >= 0) {

            this.osmId = Long.valueOf(attrs.getValue(ENTITY_ATTR_ID));

            String inVersion = attrs.getValue(ENTITY_ATTR_VERSION);
            final int version = Integer.valueOf(inVersion == null ? "0" : inVersion);

            String inChangesetId = attrs.getValue(ENTITY_ATTR_CHANGESET);
            final int changesetId = Integer.valueOf(inChangesetId == null ? "0" : inChangesetId);

            final String timestamp = attrs.getValue(ENTITY_ATTR_TIMESTAMP);
            final String userName = attrs.getValue(ENTITY_ATTR_USER);

            String inUserId = attrs.getValue(ENTITY_ATTR_USERID);
            final int userId = Integer.valueOf(inUserId == null ? "0" : inUserId);

            this.metaInfo = OSM.metaInfo(version, changesetId, timestamp, userName, userId);
        }

        switch (qName) {
            case NODE_ELEMENT:
                this.latitude = Double.valueOf(attrs.getValue(NODE_ATTR_LAT));
                this.longitude = Double.valueOf(attrs.getValue(NODE_ATTR_LONG));
                break;

            case WAY_ELEMENT:
            case RELATION_ELEMENT:
                // Nothing to do here
                break;

            case TAG_ELEMENT:
                final String key = attrs.getValue(TAG_ATTR_KEY);
                if (!key.equalsIgnoreCase("created_by"))
                    this.tagsMap.put(key, attrs.getValue(TAG_ATTR_VALUE));
                break;

            case WAY_ND_ELEMENT:
                final long refNodeId = Long.valueOf(attrs.getValue(WAY_ND_ATTR_REF));
                this.nodeIds.add(refNodeId);
                break;

            case MEMBER_ELEMENT:
                final long refId = Long.valueOf(attrs.getValue(MEMBER_ATTR_REF));
                final Type type = Type.valueOf(attrs.getValue(MEMBER_ATTR_TYPE).toLowerCase());
                final String role = attrs.getValue(MEMBER_ATTR_ROLE);

                this.members.add(OSM.member(type, refId, role));
                break;

            default:
                break;
        }

        LOGGER.debug("Element parsing started - qname: {}, meta: {}", qName, "");
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        LOGGER.debug("Element parsing completed - qname: {}, triggering callback", qName);

        switch (qName) {
            case NODE_ELEMENT:
                Node node = OSM.node(osmId, metaInfo, tagsMap, latitude, longitude);
                this.handleNode(node);

                resetTempVariables(); // Sanity work
                break;

            case WAY_ELEMENT:
                Way way = OSM.way(osmId, metaInfo, tagsMap, nodeIds);
                this.handleWay(way);

                resetTempVariables(); // Sanity work
                break;

            case RELATION_ELEMENT:
                Relation relation = OSM.relation(osmId, metaInfo, tagsMap, members);
                this.handleRelation(relation);

                resetTempVariables(); // Sanity work
                break;

            case TAG_ELEMENT:
            case WAY_ND_ELEMENT:
            case MEMBER_ELEMENT:
                // No need to handle
                break;

            default:
                LOGGER.info("Unhandled element : {}", qName);
                break;
        }

    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);

        // OSM data is always in attributes. Cool isn't it ?
    }

    // Private Methods
    // ------------------------------------------------------------------------

    private void resetTempVariables() {
        this.osmId = 0;
        this.metaInfo = null;
        this.latitude = 0;
        this.longitude = 0;

        this.tagsMap = new HashMap<>();
        this.nodeIds = new ArrayList<>();
        this.members = new ArrayList<>();
    }

    // Abstract callbacks
    // ------------------------------------------------------------------------

    /**
     * Callback for handling nodes.
     *
     * @param node object
     */
    public abstract void handleNode(Node node);

    /**
     * Callback for handling ways.
     *
     * @param way object
     */
    public abstract void handleWay(Way way);

    /**
     * Callback for handling relations.
     *
     * @param relation object
     */
    public abstract void handleRelation(Relation relation);

    /**
     * This callback is called once after the whole document is read.
     */
    public abstract void documentCompleted();

    // Counts

    /**
     * Get the total Count of the nodes that were read.
     *
     * @return nodes count
     */
    public abstract long getNodesCount();

    /**
     * Get the total Count of the ways that were read.
     *
     * @return ways count
     */
    public abstract long getWaysCount();

    /**
     * Get the total Count of the relations that were read.
     *
     * @return relations count
     */
    public abstract long getRelationsCount();

}