text:
@interface ClipMovieViewController () <PLSClipMovieViewDelegate>

@property (strong, nonatomic) UIView *baseToolboxView;
@property (strong, nonatomic) UIButton *playButton;

@property (strong, nonatomic) PLSEditPlayer *player;

@property (strong, nonatomic) PLSClipMovieView *clipMovieView;
@property (assign, nonatomic) CGFloat startTime;
@property (assign, nonatomic) CGFloat endTime;

@property (strong, nonatomic) NSTimer *playbackTimeCheckerTimer;
@property (assign, nonatomic) CGFloat videoPlaybackPosition;

@end

@implementation ClipMovieViewController

#pragma mark -- 获取视频/音频文件的总时长
- (CGFloat)getFileDuration:(NSURL*)URL {
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:URL options:opts];

    CMTime duration = asset.duration;
    float durationSeconds = CMTimeGetSeconds(duration);

    return durationSeconds;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = PLS_RGBCOLOR(25, 24, 36);

    // --------------------------
    self.startTime = 0.0f;
    self.endTime = [self getFileDuration:self.url];

    // --------------------------
    [self setupBaseToolboxView];

    [self setupClipMovieView];

    // --------------------------
    self.player = [[PLSEditPlayer alloc] init];
    [self.player setItemByAsset:[AVAsset assetWithURL:self.url]];
    self.player.loopEnabled = YES;
    self.player.preview.frame = CGRectMake(0, PLS_BaseToolboxView_HEIGHT, PLS_SCREEN_WIDTH, PLS_SCREEN_WIDTH);
    self.player.fillMode = PLSVideoFillModePreserveAspectRatio;
    [self.view addSubview:self.player.preview];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self.player seekToTime:CMTimeMake(self.startTime * 1e9, 1e9) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
    [self.player play];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    [self.player pause];
}

#pragma mark -- 配置视图
- (void)setupBaseToolboxView {
    self.baseToolboxView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, PLS_SCREEN_WIDTH, PLS_BaseToolboxView_HEIGHT)];
    self.baseToolboxView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.baseToolboxView];

    // 关闭按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage imageNamed:@"btn_bar_back_a"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_bar_back_b"] forState:UIControlStateHighlighted];
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backButton setTitleColor:PLS_RGBCOLOR(141, 141, 142) forState:UIControlStateHighlighted];
    backButton.frame = CGRectMake(0, 0, 80, 64);
    backButton.titleEdgeInsets = UIEdgeInsetsMake(0, 7, 0, 0);
    backButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.baseToolboxView addSubview:backButton];

    // 标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 100, 64)];
    if (iPhoneX) {
        titleLabel.center = CGPointMake(PLS_SCREEN_WIDTH / 2, 48);
    } else {
        titleLabel.center = CGPointMake(PLS_SCREEN_WIDTH / 2, 32);
    }
    titleLabel.text = @"剪辑";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor grayColor];
    titleLabel.font = [UIFont systemFontOfSize:18];
    [self.baseToolboxView addSubview:titleLabel];

    // 下一步
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextButton setImage:[UIImage imageNamed:@"btn_bar_next_a"] forState:UIControlStateNormal];
    [nextButton setImage:[UIImage imageNamed:@"btn_bar_next_b"] forState:UIControlStateHighlighted];
    [nextButton setTitle:@"下一步" forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextButton setTitleColor:PLS_RGBCOLOR(141, 141, 142) forState:UIControlStateHighlighted];
    nextButton.frame = CGRectMake(PLS_SCREEN_WIDTH - 80, 0, 80, 64);
    nextButton.titleEdgeInsets = UIEdgeInsetsMake(0, -40, 0, 0);
    nextButton.imageEdgeInsets = UIEdgeInsetsMake(0, 50, 0, 0);
    nextButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.baseToolboxView addSubview:nextButton];
}

- (void)setupClipMovieView {
    CGFloat duration = [self getFileDuration:self.url];
    self.clipMovieView = [[PLSClipMovieView alloc] initWithMovieURL:self.url minDuration:2.0f maxDuration:duration];
    self.clipMovieView.delegate = self;
    [self.view addSubview:self.clipMovieView];
    [self.clipMovieView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(150);
    }];
}

#pragma mark -- UIButton 按钮响应事件
#pragma mark -- 返回
- (void)backButtonClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- 下一步
- (void)nextButtonClick {
    [self.player pause];

    // 设置音视频、水印等编辑信息
    NSMutableDictionary *outputSettings = [[NSMutableDictionary alloc] init];
    // 待编辑的原始视频素材
    NSMutableDictionary *plsMovieSettings = [[NSMutableDictionary alloc] init];
    AVAsset *asset = [AVAsset assetWithURL:self.url];
    plsMovieSettings[PLSURLKey] = self.url;
    plsMovieSettings[PLSAssetKey] = asset;
    plsMovieSettings[PLSStartTimeKey] = [NSNumber numberWithFloat:self.startTime];
    plsMovieSettings[PLSDurationKey] = [NSNumber numberWithFloat:(self.endTime - self.startTime)];
    plsMovieSettings[PLSVolumeKey] = [NSNumber numberWithFloat:1.0f];
    outputSettings[PLSMovieSettingsKey] = plsMovieSettings;

    EditViewController *videoEditViewController = [[EditViewController alloc] init];
    videoEditViewController.settings = outputSettings;
    videoEditViewController.filesURLArray = @[self.url];
    [self presentViewController:videoEditViewController animated:YES completion:nil];
}

#pragma mark - PLSClipMovieView delegate
- (void)didStartDragView {
//    if (self.player.rate > 0) { // 正在播放的时候
//        [self.player pause];
//    }
}

- (void)clipFrameView:(PLSClipMovieView *)clipFrameView didDragView:(CMTime)time {

}

- (void)clipFrameView:(PLSClipMovieView *)clipFrameView didEndDragLeftView:(CMTime)time; {
    self.startTime = CMTimeGetSeconds(time);

    self.player.timeRange = CMTimeRangeMake(time, CMTimeSubtract(CMTimeMake(self.endTime * 1e9, 1e9), time));
}

- (void)clipFrameView:(PLSClipMovieView *)clipFrameView didEndDragRightView:(CMTime)time; {
    self.endTime = CMTimeGetSeconds(time);

    self.player.timeRange = CMTimeRangeMake(CMTimeMake(self.startTime * 1e9, 1e9), CMTimeSubtract(time, CMTimeMake(self.startTime * 1e9, 1e9)));
}

- (void)clipFrameView:(PLSClipMovieView *)clipFrameView isScrolling:(BOOL)scrolling {
    self.view.userInteractionEnabled = !scrolling;
}

#pragma mark -- 隐藏状态栏
- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- dealloc
- (void)dealloc {
    self.baseToolboxView = nil;

    self.player = nil;

    NSLog(@"dealloc: %@", [[self class] description]);
}

@end


text:
typedef struct _instruction_definition{
  void (*set_input_at)(instruction*, word, input*);
  void (*compile)(instruction*, asm_buff*);

  representation (*get_representation)(instruction*);
  representation (*get_input_representation)(instruction*, word);

  location_summary* (*make_location_summary)(instruction*);

  definition* (*argument_at)(instruction*, word);

  block_entry_instr* (*successor_at)(instruction*, word);

  word (*argument_count)(instruction*);
  word (*input_count)(instruction*);
  word (*successor_count)(instruction*);

  input* (*input_at)(instruction*, word);

  char* (*name)();
} instruction_definition;

typedef struct _block_definition{
  word (*predecessor_count)(block_entry_instr*);
  void (*add_predecessor)(block_entry_instr*, block_entry_instr*);
  void (*clear_predecessors)(block_entry_instr*);
  block_entry_instr* (*predecessor_at)(block_entry_instr*, word);
} block_definition;

#define DECLARE_DEFINITION(Name) \
  extern const struct _instruction_definition k##Name##Definition;
DECLARE_DEFINITION(Constant);
DECLARE_DEFINITION(Return);
DECLARE_DEFINITION(BinaryOp);
DECLARE_DEFINITION(Box);
DECLARE_DEFINITION(Unbox);
DECLARE_DEFINITION(GraphEntry);
DECLARE_DEFINITION(TargetEntry);
DECLARE_DEFINITION(JoinEntry);
DECLARE_DEFINITION(StoreLocal);
DECLARE_DEFINITION(LoadLocal);
DECLARE_DEFINITION(Phi);
DECLARE_DEFINITION(ParallelMove);
DECLARE_DEFINITION(NativeCall);
#undef DECLARE_DEFINITION

#define DEFINE_BLOCK(Name) \
  const block_definition k##Name##BlockDefinition =

#define DEFINE(Name) \
  const instruction_definition k##Name##Definition =

#define PREDECESSOR_COUNT(Name, Amount) \
  static word \
  Name##_predecessor_count(block_entry_instr* block){ \
    return Amount; \
  }

#define ADD_PREDECESSOR(Name) \
  static void \
  Name##_add_predecessor(block_entry_instr* block, block_entry_instr* pred)

#define PREDECESSOR_AT(Name, Value) \
  static block_entry_instr* \
  Name##_predecessor_at(block_entry_instr* block, word index){ \
    return to_##Name##_instr(((instruction*) block))->Value; \
  }

#define CLEAR_PREDECESSORS(Name) \
  static void \
  Name##_clear_predecessors(block_entry_instr* block)

#define INPUT_COUNT(Name, Amount) \
  static word \
  Name##_input_count(instruction* instr){ \
    return Amount; \
  }

#define INPUT_AT(Name, Value) \
  static input* \
  Name##_input_at(instruction* instr, word index){ \
    return to_##Name##_instr(instr)->Value; \
  } \
  static void \
  Name##_set_input_at(instruction* instr, word index, input* value){ \
    to_##Name##_instr(instr)->Value = value; \
  }

#define NAME(Name) \
  static char* \
  Name##_name(){ \
    return #Name; \
  }

#define SUCCESSOR_COUNT(Name, Amount) \
  static word \
  Name##_successor_count(instruction* instr){ \
    return Amount; \
  }

#define SUCCESSOR_AT(Name) \
  static block_entry_instr* \
  Name##_successor_at(instruction* instr, word index)

#if defined(ARCH_IS_X64)
#include "x64/compile.h"
#else
#error "Unknown CPU architecture"
#endif

#include "definitions.h"
#include "blocks.h"
#include "parallel_move.h"

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.topie.spi.device;

import java.io.IOException;

import javax.annotation.Resource;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DeviceFilter implements Filter {
    private DeviceConnector deviceConnector;

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        String deviceId = this.getCookie((HttpServletRequest) request,
                "SECURITY_DEVICE_ID");

        if (deviceId == null) {
            filterChain.doFilter(request, response);

            return;
        }

        DeviceDTO deviceDto = deviceConnector.findDevice(deviceId);

        if ((deviceDto != null) && "disabled".equals(deviceDto.getStatus())) {
            HttpServletResponse res = (HttpServletResponse) response;

            res.sendError(HttpServletResponse.SC_FORBIDDEN);

            return;
        }

        filterChain.doFilter(request, response);
    }

    public String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();

        if (cookies == null) {
            return null;
        }

        for (Cookie cookie : cookies) {
            if ((cookie == null) || (cookie.getName() == null)) {
                continue;
            }

            if (cookie.getName().equals(key)) {
                return cookie.getValue();
            }
        }

        return null;
    }

    @Resource
    public void setDeviceConnector(DeviceConnector deviceConnector) {
        this.deviceConnector = deviceConnector;
    }
}


text:
<?php

class Ess_M2ePro_Helper_Module_Cron extends Mage_Core_Helper_Abstract
{
    const RUNNER_MAGENTO = 'magento';
    const RUNNER_SERVICE = 'service';

    const STRATEGY_SERIAL   = 'serial';
    const STRATEGY_PARALLEL = 'parallel';

    const RUNNER_SERVICE_MAX_INACTIVE_TIME = 300;

    //########################################

    public function isModeEnabled()
    {
        return (bool)$this->getConfigValue('mode');
    }

    //########################################

    public function getRunner()
    {
        return $this->getConfigValue('runner');
    }

    public function setRunner($value)
    {
        if ($this->getRunner() != $value) {
            $this->log(
                "Cron runner was changed from [" . $this->getRunner() . "] to [" . $value . "] - ".
                Mage::helper('M2ePro')->getCurrentGmtDate(), 'cron_runner_change'
            );
        }

        return $this->setConfigValue('runner', $value);
    }

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

    public function isRunnerMagento()
    {
        return $this->getRunner() == self::RUNNER_MAGENTO;
    }

    public function isRunnerService()
    {
        return $this->getRunner() == self::RUNNER_SERVICE;
    }

    //########################################

    public function getLastRunnerChange()
    {
        return $this->getConfigValue('last_runner_change');
    }

    public function setLastRunnerChange($value)
    {
        $this->setConfigValue('last_runner_change', $value);
    }

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

    public function isLastRunnerChangeMoreThan($interval, $isHours = false)
    {
        $isHours && $interval *= 3600;

        $lastRunnerChange = $this->getLastRunnerChange();
        if ($lastRunnerChange === null) {
            return false;
        }

        return Mage::helper('M2ePro')->getCurrentGmtDate(true) > strtotime($lastRunnerChange) + $interval;
    }

    //########################################

    public function getLastAccess()
    {
        return $this->getConfigValue('last_access');
    }

    public function setLastAccess($value)
    {
        return $this->setConfigValue('last_access', $value);
    }

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

    public function isLastAccessMoreThan($interval, $isHours = false)
    {
        $isHours && $interval *= 3600;

        $lastAccess = $this->getLastAccess();
        if ($lastAccess === null) {
            return false;
        }

        return Mage::helper('M2ePro')->getCurrentGmtDate(true) > strtotime($lastAccess) + $interval;
    }

    //########################################

    public function getLastRun()
    {
        return $this->getConfigValue('last_run');
    }

    public function setLastRun($value)
    {
        return $this->setConfigValue('last_run', $value);
    }

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

    public function isLastRunMoreThan($interval, $isHours = false)
    {
        $isHours && $interval *= 3600;

        $lastRun = $this->getLastRun();
        if ($lastRun === null) {
            return false;
        }

        return Mage::helper('M2ePro')->getCurrentGmtDate(true) > strtotime($lastRun) + $interval;
    }

    //########################################

    public function getLastExecutedSlowTask()
    {
        return $this->getConfigValue('last_executed_slow_task');
    }

    public function setLastExecutedSlowTask($taskNick)
    {
        $this->setConfigValue('last_executed_slow_task', $taskNick);
    }

    //########################################

    protected function getConfig()
    {
        return Mage::helper('M2ePro/Module')->getConfig();
    }

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

    protected function getConfigValue($key)
    {
        return $this->getConfig()->getGroupValue('/cron/', $key);
    }

    protected function setConfigValue($key, $value)
    {
        return $this->getConfig()->setGroupValue('/cron/', $key, $value);
    }

    //########################################

    protected function log($message, $type)
    {
        /** @var Ess_M2ePro_Model_Log_System $log */
        $log = Mage::getModel('M2ePro/Log_System');

        $log->setType($type);
        $log->setDescription($message);

        $log->save();
    }

    //########################################
}


text:
package io.dashbase.clue.api;

public class RawBytesRefDisplay implements BytesRefDisplay {

  public RawBytesRefDisplay() {

  }

  @Override
  public BytesRefPrinter getBytesRefPrinter(String field) {
    return BytesRefPrinter.RawBytesPrinter;
  }

  public static final RawBytesRefDisplay INSTANCE = new RawBytesRefDisplay();
}


text:
module Ropian
  module Meter
    # This class provides support for Raritan brand power devices.
    class Raritan < Generic
      protected
        # If the vendor returns current in values in milli-amps for example
        # this method can be overridden to return 1000.
        #
        # @return [Numeric] Amps scaling factor.
        def amps_scale_factor
          1000
        end

        # @return [SNMP::ObjectId] SNMP OID where the unit current can be retrieved
        def unit_current_oid
          @unit_current_oid ||= SNMP::ObjectId.new("1.3.6.1.4.1.13742.4.1.4.2.1.3.1")
        end

        # @return [SNMP::ObjectId] Base SNMP OID where the outlet current can be retrieved
        def outlet_current_base_oid
          @outlet_current_base_oid ||= SNMP::ObjectId.new("1.3.6.1.4.1.13742.4.1.2.2.1.4")
        end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace Tibialyzer {
    public partial class LootDropForm : NotificationForm {
        public List<Tuple<Item, int>> items;
        public Dictionary<Creature, int> creatures;

        public Dictionary<Item, List<PictureBox>> itemControls = new Dictionary<Item, List<PictureBox>>();
        public Dictionary<Creature, Tuple<PictureBox, Label>> creatureControls = new Dictionary<Creature, Tuple<PictureBox, Label>>();
        public Creature lootCreature;
        public Hunt hunt;
        public int initialPage = 0;
        public int page = 0;
        public const int pageHeight = 400;
        public const int maxCreatureHeight = 700;
        public const int minLootWidth = 203;
        private string huntName = "";
        private string creatureName = "";
        public string rawName = "";
        private long averageGold = 0;
        private object updateLock = new object();
        private static System.Timers.Timer updateTimer;

        ToolTip value_tooltip = new ToolTip();
        public static Font loot_font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold);
        public LootDropForm(string command) {
            string[] split = command.Split('@');
            if (split.Length >= 2) {
                huntName = split[1];
            }
            if (split.Length >= 3) {
                creatureName = split[2];
            }
            if (split.Length >= 4) {
                rawName = split[3];
            }
            lootCreature = StorageManager.getCreature(creatureName);
            InitializeComponent();
            value_tooltip.AutoPopDelay = 60000;
            value_tooltip.InitialDelay = 500;
            value_tooltip.ReshowDelay = 0;
            value_tooltip.ShowAlways = true;
            value_tooltip.UseFading = true;
            this.Name = "Tibialyzer (Loot Form)";
            updateTimer = new System.Timers.Timer(500);
            updateTimer.AutoReset = false;
            updateTimer.Elapsed += (s, e) => {
                ActuallyRefreshForm();
            };
        }
        private void ActuallyRefreshForm() {
            lock (updateLock) {
                if (this.IsDisposed) return;
                try {
                    updateTimer.Stop();
                    updateTimer.Enabled = false;
                    this.Invoke((MethodInvoker)delegate {
                        UpdateLootInternal();
                    });
                } catch {

                }
            }
        }

        public static Bitmap GetStackImage(Image image, int count, Item item) {
            if (image == null) return new Bitmap(item.image);
            lock(image) {
                int max = image.GetFrameCount(FrameDimension.Time);
                int index = 0;

                if (count <= 5) index = count - 1;
                else if (count <= 10) index = 5;
                else if (count <= 25) index = 6;
                else if (count <= 50) index = 7;
                else index = 8;

                if (index >= max) index = max - 1;
                image.SelectActiveFrame(FrameDimension.Time, index);
                return new Bitmap((Image)image.Clone());
            }
        }

        public static void DrawCountOnGraphics(Graphics gr, int itemCount, int offset_x, int offset_y) {
            int numbers = (int)Math.Floor(Math.Log(itemCount, 10)) + 1;
            int xoffset = 1, logamount = itemCount;
            for (int i = 0; i < numbers; i++) {
                int imagenr = logamount % 10;
                Image imageNumber = StyleManager.GetImage(imagenr + ".png");
                xoffset = xoffset + imageNumber.Width + (itemCount >= 1000 ? 0 : 1);
                lock (imageNumber) {
                    gr.DrawImage(imageNumber, new Point(offset_x - xoffset, offset_y - imageNumber.Height - 3));
                }
                logamount /= 10;
            }
        }

        public static Bitmap DrawCountOnItem(Item item, int itemCount, int size = -1) {
            Bitmap image;
            if (item.stackable) {
                try {
                    image = new Bitmap(LootDropForm.GetStackImage(item.image, itemCount, item));
                } catch {
                    image = new Bitmap(item.image);
                }
            } else {
                image = new Bitmap(item.image);
            }

            using (Graphics gr = Graphics.FromImage(image)) {
                DrawCountOnGraphics(gr, itemCount, image.Width, image.Height);
            }
            return image;
        }

        public static Tuple<Dictionary<Creature, int>, List<Tuple<Item, int>>> GenerateLootInformation(Hunt hunt, string rawName, Creature lootCreature) {
            Dictionary<Creature, int> creatureKills;
            List<Tuple<Item, int>> itemDrops = new List<Tuple<Item, int>>();

            bool raw = rawName == "raw";
            bool all = raw || rawName == "all";
            List<Creature> displayedCreatures = null;
            if (!hunt.trackAllCreatures && hunt.trackedCreatures.Length > 0) {
                displayedCreatures = hunt.GetTrackedCreatures();
            } else if (SettingsManager.getSettingBool("IgnoreLowExperience")) {
                displayedCreatures = new List<Creature>();
                foreach (Creature cr in hunt.IterateCreatures()) {
                    if (cr.experience >= SettingsManager.getSettingInt("IgnoreLowExperienceValue")) {
                        displayedCreatures.Add(cr);
                    }
                }
            }

            if (lootCreature != null) {
                //the command is loot@<creature>, so we only display the kills and loot from the specified creature
                creatureKills = hunt.GetCreatureKills(lootCreature);
            } else if (displayedCreatures == null) {
                creatureKills = hunt.GetCreatureKills(); //display all creatures //loot.killCount;
            } else {
                // only display tracked creatures
                creatureKills = hunt.GetCreatureKills(displayedCreatures); // new Dictionary<Creature, int>();
            }

            // now handle item drops, gather a count for every item
            Dictionary<Item, int> itemCounts = new Dictionary<Item, int>();
            foreach (KeyValuePair<Creature, Dictionary<Item, int>> kvp in hunt.IterateLoot()) {
                if (lootCreature != null && kvp.Key != lootCreature) continue; // if lootCreature is specified, only consider loot from the specified creature
                if (displayedCreatures != null && !displayedCreatures.Contains(kvp.Key)) continue;
                foreach (KeyValuePair<Item, int> kvp2 in kvp.Value) {
                    Item item = kvp2.Key;
                    int value = kvp2.Value;
                    if (!itemCounts.ContainsKey(item)) itemCounts.Add(item, value);
                    else itemCounts[item] += value;
                }
            }

            // now we do item conversion
            long extraGold = 0;
            foreach (KeyValuePair<Item, int> kvp in itemCounts) {
                Item item = kvp.Key;
                int count = kvp.Value;
                // discard items that are set to be discarded (as long as all/raw mode is not enabled)
                if (item.discard && !all) continue;
                // convert items to gold (as long as raw mode is not enabled), always gather up all the gold coins found
                if ((!raw && item.convert_to_gold) || item.displayname == "gold coin" || item.displayname == "platinum coin" || item.displayname == "crystal coin") {
                    extraGold += item.GetMaxValue() * count;
                } else {
                    itemDrops.Add(new Tuple<Item, int>(item, count));
                }
            }

            // handle coin drops, we always convert the gold to the highest possible denomination (so if gold = 10K, we display a crystal coin)
            long currentGold = extraGold;
            if (currentGold > 10000) {
                itemDrops.Add(new Tuple<Item, int>(StorageManager.getItem("crystal coin"), (int)(currentGold / 10000)));
                currentGold = currentGold % 10000;
            }
            if (currentGold > 100) {
                itemDrops.Add(new Tuple<Item, int>(StorageManager.getItem("platinum coin"), (int)(currentGold / 100)));
                currentGold = currentGold % 100;
            }
            if (currentGold > 0) {
                itemDrops.Add(new Tuple<Item, int>(StorageManager.getItem("gold coin"), (int)(currentGold)));
            }

            // now order by value so most valuable items are placed first
            // we use a special value for the gold coins so the gold is placed together in the order crystal > platinum > gold
            // gold coins = <gold total> - 2, platinum coins = <gold total> - 1, crystal coins = <gold total>
            itemDrops = itemDrops.OrderByDescending(o => o.Item1.displayname == "gold coin" ? extraGold - 2 : (o.Item1.displayname == "platinum coin" ? extraGold - 1 : (o.Item1.displayname == "crystal coin" ? extraGold : o.Item1.GetMaxValue() * o.Item2))).ToList();
            return new Tuple<Dictionary<Creature, int>, List<Tuple<Item, int>>>(creatureKills, itemDrops);
        }

        private void UpdateLootInternal() {
            refreshTimer();
            var tpl = LootDropForm.GenerateLootInformation(hunt, rawName, lootCreature);
            creatures = tpl.Item1;
            items = tpl.Item2;
            this.SuspendForm();
            RefreshLoot();
            this.ResumeForm();
        }

        public void UpdateLoot() {
            if (this.IsDisposed) return;
            lock (updateLock) {
                if (!updateTimer.Enabled) {
                    updateTimer.Start();
                }
            }
        }

        public static string TimeToString(long totalSeconds) {
            string displayString = "";
            if (totalSeconds >= 3600) {
                displayString += (totalSeconds / 3600).ToString() + "h ";
                totalSeconds = totalSeconds % 3600;
            }
            if (totalSeconds >= 60) {
                displayString += (totalSeconds / 60).ToString() + "m ";
                totalSeconds = totalSeconds % 60;
            }
            displayString += totalSeconds.ToString() + "s";
            return displayString;
        }

        public static long GetAverageGold(Dictionary<Creature, int> creatures) {
            long averageGold = 0;
            foreach (KeyValuePair<Creature, int> tpl in creatures) {
                double average = 0;
                foreach (ItemDrop dr in tpl.Key.itemdrops) {
                    Item it = StorageManager.getItem(dr.itemid);
                    if (!it.discard && it.GetMaxValue() > 0 && dr.percentage > 0) {
                        average += ((dr.min + dr.max) / 2.0) * (dr.percentage / 100.0) * it.GetMaxValue();
                    }
                }
                averageGold += (int)(average * tpl.Value);
            }
            return averageGold;
        }

        public List<Control> createdControls = new List<Control>();
        public void RefreshLoot() {
            foreach (Control c in createdControls) {
                this.Controls.Remove(c);
                c.Dispose();
            }
            createdControls.Clear();
            if (page < 0) page = 0;

            int base_x = 20, base_y = 30;
            int x = 0, y = 0;
            int item_spacing = 4;
            Size item_size = new Size(32, 32);
            int max_x = SettingsManager.getSettingInt("LootFormWidth");
            if (max_x < minLootWidth) max_x = minLootWidth;
            int width_x = max_x + item_spacing * 2;

            long total_value = 0;
            int currentPage = 0;
            bool prevPage = page > 0;
            bool nextPage = false;

            averageGold = GetAverageGold(creatures);

            foreach (Tuple<Item, int> tpl in items) {
                total_value += tpl.Item1.GetMaxValue() * tpl.Item2;
            }
            Dictionary<Item, List<PictureBox>> newItemControls = new Dictionary<Item, List<PictureBox>>();
            foreach (Tuple<Item, int> tpl in items) {
                Item item = tpl.Item1;
                int count = tpl.Item2;
                while (count > 0) {
                    if (base_x + x >= (max_x - item_size.Width - item_spacing)) {
                        x = 0;
                        if (y + item_size.Height + item_spacing > pageHeight) {
                            currentPage++;
                            if (currentPage > page) {
                                nextPage = true;
                                break;
                            } else {
                                y = 0;
                            }
                        } else {
                            y = y + item_size.Height + item_spacing;
                        }
                    }
                    int mitems = 1;
                    if (item.stackable || SettingsManager.getSettingBool("StackAllItems")) mitems = Math.Min(count, 100);
                    count -= mitems;
                    if (currentPage == page) {
                        PictureBox picture_box;
                        if (itemControls.ContainsKey(item)) {
                            picture_box = itemControls[item][0];
                            itemControls[item].RemoveAt(0);
                            if (itemControls[item].Count == 0) {
                                itemControls.Remove(item);
                            }
                            picture_box.Location = new System.Drawing.Point(base_x + x, base_y + y);
                            if (picture_box.TabIndex != mitems && (item.stackable || mitems > 1)) {
                                picture_box.Image = LootDropForm.DrawCountOnItem(item, mitems);
                            }
                            picture_box.TabIndex = mitems;
                            long individualValue = item.GetMaxValue();
                            value_tooltip.SetToolTip(picture_box, System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(item.displayname) + " value: " + (individualValue >= 0 ? (individualValue * mitems).ToString() : "Unknown"));
                        } else {
                            picture_box = new PictureBox();
                            picture_box.Location = new System.Drawing.Point(base_x + x, base_y + y);
                            picture_box.Name = item.GetName();
                            picture_box.Size = new System.Drawing.Size(item_size.Width, item_size.Height);
                            picture_box.TabIndex = mitems;
                            picture_box.TabStop = false;
                            if (item.stackable || mitems > 1) {
                                picture_box.Image = LootDropForm.DrawCountOnItem(item, mitems);
                            } else {
                                picture_box.Image = item.GetImage();
                            }

                            picture_box.SizeMode = PictureBoxSizeMode.StretchImage;
                            picture_box.BackgroundImage = StyleManager.GetImage("item_background.png");
                            picture_box.Click += openItemBox;
                            long individualValue = item.GetMaxValue();
                            value_tooltip.SetToolTip(picture_box, System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(item.displayname) + " value: " + (individualValue >= 0 ? (individualValue * mitems).ToString() : "Unknown"));
                            this.Controls.Add(picture_box);
                        }
                        if (!newItemControls.ContainsKey(item)) newItemControls.Add(item, new List<PictureBox>());
                        newItemControls[item].Add(picture_box);
                    }

                    x += item_size.Width + item_spacing;
                }
                if (currentPage > page) {
                    break;
                }
            }
            if (page > currentPage) {
                page = currentPage;
                RefreshLoot();
                return;
            }

            foreach (KeyValuePair<Item, List<PictureBox>> kvp in itemControls) {
                foreach (PictureBox p in kvp.Value) {
                    this.Controls.Remove(p);
                    p.Dispose();
                }
            }
            itemControls = newItemControls;

            y = y + item_size.Height + item_spacing;
            if (prevPage) {
                PictureBox prevpage = new PictureBox();
                prevpage.Location = new Point(10, base_y + y);
                prevpage.Size = new Size(97, 23);
                prevpage.Image = StyleManager.GetImage("prevpage.png");
                prevpage.BackColor = Color.Transparent;
                prevpage.SizeMode = PictureBoxSizeMode.StretchImage;
                prevpage.Click += Prevpage_Click;
                this.Controls.Add(prevpage);
                createdControls.Add(prevpage);
            }
            if (nextPage) {
                PictureBox nextpage = new PictureBox();
                nextpage.Location = new Point(width_x - 108, base_y + y);
                nextpage.Size = new Size(98, 23);
                nextpage.BackColor = Color.Transparent;
                nextpage.Image = StyleManager.GetImage("nextpage.png");
                nextpage.SizeMode = PictureBoxSizeMode.StretchImage;
                nextpage.Click += Nextpage_Click;
                this.Controls.Add(nextpage);
                createdControls.Add(nextpage);
            }
            if (prevPage || nextPage) y += 23;

            x = 0;
            base_x = 5;
            Size creature_size = new Size(1, 1);
            Size labelSize = new Size(1, 1);

            foreach (KeyValuePair<Creature, int> tpl in creatures) {
                Creature creature = tpl.Key;
                creature_size.Width = Math.Max(creature_size.Width, creature.GetImage().Width);
                creature_size.Height = Math.Max(creature_size.Height, creature.GetImage().Height);
            }
            {
                Dictionary<Creature, Tuple<PictureBox, Label>> newCreatureControls = new Dictionary<Creature, Tuple<PictureBox, Label>>();
                int i = 0;
                foreach (Creature cr in creatures.Keys.OrderByDescending(o => creatures[o] * (1 + o.experience)).ToList<Creature>()) {
                    Creature creature = cr;
                    int killCount = creatures[cr];
                    if (x >= max_x - creature_size.Width - item_spacing * 2) {
                        x = 0;
                        y = y + creature_size.Height + 23;
                        if (y > maxCreatureHeight) {
                            break;
                        }
                    }
                    int xoffset = (creature_size.Width - creature.GetImage().Width) / 2;
                    int yoffset = (creature_size.Height - creature.GetImage().Height) / 2;

                    Label count;
                    PictureBox picture_box;
                    if (creatureControls.ContainsKey(creature)) {
                        picture_box = creatureControls[creature].Item1;
                        count = creatureControls[creature].Item2;
                        creatureControls.Remove(creature);

                        picture_box.Location = new System.Drawing.Point(base_x + x + xoffset, base_y + y + yoffset + (creature_size.Height - creature.GetImage().Height) / 2);
                        count.Location = new Point(base_x + x + xoffset, base_y + y + creature_size.Height);
                        count.Text = killCount.ToString() + "x";
                    } else {
                        count = new Label();
                        count.Text = killCount.ToString() + "x";
                        count.Font = loot_font;
                        count.Size = new Size(1, 10);
                        count.Location = new Point(base_x + x + xoffset, base_y + y + creature_size.Height);
                        count.AutoSize = true;
                        count.TextAlign = ContentAlignment.MiddleCenter;
                        count.ForeColor = StyleManager.NotificationTextColor;
                        count.BackColor = Color.Transparent;

                        picture_box = new PictureBox();
                        picture_box.Location = new System.Drawing.Point(base_x + x + xoffset, base_y + y + yoffset + (creature_size.Height - creature.GetImage().Height) / 2);
                        picture_box.Name = creature.GetName();
                        picture_box.Size = new System.Drawing.Size(creature.GetImage().Width, creature.GetImage().Height);
                        picture_box.TabIndex = 1;
                        picture_box.TabStop = false;
                        picture_box.Image = creature.GetImage();
                        picture_box.SizeMode = PictureBoxSizeMode.StretchImage;
                        picture_box.Click += openCreatureDrops;
                        picture_box.BackColor = Color.Transparent;

                        this.Controls.Add(picture_box);
                        this.Controls.Add(count);
                    }
                    int measured_size = (int)count.CreateGraphics().MeasureString(count.Text, count.Font).Width;
                    int width = Math.Max(measured_size, creature.GetImage().Width);

                    if (width > creature.GetImage().Width) {
                        picture_box.Location = new Point(picture_box.Location.X + (width - creature.GetImage().Width) / 2, picture_box.Location.Y);
                    } else {
                        count.Location = new Point(count.Location.X + (width - measured_size) / 2, count.Location.Y);
                    }
                    newCreatureControls.Add(creature, new Tuple<PictureBox, Label>(picture_box, count));

                    labelSize = count.Size;

                    i++;
                    x += width + xoffset;
                }
                y = y + creature_size.Height + labelSize.Height * 2;
                foreach (KeyValuePair<Creature, Tuple<PictureBox, Label>> kvp in creatureControls) {
                    this.Controls.Remove(kvp.Value.Item1);
                    this.Controls.Remove(kvp.Value.Item2);
                    kvp.Value.Item1.Dispose();
                    kvp.Value.Item2.Dispose();
                }
                creatureControls = newCreatureControls;
            }

            long usedItemValue = 0;
            foreach (var tpl in HuntManager.GetUsedItems(hunt)) {
                usedItemValue += tpl.Item1.GetMaxValue() * tpl.Item2;
            }

            int xPosition = width_x - totalValueValue.Size.Width - 5;
            y = base_y + y + item_spacing + 10;
            huntNameLabel.Text = hunt.name.ToString();
            totalValueLabel.Location = new Point(5, y);
            totalValueValue.Location = new Point(xPosition, y);
            totalValueValue.Text = total_value.ToString("N0");
            value_tooltip.SetToolTip(totalValueValue, String.Format("Average gold for these creature kills: {0} gold.", averageGold.ToString("N0")));
            totalExpLabel.Location = new Point(5, y += 20);
            totalExpValue.Location = new Point(xPosition, y);
            totalExpValue.Text = hunt.totalExp.ToString("N0");
            expHourValue.Text = ScanningManager.lastResults == null ? "-" : ScanningManager.lastResults.expPerHour.ToString("N0");
            expHourLabel.Location = new Point(5, y += 20);
            expHourValue.Location = new Point(xPosition, y);
            totalTimeLabel.Location = new Point(5, y += 20);
            totalTimeValue.Location = new Point(xPosition, y);
            usedItemsValue.Text = usedItemValue.ToString("N0");
            usedItemsLabel.Location = new Point(5, y += 20);
            usedItemsValue.Location = new Point(xPosition, y);
            long profit = total_value - usedItemValue;
            value_tooltip.SetToolTip(usedItemsValue, String.Format(profit > 0 ? "Total Profit: {0} gold" : "Total Waste: {0} gold", profit.ToString("N0")));

            totalTimeValue.Text = TimeToString((long)hunt.totalTime);
            y += 20;

            int widthSize = width_x / 3 - 5;
            lootButton.Size = new Size(widthSize, lootButton.Size.Height);
            lootButton.Location = new Point(5, y);
            allLootButton.Size = new Size(widthSize, lootButton.Size.Height);
            allLootButton.Location = new Point(7 + widthSize, y);
            rawLootButton.Size = new Size(widthSize, lootButton.Size.Height);
            rawLootButton.Location = new Point(10 + 2 * widthSize, y);

            y += allLootButton.Size.Height + 2;

            huntNameLabel.Size = new Size(width_x, huntNameLabel.Size.Height);
            this.Size = new Size(width_x, y + 5);
            lootLarger.Location = new Point(Size.Width - lootLarger.Size.Width - 4, 4);
            lootSmaller.Location = new Point(Size.Width - 2 * lootLarger.Size.Width - 4, 4);
        }

        public override void LoadForm() {
            this.NotificationInitialize();

            UnregisterControl(lootSmaller);
            UnregisterControl(lootLarger);
            UnregisterControl(rawLootButton);
            UnregisterControl(allLootButton);
            UnregisterControl(lootButton);

            UpdateLootInternal();

            base.NotificationFinalize();
        }

        private void Prevpage_Click(object sender, EventArgs e) {
            page--;
            this.SuspendForm();
            this.RefreshLoot();
            this.ResumeForm();
            this.Refresh();
            this.refreshTimer();
        }

        private void Nextpage_Click(object sender, EventArgs e) {
            page++;
            this.SuspendForm();
            this.RefreshLoot();
            this.ResumeForm();
            this.Refresh();
            this.refreshTimer();
        }

        void openItemBox(object sender, EventArgs e) {
            this.ReturnFocusToTibia();
            CommandManager.ExecuteCommand("item" + Constants.CommandSymbol + (sender as Control).Name);
        }

        void openCreatureDrops(object sender, EventArgs e) {
            if (creatures.Keys.Count == 1) {
                CommandManager.ExecuteCommand("creature" + Constants.CommandSymbol + (sender as Control).Name);
            } else {
                CommandManager.ExecuteCommand(String.Format("loot{0}{1}{0}{2}{0}{3}", Constants.CommandSymbol, huntName, (sender as Control).Name, rawName));
            }
        }

        private void huntNameLabel_Click(object sender, EventArgs e) {
        }

        private void rawLootButton_Click(object sender, EventArgs e) {
            rawName = "raw";
            this.UpdateLootInternal();
            this.UpdateCommand();
        }

        private void allLootButton_Click(object sender, EventArgs e) {
            rawName = "all";
            this.UpdateLootInternal();
            this.UpdateCommand();
        }

        private void lootButton_Click(object sender, EventArgs e) {
            rawName = "";
            creatureName = "";
            lootCreature = null;
            this.UpdateLootInternal();
            this.UpdateCommand();
        }

        private void UpdateCommand() {
            this.command.command = String.Format("loot{0}{1}{0}{2}{0}{3}", Constants.CommandSymbol, huntName, lootCreature == null ? "" : lootCreature.GetName(), rawName);
        }

        private void changeSize(int modification) {
            int max_x = SettingsManager.getSettingInt("LootFormWidth");
            if (max_x < minLootWidth) max_x = minLootWidth;
            max_x += modification;
            if (max_x < minLootWidth) max_x = minLootWidth;
            SettingsManager.setSetting("LootFormWidth", (max_x).ToString());
            this.SuspendForm();
            this.RefreshLoot();
            this.ResumeForm();
            this.Refresh();
            this.refreshTimer();
        }

        private void lootSmaller_Click(object sender, EventArgs e) {
            changeSize(-36);
        }

        private void lootLarger_Click(object sender, EventArgs e) {
            changeSize(36);
        }

        public override string FormName() {
            return "LootDropForm";
        }
    }
}


text:
<?php

namespace Laminas\Code\Reflection\Exception;

use Laminas\Code\Exception;

class BadMethodCallException extends Exception\BadMethodCallException implements
    ExceptionInterface
{
}


text:
from __future__ import print_function
import argparse
import logging

import mxnet as mx

from rcnn.config import config, default, generate_config
from rcnn.tools.train_rpn import train_rpn
from rcnn.tools.test_rpn import test_rpn
from rcnn.tools.train_rcnn import train_rcnn
from rcnn.utils.combine_model import combine_model

def alternate_train(args, ctx, pretrained, epoch,
                    rpn_epoch, rpn_lr, rpn_lr_step,
                    rcnn_epoch, rcnn_lr, rcnn_lr_step):
    # set up logger
    logging.basicConfig()
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    # basic config
    begin_epoch = 0
    config.TRAIN.BG_THRESH_LO = 0.0

    logging.info('########## TRAIN RPN WITH IMAGENET INIT')
    train_rpn(args.network, args.dataset, args.image_set, args.root_path, args.dataset_path,
              args.frequent, args.kvstore, args.work_load_list, args.no_flip, args.no_shuffle, args.resume,
              ctx, pretrained, epoch, 'model/rpn1', begin_epoch, rpn_epoch,
              train_shared=False, lr=rpn_lr, lr_step=rpn_lr_step)

    logging.info('########## GENERATE RPN DETECTION')
    image_sets = [iset for iset in args.image_set.split('+')]
    for image_set in image_sets:
        test_rpn(args.network, args.dataset, image_set, args.root_path, args.dataset_path,
                 ctx[0], 'model/rpn1', rpn_epoch,
                 vis=False, shuffle=False, thresh=0)

    logging.info('########## TRAIN RCNN WITH IMAGENET INIT AND RPN DETECTION')
    train_rcnn(args.network, args.dataset, args.image_set, args.root_path, args.dataset_path,
               args.frequent, args.kvstore, args.work_load_list, args.no_flip, args.no_shuffle, args.resume,
               ctx, pretrained, epoch, 'model/rcnn1', begin_epoch, rcnn_epoch,
               train_shared=False, lr=rcnn_lr, lr_step=rcnn_lr_step, proposal='rpn')

    logging.info('########## TRAIN RPN WITH RCNN INIT')
    train_rpn(args.network, args.dataset, args.image_set, args.root_path, args.dataset_path,
              args.frequent, args.kvstore, args.work_load_list, args.no_flip, args.no_shuffle, args.resume,
              ctx, 'model/rcnn1', rcnn_epoch, 'model/rpn2', begin_epoch, rpn_epoch,
              train_shared=True, lr=rpn_lr, lr_step=rpn_lr_step)

    logging.info('########## GENERATE RPN DETECTION')
    image_sets = [iset for iset in args.image_set.split('+')]
    for image_set in image_sets:
        test_rpn(args.network, args.dataset, image_set, args.root_path, args.dataset_path,
                 ctx[0], 'model/rpn2', rpn_epoch,
                 vis=False, shuffle=False, thresh=0)

    logger.info('########## COMBINE RPN2 WITH RCNN1')
    combine_model('model/rpn2', rpn_epoch, 'model/rcnn1', rcnn_epoch, 'model/rcnn2', 0)

    logger.info('########## TRAIN RCNN WITH RPN INIT AND DETECTION')
    train_rcnn(args.network, args.dataset, args.image_set, args.root_path, args.dataset_path,
               args.frequent, args.kvstore, args.work_load_list, args.no_flip, args.no_shuffle, args.resume,
               ctx, 'model/rcnn2', 0, 'model/rcnn2', begin_epoch, rcnn_epoch,
               train_shared=True, lr=rcnn_lr, lr_step=rcnn_lr_step, proposal='rpn')

    logger.info('########## COMBINE RPN2 WITH RCNN2')
    combine_model('model/rpn2', rpn_epoch, 'model/rcnn2', rcnn_epoch, 'model/final', 0)

def parse_args():
    parser = argparse.ArgumentParser(description='Train Faster R-CNN Network')
    # general
    parser.add_argument('--network', help='network name', default=default.network, type=str)
    parser.add_argument('--dataset', help='dataset name', default=default.dataset, type=str)
    args, rest = parser.parse_known_args()
    generate_config(args.network, args.dataset)
    parser.add_argument('--image_set', help='image_set name', default=default.image_set, type=str)
    parser.add_argument('--root_path', help='output data folder', default=default.root_path, type=str)
    parser.add_argument('--dataset_path', help='dataset path', default=default.dataset_path, type=str)
    # training
    parser.add_argument('--frequent', help='frequency of logging', default=default.frequent, type=int)
    parser.add_argument('--kvstore', help='the kv-store type', default=default.kvstore, type=str)
    parser.add_argument('--work_load_list', help='work load for different devices', default=None, type=list)
    parser.add_argument('--no_flip', help='disable flip images', action='store_true')
    parser.add_argument('--no_shuffle', help='disable random shuffle', action='store_true')
    parser.add_argument('--resume', help='continue training', action='store_true')
    # alternate
    parser.add_argument('--gpus', help='GPU device to train with', default='0', type=str)
    parser.add_argument('--pretrained', help='pretrained model prefix', default=default.pretrained, type=str)
    parser.add_argument('--pretrained_epoch', help='pretrained model epoch', default=default.pretrained_epoch, type=int)
    parser.add_argument('--rpn_epoch', help='end epoch of rpn training', default=default.rpn_epoch, type=int)
    parser.add_argument('--rpn_lr', help='base learning rate', default=default.rpn_lr, type=float)
    parser.add_argument('--rpn_lr_step', help='learning rate steps (in epoch)', default=default.rpn_lr_step, type=str)
    parser.add_argument('--rcnn_epoch', help='end epoch of rcnn training', default=default.rcnn_epoch, type=int)
    parser.add_argument('--rcnn_lr', help='base learning rate', default=default.rcnn_lr, type=float)
    parser.add_argument('--rcnn_lr_step', help='learning rate steps (in epoch)', default=default.rcnn_lr_step, type=str)
    args = parser.parse_args()
    return args

def main():
    args = parse_args()
    print('Called with argument:', args)
    ctx = [mx.gpu(int(i)) for i in args.gpus.split(',')]
    alternate_train(args, ctx, args.pretrained, args.pretrained_epoch,
                    args.rpn_epoch, args.rpn_lr, args.rpn_lr_step,
                    args.rcnn_epoch, args.rcnn_lr, args.rcnn_lr_step)

if __name__ == '__main__':
    main()


text:
import lodash from 'lodash';
import React from 'react';

import DisplayDie from '../displayDie/DisplayDie';
import {DiceStoreResult} from '../../../diceSets/common/diceStoreBase';

import './diceHand.scss';

type Props<SymbolType, StatsType> = {
  diceSet: DiceStoreResult<SymbolType, StatsType>;
}

/**
 * The DiceHand component.
 *
 * @param props
 * @param props.diceSet - The dice set.
 */
function DiceHand<SymbolType, StatsType>({
  diceSet
}: Props<SymbolType, StatsType>): React.ReactElement
{
  const hand = diceSet.hand;

  return (

          {lodash.map(hand, (die, i) => (
            <DisplayDie key={die.name + i} display={die.display} onClick={(): void => diceSet.removeFromHand(die)} />
          ))}

        {(hand.length) ? (

Tap dice above to remove them from your hand

        ) : (

Your Hand is Empty

        )}

  );
}

export default DiceHand;


text:
'use strict';

const path = require('path');
const express = require('express');
const request = require('supertest');

const autoroute = require('../');

let app;
let server;

describe('Custom Routes folder loading', () => {
  before(() => {
    app = express();

    autoroute(app, {
      throwErrors: true,
      routesDir: path.join(process.cwd(), 'test', 'routes'),
    });

    server = app.listen(4000);
  });
  after((done) => {
    app = null;
    server.close(done);
  });
  describe('test.js', () => {
    it('should return "get" from /getTest', (done) => {
      request(app).get('/getTest').expect(200).expect('get test/routes')
        .end(done);
    });
    it('should return "post" from /postTest', (done) => {
      request(app).post('/postTest').expect(200).expect('post test/routes')
        .end(done);
    });

    // parametrised tests
    it('should return "378" from /getTest/378', (done) => {
      request(app).get('/getTest/378').expect(200).expect('378 test/routes')
        .end(done);
    });
    it('should return "3874" from /postTest/3874', (done) => {
      request(app).post('/postTest/3874').expect(200).expect('3874 test/routes')
        .end(done);
    });
    it('should return "752" from /deleteTest/752', (done) => {
      request(app).del('/deleteTest/752').expect(200).expect('752 test/routes')
        .end(done);
    });
  });
});


text:
use crate::world::Tile;
use crate::world::World;

use crate::helpers::compute_index;
use crate::helpers::Position;
use crate::helpers::Size;

use crate::robot::Robot;

// World builder
pub struct WorldBuilder {
    karel: Option<Robot>,
    heigth: Size,
    width: Size,
    tiles: Vec<Tile>,
}

impl WorldBuilder {
    pub fn new() -> WorldBuilder {
        WorldBuilder {
            karel: None,
            width: 0,
            heigth: 0,
            tiles: Vec::new(),
        }
    }

    pub fn dimensions(&mut self, width: Size, heigth: Size) -> &mut WorldBuilder {
        self.heigth = heigth;
        self.width = width;

        self.tiles = vec![Tile::Empty; heigth as usize * width as usize];

        self
    }

    pub fn karel(&mut self, karel: Robot) -> &mut WorldBuilder {
        self.karel = Some(karel);

        self
    }

    pub fn tile(&mut self, position: Position, tile: Tile) -> &mut WorldBuilder {
        let tile_index = compute_index(position, self.width) as usize;

        // handle the loaded content colision here
        self.tiles[tile_index] = tile;

        self
    }

    pub fn build(self) -> World {
        // TODO handle error states
        // e.g. parsing values validation
        // required lines must be present and valid
        World::new(self.width, self.heigth, self.karel.unwrap(), self.tiles)
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: naveen
 * Date: 13/01/16
 * Time: 5:34 AM
 */

namespace Application\Model;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;

class CartTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll($paginated=false) {

        $sql = new Sql($this->tableGateway->adapter);
        $select = $sql->select();
        $select->from($this->tableGateway->getTable());
       // $select->order('order_id DESC');
       // $select->join(array("p"=>"products"), 'p.product_id = orders.product_id',array("merchant_id","product_name"));
       // $select->join(array("i"=>"images"), 'i.product_id = p.product_id',array("image_name"));

        if ($paginated) {
            $dbTableGatewayAdapter = new DbSelect($select, $sql);
            //$dbTableGatewayAdapter = new DbTableGateway($this->tableGateway);
            $paginator = new Paginator($dbTableGatewayAdapter);
            return $paginator;
        } else {
            $resultSet = $this->tableGateway->selectWith($select);
        }
        //var_dump($resultSet->current());exit;
        return $resultSet;
    }

    public function getCart($userId){
        $sqlString = "SELECT * FROM resume_cart ";
        $sqlString .= " join services on services.serviceId=resume_cart.serviceId";
        $sqlString .= " join service_options on service_options.serviceOptionId=resume_cart.serviceOptionId";
        $sqlString .= " where resume_cart.UserId = '".$userId."' and resume_cart.status != 1" ;
        //var_dump($sqlString); exit;
        $resultSet = $this->tableGateway->getAdapter()->driver->getConnection()->execute($sqlString);

        return $resultSet;

    }

    public function getTotalCartCost($userId){
        /*$where['UserId'] = $userId;
        $where['status'] = 0;
        //print_r($where);

        $sql = new Sql($this->tableGateway->adapter);
        $select = $sql->select();
        $select->from($this->tableGateway->getTable());
        $select->where($where);
        //echo  $select->getSqlString(); exit;
        $resultSet = $this->tableGateway->selectWith($select);
        */

        $sqlString = "SELECT so.price FROM service_options so ";
        $sqlString .= " JOIN services s on s.serviceId = so.serviceId";
        $sqlString .= " JOIN resume_cart rc on so.serviceOptionid = rc.serviceOptionId";
        $sqlString .= " where rc.userId = '".$userId."' and rc.status = 0" ;
        //var_dump($sqlString); exit;
        $resultSet = $this->tableGateway->getAdapter()->driver->getConnection()->execute($sqlString);

       // return $resultSet;

        $totalAmount = 0;
        foreach($resultSet as $res){
            //var_dump($res);
            $totalAmount= $totalAmount +  $res['price'];
            //echo $res->price;
        }
        //exit;

        return $totalAmount;

    }

    public function checkIfExist($data){
        $where['UserId'] = $data['UserId'];
        $where['serviceId'] = $data['serviceId'] ;
        $where['serviceOptionId'] =$data['serviceOptionId'] ;
        $where['status'] = 0;
        //print_r($where);

        $sql = new Sql($this->tableGateway->adapter);
        $select = $sql->select();
        $select->from($this->tableGateway->getTable());
        $select->where($where);
       //echo  $select->getSqlString(); exit;
        $resultSet = $this->tableGateway->selectWith($select);

        //return $resultSet->current();
        return $resultSet;
    }
//
    public function updateOrderId($userId, $orderId ){
        $set = array(
            'orderId' => $orderId,
            //'status'=>"0"
        );
        //echo $userId."---------".$orderId."<br>";
        $return =  $this->tableGateway->update($set,array("userId"=>$userId,"status"=>"0"));
        //var_dump($return); exit;
        //$sqlString = "UPDATE resume_cart SET orderId = '".$orderId."' WHERE userId ='".$userId."' AND status='0'";
        //echo $sqlString; exit;
       // $resultSet = $this->tableGateway->getAdapter()->driver->getConnection()->execute($sqlString);

        return $return;
    }

    public function updateResponse($data,$where){
        /*$sqlData = array(
            'userId'=>$userId,
            'orderId' => $orderId,
            'status'=>"1"
        );*/
        return $this->tableGateway->update($data,$where);

    }

    public function save($data){
        $Sqldata = array(
            'cartId'=>$data->cartId,
            'userId'=>$data->UserId,
            'serviceId'=>$data->serviceId,
            'serviceOptionId'=>$data->serviceOptionId,

        );
        return $this->tableGateway->insert($Sqldata);
    }

    public function removeCart($data){
        //$where['UserId'] = $data['UserId'];
        //$where['serviceId'] = $data['serviceId'] ;
        //$where['serviceOptionId'] =$data['serviceOptionId'] ;
        //$where['status'] = 0;

        $sqlString = "DELETE FROM resume_cart where userId='".$data['UserId']."' AND serviceId='".$data['serviceId'] ."' AND serviceOptionId='".$data['serviceOptionId']."' AND status !='1'" ;
        //var_dump($sqlString); exit;

        //echo  $select->getSqlString(); exit;
        try{
            $resultSet = $this->tableGateway->getAdapter()->driver->getConnection()->execute($sqlString);
        } catch(\Exception $e){
            echo $e->getMessage();
        }

        //return $resultSet->current();
        if($resultSet){
            return true;
        } else {
            return false;
        }
    }

    public function getPaymentStatus($email="",$mobile=""){
        $select = "SELECT js.Name,js.Email,js.Mobile,rc.status,rc.dateAdded FROM jobseekers js JOIN resume_cart rc on js.UserId=rc.userId   ";

        if($email!="" && $mobile==""){
            $select .=" WHERE js.Email = '".$email."'";
        }
        if($email=="" && $mobile!=""){
            $select .=" WHERE js.Mobile = '".$mobile."'";
        }
        if($email!="" && $mobile!=""){
            $select .=" WHERE js.Email = '".$email."'";
        }
        $select .="  Order by rc.dateAdded desc";

        //echo $select; exit;
        //echo  $select->getSqlString(); exit;
        $resultSet =  $this->tableGateway->getAdapter()->driver->getConnection()->execute($select);

        //return $resultSet->current();
        return $resultSet;

    }

    /*public function getServiceById($serviceId){
        $sqlString = "SELECT * FROM services join servicePrice on services.serviceId=servicePrice.serviceId where services.serviceId = '".$serviceId."'" ;
        //var_dump($sqlString); exit;
        $resultSet = $this->tableGateway->getAdapter()->driver->getConnection()->execute($sqlString);

        return $resultSet;
    }

    public function getServices($serviceId = "" , $all = "all"){
        $sqlString = "SELECT * FROM services join service_options on services.serviceId=service_options.serviceId ";
        if($serviceId != ""){
            $sqlString .= " where services.serviceId = ".$serviceId."  ";
        }
        if($all == "none" ){
            $sqlString .= " group by services.serviceId";
        }
       // echo $sqlString; exit;
        $resultSet = $this->tableGateway->getAdapter()->driver->getConnection()->execute($sqlString);

        return $resultSet;

    }*/

}


text:
<!DOCTYPE html>

		<link href='https://fonts.googleapis.com/css?family=Architects+Daughter' rel='stylesheet' type='text/css'>
		<meta charset="UTF-8">
		<title>About Game</title>
		<link rel="stylesheet" href="css/tyyli.css" type="text/css">

		<?php include 'divs/navbar.html'; ?>

Coders / Authors / Team members

Ahonen Hanna

Kokkonen Juha-Matti

Kosunen Tommi

Nissi Juho

Pikkarainen Joeli

If you're intrested, visit our github

© DWord

		<?php include 'script/doorbell.js';?>


text:
package com.pongasoft.kiwidoc.testdata.pubdir1;

import java.util.List;

/**
 * @author yan@pongasoft.com
 */
public class Pub1Class4<V> extends Pub1Class2<Integer, Float> implements Pub1Interface2<V>
{
  public static @interface NestedAnnotation
  {
    int value() default 0;
  }

  public static class InnerPub1Class4
  {
    public static class InnerInnerPub1Class4
    {

    }
  }

  public class Inner2Pub1Class4<K>
  {
    public class InnerInner2Pub1Class4<W>
    {

    }
  }

  public class Inner3Pub1Class4
  {
    public class InnerInner3Pub1Class4<W>
    {

    }
  }

  /**
   * Constructor
   */
  public Pub1Class4()
  {
  }

  /**
   * This is the first line
   * and the second one.
   *
   * @param p1 parameter 1
   * @param p2 parameter 2
   * @return a type {@link V} and you should check {@link Pub1Class4<String>}
   */
  public V method1(V p1, List<? extends V> p2)
  {
    return p1;
  }

  /**
   * In Pub1Class4 [ {@inheritDoc} ]
   */
  public void imethod1(V v)
  {
  }

  public void useInnerClass(InnerPub1Class4 p1)
  {

  }

  public void useInnerClass2(Inner2Pub1Class4<Integer> p1)
  {

  }

  public static void staticMethod(Pub1Class4<String>.Inner2Pub1Class4<Integer> p)
  {

  }

  public static void staticMethod2(Pub1Class4<String>.Inner2Pub1Class4<Integer>.InnerInner2Pub1Class4<Double> p)
  {

  }

  public static void staticMethod2(Pub1Class4<String>.Inner3Pub1Class4.InnerInner3Pub1Class4<Double> p)
  {

  }
}


text:
layout: post
title: "From Purok To Barangay: Mapping Informality in Philippine Cities"
category: SDI

excerpt: |
    "I saw the importance of doing settlement profiling and mapping, the use of new technology, and how to encode. At least we learned something. I felt happy."
 – Erlinda Mosqueda, Valenzuela Peoples Organization Network (VALPONET), President/Community Worker

---

**By the Homeless People's Federation of the Philippines, Inc.**, cross posted from Shack/Slum Dwellers International.

![Picture 1]({{ site.url }}/images/blog_images/sdi_phil1.png)

The  Homeless People's Federation of the Philippines, Inc. (HPFPI), commenced their settlement profiling and mapping in January 2015 during a learning exchange supported by the Indian Alliance. The exchange brought together participants from different regions of the country like the NCR, Cebu, Davao and Kidapawanin San Isidro, Jaro, and Iloilo City.  Since then, the Federation and their support staff have been actively mapping and profiling in three cities: Valenzuela, Davao and Iloilo City.

Erlinda Mosqueda, Valenzuela Peoples Organization Network (VALPONET), President/Community Worker, reflects:

*"I had a good experience in doing settlement profiling and mapping. I learned how to use the GPS (Global Positioning System) device. Once I saw our settlement in the computer through the GPS device, I felt it was a success.*

*We also experienced many hardships. Our first step was to have a courtesy call to the head of the Barangay (the smallest government unit of the city) before going to the community. Some communities refused to be interviewed because they were afraid the data that will be gathered might be used against them. In spite of these struggles, we were able to interview 21 communities.*

*I saw the importance of doing settlement profiling and mapping, the use of new technology, and how to encode. At least we learned something. I felt happy.*

*Before I do not know also how to do the settlement profiling. Being president of our network, VALPONET, I want other leaders to know also how to interview using the settlement profiling form and now I am happy that there are already other community leaders who know how to interview using the settlement profiling form.*

*One of our challenges is that only one knows from our network how to upload the settlement profiling form in the computer. It is a challenge for us to learn how to use the computer because this is the trend now.*

*The important thing about doing the settlement profiling and mapping is when one community asks for their own data, the VALPONET is ready to give them."*

Valenzuela City is part of the Metropolitan Manila, Philippines. Together with 16 other cities and a municipality it forms part of the most populous region in the Philippines. A total of 8 settlements have thus far been profiled by the federation. Six of these settlements are undeclared settlements with insecure land tenure with an estimated population of 17,121 persons. The Federation estimates that there are approximately 3,369 structures in total, of which about 376 are residential-cum-business structures and a further 129 full business structures. Businesses in settlements offer access to goods and services within the settlement and serve as a livelihood stream for many families.

![Picture 2]({{ site.url }}/images/blog_images/sdi_phil2.png)

Davao City is a highly urbanised city and said to be the fourth most populous city in the Philippines. The federation has profiled a total of 6 slums thus far with an estimated population of 17,033 persons and an estimated 2657 structures in total of which 2,309 are residential. Securing land tenure is a priority in 5 of these settlements. Access to adequate sanitation and sewerage was named by the 6th settlement as their most important development priority.

![Picture 4]({{ site.url }}/images/blog_images/sdi_phil4.png)

In Iloilo City the federation has profiled two communities thus far. The estimated total population in these communities is 2,261. Both of these settlements are undeclared, with insecure land tenure, security of tenure, and housing identified as the most important community development priorities.

![Picture 5]({{ site.url }}/images/blog_images/sdi_phil5.png)

Of the 23 settlements the Philippine federations has profiled and documented thus far, 13 of these are currently facing eviction threats. Floods and strong winds have been listed as the most often occurring natural disasters.

![Picture 6]({{ site.url }}/images/blog_images/sdi_phil6.png)

![Picture 7]({{ site.url }}/images/blog_images/sdi_phil7.png)

![Picture 8]({{ site.url }}/images/blog_images/sdi_phil8.png)

Interview using the informal settlement profile form

![Picture 9]({{ site.url }}/images/blog_images/sdi_phil9.png)

Interview with barangay officials regarding barangay profile and boundary at Ungka Jaro, Iloilo


text:
var JobRating = chic.Class.extend({
    init: function() {
        $('#jobRatingWrapper').bind('rated', this.rateJob);
    },
    rateJob: function(event, value) {
        console.log('rating the job! ' + value);

        $.ajax({
            type: "POST",
            url: '/job/2/rate',
            data: { rating: value},
            success: this.handleSuccessfulRating
        });
    },
    handleSuccessfulRating: function() {
        console.log('rated the job!');
    }
});


text:
package idiff

import (
	"fmt"
	"reflect"
	"strings"
)

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// FormatTest formats a diff so it's test friendly.
// You can create your own function like this one to format
// how you want to.
func FormatTest(d *DiffResult) string {
	if reflect.TypeOf(d.A) != reflect.TypeOf(d.B) {
		return fmt.Sprintf("types differ. got: %T, expected: %T\n", d.B, d.A)
	}

	var str []string
	for _, added := range d.Added {
		str = append(str, fmt.Sprintf("%T%s: added: %#v\n", d.A, added.Path, added.Value))
	}
	for _, removed := range d.Removed {
		str = append(str, fmt.Sprintf("%T%s: removed: %#v\n", d.A, removed.Path, removed.Value))
	}
	for _, modified := range d.Modified {
		if reflect.TypeOf(modified.A).Kind() == reflect.Func && reflect.ValueOf(modified.A).IsNil() {
			str = append(str, fmt.Sprintf("%T%s: got: not nil, expected: nil\n", d.A, modified.Path))
		} else if reflect.TypeOf(modified.B).Kind() == reflect.Func && reflect.ValueOf(modified.B).IsNil() {
			str = append(str, fmt.Sprintf("%T%s: got: nil, expected: not nil\n", d.A, modified.Path))
		} else {
			str = append(str, fmt.Sprintf("%T%s: got: %#v, expected: %#v\n", d.A, modified.Path, modified.B, modified.A))
		}
	}

	if len(str) > 0 {
		result := strings.Join(str, "")
		return result[:len(result)-1]
	}
	return ""
}

// Diff does a difference of the two passed interfaces.
func Diff(a, b interface{}) (*DiffResult, bool) {
	dr := newDiffResult(a, b)
	equal := dr.diff(reflect.ValueOf(a), reflect.ValueOf(b), "")
	return dr, equal
}

// Added represents a part of the diff where a thing was added.
type Added struct {
	Path  string
	Value interface{}
	A     interface{}
	B     interface{}
}

// Removed represents a part of the diff where a thing was removed.
type Removed struct {
	Path  string
	Value interface{}
	A     interface{}
	B     interface{}
}

// Modified represents a part of the diff where a thing was modified.
type Modified struct {
	Path string
	A    interface{}
	B    interface{}
}

// DiffResult represents a diff of values of two
// interface{}s
type DiffResult struct {
	Added    []Added
	Removed  []Removed
	Modified []Modified

	A interface{}
	B interface{}
}

func newDiffResult(a, b interface{}) *DiffResult {
	return &DiffResult{A: a, B: b}
}

func (dr *DiffResult) diff(v1, v2 reflect.Value, path string) bool {
	if !v1.IsValid() && !v2.IsValid() {
		return true
	}

	if !v1.IsValid() || !v2.IsValid() {
		dr.Modified = append(dr.Modified, Modified{
			Path: path,
			A:    v1.Interface(),
			B:    v2.Interface(),
		})
		return false
	}

	if v1.Type() != v2.Type() {
		dr.Modified = append(dr.Modified, Modified{
			Path: path,
			A:    v1.Interface(),
			B:    v2.Interface(),
		})
		return false
	}

	kind := v1.Type().Kind()
	equal := true
	switch kind {
	// case reflect.Func:
	// 	if !v1.IsNil() || !v2.IsNil() {
	// 		dr.Modified = append(dr.Modified, Modified{
	// 			Path:   path,
	// 			A: v1.Interface(),
	// 			B: v2.Interface(),
	// 		})
	// 		equal = false
	// 	}
	case reflect.Array, reflect.Slice:
		v1Len := v1.Len()
		v2Len := v2.Len()
		for i := 0; i < min(v1Len, v2Len); i++ {
			local := path + fmt.Sprintf("[%d]", i)
			if eq := dr.diff(v1.Index(i), v2.Index(i), local); !eq {
				equal = false
			}
		}
		if v1Len > v2Len {
			for i := v2Len; i < v1Len; i++ {
				local := path + fmt.Sprintf("[%d]", i)
				dr.Removed = append(dr.Removed, Removed{
					Path:  local,
					Value: v1.Index(i).Interface(),
					A:     v1.Interface(),
					B:     v2.Interface(),
				})
				equal = false
			}
		} else if v1Len < v2Len {
			for i := v1Len; i < v2Len; i++ {
				local := path + fmt.Sprintf("[%d]", i)
				dr.Added = append(dr.Added, Added{
					Path:  local,
					Value: v2.Index(i).Interface(),
					A:     v1.Interface(),
					B:     v2.Interface(),
				})
				equal = false
			}
		}
	case reflect.Ptr:
		v1 = v1.Elem()
		v2 = v2.Elem()
		if !v1.IsValid() && !v2.IsValid() {
			equal = true
		} else if !v1.IsValid() || !v2.IsValid() {
			dr.Modified = append(dr.Modified, Modified{
				Path: path,
				A:    v1.Interface(),
				B:    v2.Interface(),
			})
			equal = false
		} else {
			equal = dr.diff(v1, v2, path)
		}
	case reflect.Struct:
		typ := v1.Type()
		for i := 0; i < typ.NumField(); i++ {
			index := []int{i}
			field := typ.FieldByIndex(index)
			local := path + fmt.Sprintf(".%s", field.Name)
			if eq := dr.diff(v1.FieldByIndex(index), v2.FieldByIndex(index), local); !eq {
				equal = false
			}
		}
	case reflect.Map:
		for _, key := range v1.MapKeys() {
			av := v1.MapIndex(key)
			bv := v2.MapIndex(key)
			local := path + fmt.Sprintf("[%#v]", key.Interface())
			if !bv.IsValid() {
				dr.Removed = append(dr.Removed, Removed{
					Path:  local,
					Value: av.Interface(),
					A:     v1.Interface(),
					B:     v2.Interface(),
				})
				equal = false
			} else if eq := dr.diff(av, bv, local); !eq {
				equal = false
			}
		}
		for _, key := range v2.MapKeys() {
			aI := v1.MapIndex(key)
			if !aI.IsValid() {
				bI := v2.MapIndex(key)
				local := path + fmt.Sprintf("[%#v]", key.Interface())
				dr.Added = append(dr.Added, Added{
					Path:  local,
					Value: bI.Interface(),
					A:     v1.Interface(),
					B:     v2.Interface(),
				})
				equal = false
			}
		}
	default:
		if reflect.DeepEqual(v1.Interface(), v2.Interface()) {
			equal = true
		} else {
			dr.Modified = append(dr.Modified, Modified{
				Path: path,
				A:    v1.Interface(),
				B:    v2.Interface(),
			})
			equal = false
		}
	}
	return equal
}


text:
## Introduction
Download website to a local directory (including all css, images, js, etc.)

[![Build Status](https://img.shields.io/travis/s0ph1e/node-website-scraper/master.svg?style=flat)](https://travis-ci.org/s0ph1e/node-website-scraper)
[![Build status](https://ci.appveyor.com/api/projects/status/s7jxui1ngxlbgiav/branch/master?svg=true)](https://ci.appveyor.com/project/s0ph1e/node-website-scraper/branch/master)
[![Test Coverage](https://codeclimate.com/github/s0ph1e/node-website-scraper/badges/coverage.svg)](https://codeclimate.com/github/s0ph1e/node-website-scraper/coverage)
[![Code Climate](https://codeclimate.com/github/s0ph1e/node-website-scraper/badges/gpa.svg)](https://codeclimate.com/github/s0ph1e/node-website-scraper)
[![Dependency Status](https://david-dm.org/s0ph1e/node-website-scraper.svg?style=flat)](https://david-dm.org/s0ph1e/node-website-scraper)

[![Version](https://img.shields.io/npm/v/website-scraper.svg?style=flat)](https://www.npmjs.org/package/website-scraper)
[![Downloads](https://img.shields.io/npm/dm/website-scraper.svg?style=flat)](https://www.npmjs.org/package/website-scraper)
[![Gitter](https://badges.gitter.im/s0ph1e/node-website-scraper.svg)](https://gitter.im/s0ph1e/node-website-scraper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)

[![NPM Stats](https://nodei.co/npm/website-scraper.png?downloadRank=true&stars=true)](https://www.npmjs.org/package/website-scraper)

You can try it in [demo app](https://scraper.nepochataya.pp.ua/) ([source](https://github.com/s0ph1e/web-scraper))

**Note:** dynamic websites (where content is loaded by js) may be saved not correctly because `website-scraper` doesn't execute js, it only parses http responses for html and css files.

## Installation
```
npm install website-scraper
```

## Usage
```javascript
var scrape = require('website-scraper');
var options = {
  urls: ['http://nodejs.org/'],
  directory: '/path/to/save/',
};

// with callback
scrape(options, function (error, result) {
	/* some code here */
});

// or with promise
scrape(options).then(function (result) {
	/* some code here */
});
```

## API
### scrape(options, callback)
Makes requests to `urls` and saves all files found with `sources` to `directory`.

**options** - object containing next options:

 - `urls`: array of urls to load and filenames for them *(required, see example below)*
 - `urlFilter`: function which is called for each url to check whether it should be scraped. *(optional, see example below)*
 - `directory`: path to save loaded files *(required)*
 - `filenameGenerator`: name of one of the bundled filenameGenerators, or a custom filenameGenerator function *(optional, default: 'byType')*
 - `defaultFilename`: filename for index page *(optional, default: 'index.html')*
 - `prettifyUrls`: whether urls should be 'prettified', by having the `defaultFilename` removed *(optional, default: false)*
 - `sources`: array of objects to load, specifies selectors and attribute values to select files for loading *(optional, see example below)*
 - `subdirectories`: array of objects, specifies subdirectories for file extensions. If `null` all files will be saved to `directory` *(optional, see example below)*
 - `request`: object, custom options for [request](https://github.com/request/request#requestoptions-callback) *(optional, see example below)*
 - `recursive`: boolean, if `true` scraper will follow anchors in html files. Don't forget to set `maxDepth` to avoid infinite downloading *(optional, see example below)*
 - `maxDepth`: positive number, maximum allowed depth for dependencies *(optional, see example below)*
 - `ignoreErrors`: boolean, if `true` scraper will continue downloading resources after error occured, if `false` - scraper will finish process and return error *(optional, default: true)*

Default options you can find in [lib/config/defaults.js](https://github.com/s0ph1e/node-website-scraper/blob/master/lib/config/defaults.js).

**callback** - callback function *(optional)*, includes following parameters:

  - `error`: if error - `Error` object, if success - `null`
  - `result`: if error - `null`, if success - array of [Resource](https://github.com/s0ph1e/node-website-scraper/blob/master/lib/resource.js) objects containing:
    - `url`: url of loaded page
    - `filename`: filename where page was saved (relative to `directory`)
    - `children`: array of children Resources

### Filename Generators
The filename generator determines where the scraped files are saved.

#### byType (default)
When the `byType` filenameGenerator is used the downloaded files are saved by type (as defined by the `subdirectories` setting)
or directly in the `directory` folder, if no subdirectory is specified for the specific type.

#### bySiteStructure
When the `bySiteStructure` filenameGenerator is used the downloaded files are saved in `directory` using same structure as on the website:
- `/` => `DIRECTORY/index.html`
- `/about` => `DIRECTORY/about/index.html`
- `/resources/javascript/libraries/jquery.min.js` => `DIRECTORY/resources/javascript/libraries/jquery.min.js`

## Examples
#### Example 1
Let's scrape some pages from [http://nodejs.org/](http://nodejs.org/) with images, css, js files and save them to `/path/to/save/`.
Imagine we want to load:
  - [Home page](http://nodejs.org/) to `index.html`
  - [About page](http://nodejs.org/about/) to `about.html`
  - [Blog](http://blog.nodejs.org/) to `blog.html`

and separate files into directories:

  - `img` for .jpg, .png, .svg (full path `/path/to/save/img`)
  - `js` for .js (full path `/path/to/save/js`)
  - `css` for .css (full path `/path/to/save/css`)

```javascript
var scrape = require('website-scraper');
scrape({
  urls: [
    'http://nodejs.org/',	// Will be saved with default filename 'index.html'
    {url: 'http://nodejs.org/about', filename: 'about.html'},
    {url: 'http://blog.nodejs.org/', filename: 'blog.html'}
  ],
  directory: '/path/to/save',
  subdirectories: [
    {directory: 'img', extensions: ['.jpg', '.png', '.svg']},
    {directory: 'js', extensions: ['.js']},
    {directory: 'css', extensions: ['.css']}
  ],
  sources: [
    {selector: 'img', attr: 'src'},
    {selector: 'link[rel="stylesheet"]', attr: 'href'},
    {selector: 'script', attr: 'src'}
  ],
  request: {
    headers: {
      'User-Agent': 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'
    }
  }
}).then(function (result) {
  console.log(result);
}).catch(function(err){
  console.log(err);
});
```

#### Example 2. Recursive downloading
```javascript
// Links from example.com will be followed
// Links from links will be ignored because theirs depth = 2 is greater than maxDepth
var scrape = require('website-scraper');
scrape({
  urls: ['http://example.com/'],
  directory: '/path/to/save',
  recursive: true,
  maxDepth: 1
}).then(console.log).catch(console.log);
```

#### Example 3. Filtering out external resources
```javascript
// Links to other websites are filtered out by the urlFilter
var scrape = require('website-scraper');
scrape({
  urls: ['http://example.com/'],
  urlFilter: function(url){
    return url.indexOf('http://example.com') === 0;
  },
  directory: '/path/to/save'
}).then(console.log).catch(console.log);
```

#### Example 4. Downloading an entire website
```javascript
// Downloads all the crawlable files of example.com.
// The files are saved in the same structure as the structure of the website, by using the `bySiteStructure` filenameGenerator.
// Links to other websites are filtered out by the urlFilter
var scrape = require('website-scraper');
scrape({
  urls: ['http://example.com/'],
  urlFilter: function(url){
      return url.indexOf('http://example.com') === 0;
  },
  recursive: true,
  maxDepth: 100,
  prettifyUrls: true,
  filenameGenerator: 'bySiteStructure',
  directory: '/path/to/save'
}).then(console.log).catch(console.log);
```

## Log and debug
This module uses [debug](https://github.com/visionmedia/debug) to log events. To enable logs you should use environment variable `DEBUG`.
Next command will log everything from website-scraper
```bash
export DEBUG=website-scraper*; node app.js
```

Module has different loggers for levels: `website-scraper:error`, `website-scraper:warn`, `website-scraper:info`, `website-scraper:debug`, `website-scraper:log`. Please read [debug](https://github.com/visionmedia/debug) documentation to find how to include/exclude specific loggers.


text:
var a = 56;

// let

let b = "message...";

// type
type Person = { name: string, age?: number };

type FilterFunc = ([]: Person[], name: string) => Person[];

// Example

let peopleSortFunc: FilterFunc = (people: Person[] = [], name: string) => {
  return people.filter(person => person.name === name);
};

let otherSortFunc: ([]: Person[], name: string) => Person[] = peopleSortFunc;


text:
/*
 * Portions Copyright (c) Microsoft Corporation
 */

package com.azure.cosmos.implementation.apachecommons.text.translate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class EntityArrays {
    /**
     * A Map<CharSequence, CharSequence> to escape the Java
     * control characters.
     *
     * Namely: {@code \b \n \t \f \r}
     */
    public static final Map<CharSequence, CharSequence> JAVA_CTRL_CHARS_ESCAPE;
    static {
        final Map<CharSequence, CharSequence> initialMap = new HashMap<>();
        initialMap.put("\b", "\\b");
        initialMap.put("\n", "\\n");
        initialMap.put("\t", "\\t");
        initialMap.put("\f", "\\f");
        initialMap.put("\r", "\\r");
        JAVA_CTRL_CHARS_ESCAPE = Collections.unmodifiableMap(initialMap);
    }

    /**
     * Reverse of {@link #JAVA_CTRL_CHARS_ESCAPE} for unescaping purposes.
     */
    public static final Map<CharSequence, CharSequence> JAVA_CTRL_CHARS_UNESCAPE;
    static {
        JAVA_CTRL_CHARS_UNESCAPE = Collections.unmodifiableMap(invert(JAVA_CTRL_CHARS_ESCAPE));
    }

    /**
     * Used to invert an escape Map into an unescape Map.
     * @param map Map<String, String> to be inverted
     * @return Map<String, String> inverted array
     */
    public static Map<CharSequence, CharSequence> invert(final Map<CharSequence, CharSequence> map) {
        final Map<CharSequence, CharSequence> newMap = new HashMap<>();
        for (final Map.Entry<CharSequence, CharSequence> pair : map.entrySet()) {
            newMap.put(pair.getValue(), pair.getKey());
        }
        return newMap;
    }
}


text:
import os
import subprocess
import sys
import textwrap
from contextlib import contextmanager

import jediepcserver as jep

@contextmanager
def osenv(*args, **kwds):
    def putenvs(dct):
        for (k, v) in dct.items():
            if v is None:
                os.environ.pop(k, None)
            else:
                os.environ[k] = v
    newenv = dict(*args, **kwds)
    oldenv = dict(zip(newenv, map(os.getenv, newenv)))
    try:
        putenvs(newenv)
        yield
    finally:
        putenvs(oldenv)

def test_epc_server_runs_fine_in_non_virtualenv():
    # See: https://github.com/tkf/emacs-jedi/issues/3
    with osenv(VIRTUAL_ENV=None):
        jep.jedi_epc_server()

def test_epc_server_runs_fine_in_virtualenv():
    major_version, minor_version = sys.version_info[:2]
    envname = 'py{}{}'.format(major_version, minor_version)
    subprocess.check_call(['tox', '-e', envname, '--notest'])
    relative_venv_path = ".tox/" + envname
    full_venv_path = os.path.join(os.getcwd(), relative_venv_path)

    handler = jep.JediEPCHandler(virtual_envs=[full_venv_path])
    sys_path = handler.get_sys_path()
    venv_path = '{0}/lib/python{1}.{2}/site-packages'.format(
        full_venv_path, major_version, minor_version,
    )
    assert venv_path in sys_path

def check_defined_names(source, keys, deftree):
    stripdict = lambda d: dict((k, d[k]) for k in keys)
    striptree = lambda ds: [stripdict(ds[0])] + list(map(striptree, ds[1:]))
    handler = jep.JediEPCHandler()
    fulldicts = handler.defined_names(textwrap.dedent(source), 'example.py')
    dicts = list(map(striptree, fulldicts))
    assert dicts == deftree

def test_defined_names_imports():
    item = lambda name, local_name: {'name': name, 'local_name': local_name}
    keys = ['name', 'local_name']
    dicts = [
        [item('f', 'f')],
        [item('g', 'g')],
        [item('C', 'C'), [item('h', 'C.h')]],
    ]
    check_defined_names("""
    from module import f
    g = f(f)
    class C:
        h = g
    """, keys, dicts)

def test_defined_names_nested_classes():
    item = lambda name, local_name: {'name': name, 'local_name': local_name}
    keys = ['name', 'local_name']
    dicts = [
        [item('L1', 'L1'),
         [item('L2', 'L1.L2'),
          [item('L3', 'L1.L2.L3'),
           [item('f', 'L1.L2.L3.f')]],
          [item('f', 'L1.L2.f')]],
         [item('f', 'L1.f')]],
        [item('f', 'f')]]
    check_defined_names("""
    class L1:
        class L2:
            class L3:
                def f(): pass
            def f(): pass
        def f(): pass
    def f(): pass
    """, keys, dicts)

def _get_jedi_script_params(src, filename='example.py'):
    source = textwrap.dedent(src)
    lines = source.splitlines()
    return source, len(lines), len(lines[-1]), filename

def test_get_in_function_call():
    params = _get_jedi_script_params("""
    def foo(bar, baz, *qux, **quux):
        pass

    foo(
    """)
    handler = jep.JediEPCHandler()
    result = handler.get_in_function_call(*params)
    assert result == {
        'params': ['bar', 'baz', '*qux', '**quux'],
        'index': 0,
        'call_name': 'foo',
    }

def test_completion_docstring_raises(monkeypatch):
    """Test "complete" handler does not fail if "comp.docstring" raises

    Ref. #339
    """
    def raise_exception(*args, **kwargs):
        raise Exception('hello, world')

    monkeypatch.setattr(
        'jedi.api.classes.Completion.docstring', raise_exception
    )

    params = _get_jedi_script_params("""
    import os

    os.chd
    """)
    handler = jep.JediEPCHandler()
    result = handler.complete(*params)
    assert result == [
        {
            'word': 'chdir',
            'doc': '',
            'description': 'def chdir',
            'symbol': 'f',
        },
    ]


text:
using System.Linq;
using Gauge.CSharp.Lib;
using OpenQA.Selenium;

namespace Gauge.Example.Implementation
{
    public class ScreenGrabber : IScreenGrabber
    {
        public byte[] TakeScreenShot()
        {
            var screenshot = DriverFactory.Driver as ITakesScreenshot;
            return screenshot == null ? Enumerable.Empty<byte>().ToArray() :  screenshot.GetScreenshot().AsByteArray;
        }
    }
}


text:
package com.pa.devbox.di.module;

import android.os.Bundle;

import com.pa.devbox.ui.aty.BaseActivity;
import com.pa.devbox.ui.viewModel.AccountFragModel;
import com.pa.devbox.ui.viewModel.LibListFragModel;
import com.pa.devbox.ui.viewModel.TypeListFragModel;

import dagger.Module;
import dagger.Provides;

/**
 * Description:
 * <p>
 * Author: PandaApe.
 * CreatedAt: 7/5/16 00:09.
 * Email: whailong2010@gmail.com
 */
@Module
public class FragmentModule {

    private BaseActivity context;
    private Bundle savedInstanceState;

    public FragmentModule(BaseActivity context, Bundle savedInstanceState) {
        this.context = context;
        this.savedInstanceState = savedInstanceState;
    }

    @Provides
    TypeListFragModel provideModel() {
        return new TypeListFragModel(context);
    }

    @Provides
    AccountFragModel provideAccountModel() {
        return new AccountFragModel(this.context);
    }

    @Provides
    LibListFragModel provideLibModel() {
        return new LibListFragModel(context,this.savedInstanceState);
    }

    @Provides
    BaseActivity provideContext() {
        return this.context;
    }
}