text:
package org.seckill.config;

import javax.sql.DataSource;

import org.jfaster.mango.datasource.DriverManagerDataSource;
import org.jfaster.mango.operator.Mango;
import org.jfaster.mango.plugin.spring.AbstractMangoFactoryBean;

public class MyMangoFactoryBean extends AbstractMangoFactoryBean{

	 @Override
	    public Mango createMango() {
	        String driverClassName = "com.mysql.jdbc.Driver";
	        String url = "jdbc:mysql://localhost:3306/seckill";
	        String username = "root"; // 这里请使用您自己的用户名
	        String password = "root"; // 这里请使用您自己的密码
	        DataSource ds = new DriverManagerDataSource(driverClassName, url, username, password);
	        Mango mango = Mango.newInstance(ds); // 使用数据源初始化mango
	        return mango;
	    }
}


text:
@Title="Installation"

Our primary distribution channel is [NuGet](https://www.nuget.org/) with
two packages:

- [NodaTime](https://www.nuget.org/packages/NodaTime)
- [NodaTime.Testing](https://www.nuget.org/packages/NodaTime.Testing)

An experimental assembly to support Json.NET is also available (in source form
only); see the [serialization guide](serialization) for more information.

See the ["Building and testing"][building] section in the developer guide for
instructions on building Noda Time from source.

[building]: /developer/building

System requirements
-------------------

Currently Noda Time requires .NET 3.5 (client profile). It supports
Mono ([with some caveats](mono)) but does *not* support
Silverlight (or, by extension, Windows Phone 7). We'd like to
support these in the future, but it will involve a non-trivial
amount of work. The same goes for creating a Portable Class Library project,
although that may be simpler.

Package contents and getting started
------------------------------------

Everything you need to *use* Noda Time is contained in the NodaTime package. The NodaTime.Testing package is designed
for testing code which uses Noda Time. See the [testing guide](testing) for more information. It is expected
that production code will only refer to the `NodaTime.dll` assembly, and that's all that's required at execution time.
This assembly includes the [TZDB database](tzdb) as an embedded resource.

Everything within the NodaTime assembly is in the NodaTime namespace or a "child" namespace. After adding a reference to
the main assembly (either directly via the file system or with NuGet) and including an appropriate `using` directive, you should
be able to start using Noda Time immediately, with no further effort.

redpajama_set_name: RedPajamaGithub


text:
namespace VEngine
{
    namespace Renderer
    {
        namespace Internal
        {
            class VulkanDevice;
        }
        class VulkanShaderModule : public ShaderModuleInterface
        {
        public:
            VulkanShaderModule(Internal::VulkanDevice * device, VEngineShaderModuleType type, std::string path);
            ~VulkanShaderModule();
            VkShaderModule getHandle();
            virtual VEngineShaderModuleType getType() override;

        private:
            VkShaderModule handle;
            Internal::VulkanDevice * device;
            VEngineShaderModuleType type;
        };
    }
}


text:
import hashlib
import os
import sys

utils_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
utils_dir = os.path.join(utils_dir, 'utils')
sys.path.append(utils_dir)

import util

parent_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

cfd = os.path.join(parent_path, 'data', 'intermediate', 'class_file_dirs')
wfd = os.path.join(parent_path, 'data', 'intermediate', 'write_file_dirs')
class_file_dirs = util.load_obj(cfd)
write_file_dirs = util.load_obj(wfd)

class_file_hashes = []
write_file_hashes = []

count = 0
for tup in class_file_dirs:
    if (count % 100000 == 0):
        print('hashed %d class images' % count)

    (cclass, cfile) = tup
    file_path = os.path.join(parent_path, cfile)

    chash = hashlib.md5(open(file_path, 'rb').read()).hexdigest()

    class_file_hashes.append((cclass, cfile, chash))

    count += 1

cfhd = os.path.join(parent_path, 'data', 'intermediate', 'class_file_hashes')
util.save_obj(class_file_hashes, cfhd)

count = 0
for tup in write_file_dirs:
    if (count % 100000 == 0):
        print('hashed %d write images' % count)

    (cclass, cfile) = tup
    file_path = os.path.join(parent_path, cfile)

    chash = hashlib.md5(open(file_path, 'rb').read()).hexdigest()

    write_file_hashes.append((cclass, cfile, chash))

    count += 1

wfhd = os.path.join(parent_path, 'data', 'intermediate', 'write_file_hashes')
util.save_obj(write_file_hashes, wfhd)


text:
using System;
using AspNet.Metrics;
using Metrics;
using Microsoft.Extensions.DependencyInjection.Extensions;

// ReSharper disable CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
// ReSharper restore CheckNamespace
{
    public static class MetricsServiceCollectionExtensions
    {
        public static IMetricsBuilder AddMetrics(this IServiceCollection services)
        {
            return services.AddMetricsCore(null);
        }

        public static IMetricsBuilder AddMetrics(this IServiceCollection services,
            Action<MetricsOptions> setupAction)
        {
            var builder = services.AddMetricsCore(setupAction);

            if (setupAction != null)
            {
                builder.Services.Configure(setupAction);
            }

            return builder;
        }
    }
}


text:
/** @file The maestro! Helper that knows which music tracks can be played, and
 *        which one is playing now, and selects and plays them appropriately. */
'use strict';

var utils = require('./utils');
var _ = utils.getLodash();

var debugLogging = false;
function debug(msg) {
  if (debugLogging && console && console.info) {
    console.info((new Date()).getTime() + ': MusicController: ' + msg);
  }
}

/**
 * @typedef {Object} MusicTrackDefinition
 * External track representation, used to define track info in skins.js.
 *
 * @property {string} name - corresponds to music filenames
 * @property {number} volume - on a 0..1 scale
 * @property {boolean} hasOgg - whether a .ogg version of the file should also
 *           available in addition to the .mp3
 */

/**
 * @typedef {Object} MusicTrack
 * Internal track representation, includes track metadata and references to
 * loaded sound object.
 *
 * @property {string} name
 * @property {string[]} assetUrls
 * @property {number} volume
 * @property {Sound} sound
 * @property {boolean} isLoaded
 */

/**
 * A helper class that handles loading, choosing, playing and stopping
 * background music for certain studio apps (e.g. playlab, craft).
 *
 * @param {AudioPlayer} audioPlayer - Reference to the Sounds object.
 * @param {function} assetUrl - Function for generating paths to static assets
 *        for the current skin.
 * @param {MusicTrackDefinition[]} [trackDefinitions] - List of music assets and
 *        general info about how they should be played. Can be omitted or empty
 *        if no music should be played.
 * @param {Number} [loopRandomWithDelay] - if specified, after a song is
 *        completed, will play a random track after given duration (in ms).
 * @constructor
 */
var MusicController = function (audioPlayer, assetUrl, trackDefinitions,
    loopRandomWithDelay) {
  /** @private {AudioPlayer} */
  this.audioPlayer_ = audioPlayer;

  /** @private {function} */
  this.assetUrl_ = assetUrl;

  /** @private {MusicTrack[]} */
  this.trackList_ = buildTrackData(trackDefinitions, assetUrl);

  /** @private {string} */
  this.nowPlaying_ = null;

  /** @private {string} Name of track to play on load */
  this.playOnLoad_ = null;

  /** @private {number} */
  this.loopRandomWithDelay_ = loopRandomWithDelay;

  /**
   * @private {boolean} whether we stopped playing music due to video being
   *          shown
   */
  this.wasPlayingWhenVideoShown_ = false;

  /** @private {number} setTimeout callback identifier for un-binding repeat */
  this.betweenTrackTimeout_ = null;

  // If the video player gets pulled up, make sure we stop the music.
  document.addEventListener('videoShown', function () {
    debug("video shown");
    if (this.nowPlaying_ || this.betweenTrackTimeout_) {
      this.wasPlayingWhenVideoShown_ = true;

      if (this.betweenTrackTimeout_) {
        window.clearTimeout(this.betweenTrackTimeout_);
        this.betweenTrackTimeout_ = null;
      }
      this.fadeOut();
    }
  }.bind(this));

  // If the video player gets closed, make sure we re-start the music.
  document.addEventListener('videoHidden', function () {
    if (this.wasPlayingWhenVideoShown_ &&
        this.loopRandomWithDelay_ &&
        !this.nowPlaying_) {
      this.play();
    }
    this.wasPlayingWhenVideoShown_ = false;
  }.bind(this));

  debug('constructed');
};
module.exports = MusicController;

/**
 * Build up initial internal track metadata.
 * @param {MusicTrackDefinition[]} trackDefinitions
 * @param {function} assetUrl
 * @return {MusicTrack[]}
 */
function buildTrackData(trackDefinitions, assetUrl) {
  trackDefinitions = utils.valueOr(trackDefinitions, []);
  return trackDefinitions.map(function (trackDef) {

    var assetUrls = [];
    assetUrls.push(assetUrl(trackDef.name + '.mp3'));
    if (trackDef.hasOgg) {
      assetUrls.push(assetUrl(trackDef.name + '.ogg'));
    }

    return {
      name: trackDef.name,
      assetUrls: assetUrls,
      volume: utils.valueOr(trackDef.volume, 1),
      sound: null,
      isLoaded: false
    };
  });
}

/**
 * Preload all music assets
 */
MusicController.prototype.preload = function () {
  if (!this.audioPlayer_) {
    return;
  }

  this.trackList_.forEach(function (track) {
    track.sound = this.audioPlayer_.registerByFilenamesAndID(
        track.assetUrls, track.name);
    track.sound.onLoad = function () {
      debug('done loading ' + track.name);
      track.isLoaded = true;
      if (this.playOnLoad_ === track.name) {
        this.play(track.name);
      }
    }.bind(this);
  }, this);
};

/**
 * Begins playing a particular piece of music immediately.
 * @param {string} trackName
 */
MusicController.prototype.play = function (trackName) {
  debug('play ' + trackName);
  if (!this.audioPlayer_) {
    return;
  }

  var track;
  if (trackName) {
    track = this.getTrackByName_(trackName);
  } else {
    track = this.getRandomTrack_();
  }

  if (!track) {
    // No track to play - throw an exception?
    return;
  }

  if (track.sound && track.isLoaded) {
    debug('playing now');
    var callback = this.whenMusicStopped_.bind(this, track.name);
    track.sound.play({ volume: track.volume, onEnded: callback });
    this.nowPlaying_ = track.name;
  } else {
    debug('not done loading, playing after load');
    this.playOnLoad_ = track.name;
  }
};

/**
 * Stops playing whatever music is currently playing, immediately.
 */
MusicController.prototype.stop = function () {
  if (!this.nowPlaying_) {
    return;
  }

  var sound = this.audioPlayer_.get(this.nowPlaying_);
  if (sound) {
    sound.stop();
  }
};

/**
 * Fades music to nothing, then stops it.
 * @param {number} [durationSeconds] in seconds.  Default 3.
 */
MusicController.prototype.fadeOut = function (durationSeconds) {
  if (!this.nowPlaying_) {
    return;
  }

  durationSeconds = utils.valueOr(durationSeconds, 3);

  // Trigger a fade
  var sound = this.audioPlayer_.get(this.nowPlaying_);
  if (sound) {
    sound.fadeToGain(0, durationSeconds);
  }

  // Stop the audio after the fade.
  // Add a small margin due to poor fade granularity on fallback player.
  window.setTimeout(function () {
    this.stop();
  }.bind(this), 1000 * durationSeconds + 100);
};

/**
 * Callback for when music stops, to update internal state.
 * @param {string} musicName that was playing.  Should be bound when music
 *        is started.
 * @private
 */
MusicController.prototype.whenMusicStopped_ = function (musicName) {
  if (this.nowPlaying_ === musicName) {
    this.nowPlaying_ = null;
  }
  if (this.loopRandomWithDelay_ && !this.wasPlayingWhenVideoShown_) {
    this.betweenTrackTimeout_ = window.setTimeout(function () {
      this.betweenTrackTimeout_ = null;
      if (!this.nowPlaying_ && !this.wasPlayingWhenVideoShown_) {
        this.play();
      }
    }.bind(this), this.loopRandomWithDelay_);
  }
};

/**
 * @param {string} name
 * @returns {MusicTrack|undefined}
 * @private
 */
MusicController.prototype.getTrackByName_ = function (name) {
  return _.find(this.trackList_, function (track) {
    return track.name === name;
  });
};

/**
 * @returns {MusicTrack|undefined}
 * @private
 */
MusicController.prototype.getRandomTrack_ = function () {
  var trackIndex = Math.floor(Math.random() * this.trackList_.length);
  return this.trackList_[trackIndex];
};


text:
require 'spec_helper'

describe 'pound::service', :type => :class do

  it { should contain_service('pound') }

end


text:
namespace MvvX.Plugins.HockeyApp
{
    /// <summary>
    /// interface for a hockeyapp feedback thread
    /// </summary>
    public interface IHockeyAppThread
    {
        /// <summary>
        /// time of creation as string
        /// </summary>
        string CreatedAt { get; }

        /// <summary>
        /// unique id
        /// </summary>
        int Id { get; }

        /// <summary>
        /// status
        /// </summary>
        int Status { get; }

        /// <summary>
        /// unique token for this thread
        /// </summary>
        string Token { get; }
    }
}


text:
package io.katharsis.internal.boot.cdi.model;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.enterprise.context.ApplicationScoped;

import io.katharsis.queryspec.QuerySpec;
import io.katharsis.repository.annotations.JsonApiDelete;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiFindAllWithIds;
import io.katharsis.repository.annotations.JsonApiFindOne;
import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;
import io.katharsis.resource.exception.ResourceNotFoundException;

@JsonApiResourceRepository(Task.class)
@ApplicationScoped
public class TaskRepository {

	private static final ConcurrentHashMap<Long, Task> map = new ConcurrentHashMap<>();

	public static void clear() {
		map.clear();
	}

	@JsonApiSave
	public <S extends Task> S save(S entity) {

		if (entity.getId() == null) {
			entity.setId((long) (map.size() + 1));
		}
		map.put(entity.getId(), entity);

		return entity;
	}

	@JsonApiFindOne
	public Task findOne(Long aLong, QuerySpec querySpec) {
		Task task = map.get(aLong);
		if (task == null) {
			throw new ResourceNotFoundException("");
		}
		return task;
	}

	@JsonApiFindAll
	public Iterable<Task> findAll(QuerySpec queryParams) {
		return queryParams.apply(map.values());
	}

	@JsonApiFindAllWithIds
	public Iterable<Task> findAll(Iterable<Long> ids, QuerySpec queryParams) {
		List<Task> values = new LinkedList<>();
		for (Task value : map.values()) {
			if (contains(value, ids)) {
				values.add(value);
			}
		}
		return values;
	}

	private boolean contains(Task value, Iterable<Long> ids) {
		for (Long id : ids) {
			if (value.getId().equals(id)) {
				return true;
			}
		}

		return false;
	}

	@JsonApiDelete
	public void delete(Long aLong) {
		map.remove(aLong);
	}
}


text:
package com.ming.myweather.util;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by Ming on 2017/7/22.
 */
public class HttpUtil {
    public static void sendHttpRequest(String url, Callback callback){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(callback);
    }
}


text:
$(function () {
//    if ($.cookie('admin_leftbar_collapse') === 'collapse-leftbar') {
//        $('body').addClass('collapse-leftbar');
//    } else {
//        $('body').removeClass('collapse-leftbar');
//    }

    $('body').on('click', 'ul.acc-menu a', function () {
        var LIs = $(this).closest('ul.acc-menu').children('li');
        $(this).closest('li').addClass('clicked');
        $.each(LIs, function (i) {
            if ($(LIs[i]).hasClass('clicked')) {
                $(LIs[i]).removeClass('clicked');
                return true;
            }
            if ($.cookie('admin_leftbar_collapse') !== 'collapse-leftbar' || $(this).parents('.acc-menu').length > 1)
                $(LIs[i]).find('ul.acc-menu:visible').slideToggle();
            $(LIs[i]).removeClass('open');
        });
        if ($(this).siblings('ul.acc-menu:visible').length > 0)
            $(this).closest('li').removeClass('open');
        else
            $(this).closest('li').addClass('open');
        if ($.cookie('admin_leftbar_collapse') !== 'collapse-leftbar' || $(this).parents('.acc-menu').length > 1)
            $(this).siblings('ul.acc-menu').slideToggle({
                duration: 200,
                progress: function () {
                    checkpageheight();
                    if ($(this).closest('li').is(":last-child")) { //only scroll down if last-child
                        $("#sidebar").animate({scrollTop: $("#sidebar").height()}, 0);
                    }

                },
                complete: function () {
                    $("#sidebar").getNiceScroll().resize();
                }
            });
    });

    var targetAnchor;
    $.each($('ul.acc-menu a'), function () {
        //console.log(this.href);

        if (this.href == window.location) {
            targetAnchor = this;
            return false;
        }
    });

    var parent = $(targetAnchor).closest('li');
    while (true) {
        parent.addClass('active');
        parent.closest('ul.acc-menu').show().closest('li').addClass('open');
        parent = $(parent).parents('li').eq(0);
        if ($(parent).parents('ul.acc-menu').length <= 0)
            break;
    }

    var liHasUlChild = $('li').filter(function () {
        return $(this).find('ul.acc-menu').length;
    });
    $(liHasUlChild).addClass('hasChild');

//    if ($.cookie('admin_leftbar_collapse') === 'collapse-leftbar') {
//        $('ul.acc-menu:first ul.acc-menu').css('visibility', 'hidden');
//    }
    $('ul.acc-menu:first > li').hover(function () {
        if ($.cookie('admin_leftbar_collapse') === 'collapse-leftbar')
            $(this).find('ul.acc-menu').css('visibility', '');
    }, function () {
        if ($.cookie('admin_leftbar_collapse') === 'collapse-leftbar')
            $(this).find('ul.acc-menu').css('visibility', 'hidden');
    });

    // Reads Cookie for Collapsible Leftbar
    // if($.cookie('admin_leftbar_collapse') === 'collapse-leftbar')
    //     $("body").addClass("collapse-leftbar");

    //Make only visible area scrollable
//    $("#widgetarea").css({"max-height": $("body").height()});
    //Bind widgetarea to nicescroll
//    $("#widgetarea").niceScroll({horizrailenabled: false});

    // Toggle Buttons
    // ------------------------------

    //On click of left menu
//    $("a#leftmenu-trigger").click(function () {
//        if ((window.innerWidth) < 768) {
//            $("body").toggleClass("show-leftbar");
//        } else {
//            $("body").toggleClass("collapse-leftbar");
//
//            //Sets Cookie for Toggle
//            if ($.cookie('admin_leftbar_collapse') === 'collapse-leftbar') {
//                $.cookie('admin_leftbar_collapse', '');
//                $('ul.acc-menu').css('visibility', '');
//
//            } else {
//                $.each($('.acc-menu'), function () {
//                    if ($(this).css('display') == 'none')
//                        $(this).css('display', '');
//                });
//
//                $('ul.acc-menu:first ul.acc-menu').css('visibility', 'hidden');
//                $.cookie('admin_leftbar_collapse', 'collapse-leftbar');
//            }
//        }
//        checkpageheight();
//        leftbarScrollShow();
//    });

    // On click of right menu
//    $("a#rightmenu-trigger").click(function () {
//        $("body").toggleClass("show-rightbar");
//        widgetheight();
//
//        if ($.cookie('admin_rightbar_show') === 'show-rightbar')
//            $.cookie('admin_rightbar_show', '');
//        else
//            $.cookie('admin_rightbar_show', 'show-rightbar');
//    });

    //set minimum height of page
    dh = ($(document).height() - 40);
    $("#page-content").css("min-height", dh + "px");
    //checkpageheight();

});

// Recalculate widget area on a widget being shown
$(".widget-body").on('shown.bs.collapse', function () {
    widgetheight();
});

// -------------------------------
// Sidebars Positionings
// -------------------------------

$(window).scroll(function () {
    if ($("#widgetarea").length > 0) {
        $("#widgetarea").getNiceScroll().resize();
    }
    if ($(".chathistory").length > 0) {
        $(".chathistory").getNiceScroll().resize();
    }
    rightbarTopPos();
    leftbarTopPos();
});

$(window).resize(function () {
    widgetheight();

    rightbarRightPos();
    if ($("#sidebar").length > 0) {
        $("#sidebar").getNiceScroll().resize();
    }
});
rightbarRightPos();

// -------------------------------
// Mobile Only - set sidebar as fixed position, slide
// -------------------------------

enquire.register("screen and (max-width: 767px)", {
    match: function () {
        // For less than 768px
        $(function () {

            //Bind sidebar to nicescroll
            $("#sidebar").niceScroll({horizrailenabled: false});
            leftbarScrollShow();

            //Click on body and hide leftbar
            $("#wrap").click(function () {
                if ($("body").hasClass("show-leftbar")) {
                    $("body").removeClass("show-leftbar");
                    leftbarScrollShow();
                }
            });

            //Fix a bug
            $('#sidebar ul.acc-menu').css('visibility', '');

            //open up leftbar
            $("body").removeClass("show-leftbar");
            $.removeCookie("admin_leftbar_collapse");

            $("body").removeClass("collapse-leftbar");

        });

        console.log("match");
    },
    unmatch: function () {

        //Remove nicescroll to clear up some memory
        $("#sidebar").niceScroll().remove();
        $("#sidebar").css("overflow", "visible");

        console.log("unmatch");

        //hide leftbar
        $("body").removeClass("show-leftbar");

    }
});

//Helper functions
//---------------

//Fixing the show of scroll rails even when sidebar is hidden
function leftbarScrollShow() {
    if ($("body").hasClass("show-leftbar")) {
        $("#sidebar").getNiceScroll().show();
    } else {
        $("#sidebar").getNiceScroll().hide();
    }
    $("#sidebar").getNiceScroll().resize();
}

//set Top positions for changing between static and fixed header
function leftbarTopPos() {
    var scr = $('body.static-header').scrollTop();
    if (scr < 41) {
        $('ul#sidebar').css('top', 40 - scr + 'px');
    } else {
        $('ul#sidebar').css('top', 0);
    }
}

function rightbarTopPos() {
    var scr = $('body.static-header').scrollTop();
    if ($('#page-rightbar').length > 0) {
        if (scr < 41) {
            $('#page-rightbar').css('top', 40 - scr + 'px');
        } else {
            $('#page-rightbar').css('top', 0);
        }
    }
}

//Set Right position for fixed layouts
function rightbarRightPos() {
    if ($('body').hasClass('fixed-layout')) {
        var $pc = $('#page-content');
        var ending_right = ($(window).width() - ($pc.offset().left + $pc.outerWidth()));
        if (ending_right < 0)
            ending_right = 0;
        $('#page-rightbar').css('right', ending_right);
    }
}

// Match page height with Sidebar Height
function checkpageheight() {
    sh = $("#page-leftbar").height();
    ch = $("#page-content").height();

    if (sh > ch)
        $("#page-content").css("min-height", sh + "px");
}

// Recalculate widget area to area visible
function widgetheight() {
    $("#widgetarea").css({"max-height": $("body").height()});
    $("#widgetarea").getNiceScroll().resize();
}

// -------------------------------
// Back to Top button
// -------------------------------

$('#back-to-top').click(function () {
    $('body,html').animate({
        scrollTop: 0
    }, 500);
    return false;
});

// -------------------------------
// Panel Collapses
// -------------------------------
$('a.panel-collapse').click(function () {
    $(this).children().toggleClass("fa-chevron-down fa-chevron-up");
    $(this).closest(".panel-heading").next().slideToggle({duration: 200});
    $(this).closest(".panel-heading").toggleClass('rounded-bottom');
    return false;
});

// -------------------------------
// Quick Start
// -------------------------------
$('#headerbardropdown').click(function () {
    $('#headerbar').css('top', 0);
    return false;
});

$('#headerbardropdown').click(function (event) {
    $('html').one('click', function () {
        $('#headerbar').css('top', '-1000px');
    });

    event.stopPropagation();
});

// -------------------------------
// Keep search open on click
// -------------------------------
$('#search>a').click(function () {
    $('#search').toggleClass('keep-open');
    $('#search>a i').toggleClass("opacity-control");
});

$('#search').click(function (event) {
    $('html').one('click', function () {
        $('#search').removeClass('keep-open');
        $('#search>a i').addClass("opacity-control");
    });

    event.stopPropagation();
});

//Presentational: set all panel-body with br0 if it has panel-footer
$(".panel-footer").prev().css("border-radius", "0");


text:
package com.secdec.codepulse.util

import java.io.File
import java.io.OutputStream
import java.util.zip._

import scala.collection.JavaConversions._
import scala.util.Success
import scala.util.Try

import org.apache.commons.io.FileUtils
import org.apache.commons.io.IOUtils

/** A helper to clean up sludge in zip files as they're being copied into the StorageManager.
  *
  * The primary purpose for this is to remove the __MACOSX folder and .DS_Store files that
  * OS X insists on creating/adding. FindBugs, in particular, has issues with processing when
  * the __MACOSX folder exists.
  *
  * @author robertf
  */
object ZipCleaner {
	// filter out __MACOSX from the root, and .svn folders / .DS_Store files all over
	private val Filter = """^__MACOSX(?:/.*)?$|(?:^|.*/)\.svn(?:/.*)?$|(?:^|.*/)\.DS_Store$""".r

	private def needsFiltering(file: ZipFile) = file.entries.exists(shouldFilter)

	/** Checks whether or not a given zip entry should be filtered */
	def shouldFilter(e: ZipEntry) = Filter.pattern.matcher(e.getName).matches

	/** Filters a zip, from a file to an output stream. Zips that do not contain offending files
	  * are left unaltered, as are files that aren't zips.
	  */
	def cleanZip(source: File)(out: OutputStream) {
		val zip = Try(new ZipFile(source))

		zip match {
			case Success(zip) if needsFiltering(zip) =>
				// filtering is necessary, so build a new zip on the output stream
				val zout = new ZipOutputStream(out)
				try {
					for (entry <- zip.entries.filterNot(shouldFilter)) {
						zout.putNextEntry(new ZipEntry(entry.getName))

						val in = zip.getInputStream(entry)
						try {
							IOUtils.copyLarge(in, zout)
						} finally {
							in.close
						}
					}
				} finally {
					zout.close
				}

			case _ =>
				// not a zip, or doesn't need filtering. just copy it.
				FileUtils.copyFile(source, out)
		}

		zip.foreach(_.close)
	}
}


text:
package definitions

import "testing"
import "flag"
import "fmt"
import "log"
import "os/user"

func init() {
	flag.Parse()

	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	str := fmt.Sprintf("%s/git/cuview", usr.HomeDir)
	BaseDirectory = &str

}

func TestLoadApiDefs(t *testing.T) {
	defs := LoadAPIDefs()
	expected_version := "2.0"
	if expected_version != defs.SwaggerVer {
		t.Errorf("expected_version == %q, want %q",
			defs.SwaggerVer, expected_version)
	}
}


text:
<?php

class I18nTest extends AimeosTestAbstract
{
	public function testGet()
	{
		$aimeos = $this->app->make( '\Aimeos\Shop\Base\Aimeos' );

		$configMock = $this->getMockBuilder( '\Illuminate\Config\Repository' )
			->setMethods( array( 'get', 'has' ) )->getMock();

		$configMock->expects( $this->once() )->method( 'has' )
			->will( $this->returnValue( true ) );

		$configMock->expects( $this->exactly( 3 ) )->method( 'get' )
			->will( $this->onConsecutiveCalls( true, 'laravel:', array() ) );

		$object = new \Aimeos\Shop\Base\I18n( $configMock, $aimeos );
		$list = $object->get( array( 'en' ) );

		$this->assertInstanceOf( '\Aimeos\Base\Translation\Iface', $list['en'] );
	}
}


text:
File Watcher
==============

This is a utility for watching a set of files in a directory,
then triggering a build and restarting a process when those files change.

It will recursively traverse the directories from the current working directory, and watch for changes in any
files that match the specified pattern.

It accepts three arguments on the command line.

* `-build-cmd` The command to rebuild your source.
* `-run-cmd` The command to run your process.
* `-file-pattern` The file pattern to monitor.  This only accepts simple patterns at the moment, like `*.go`, `manifest.json` etc
etc


text:
package org.edx.mobile.services;

import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

import com.google.inject.Inject;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.edx.mobile.R;
import org.edx.mobile.http.RestApiManager;
import org.edx.mobile.logger.Logger;
import org.edx.mobile.model.DownloadDescriptor;
import org.edx.mobile.module.analytics.ISegment;
import org.edx.mobile.module.prefs.PrefManager;
import org.edx.mobile.util.NetworkUtil;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import roboguice.service.RoboService;

/**
 * Created by marcashman on 2014-12-01.
 */
public class DownloadSpeedService extends RoboService {

    private static final String TAG = DownloadSpeedService.class.getCanonicalName();
    private static final long NS_PER_SEC = 1000000000;
    private static final int BLOCK_SIZE = 4096;

    public static final String EXTRA_FILE_DESC = TAG + ".file_desc";
    public static final String EXTRA_REPORT_PROGRESS = TAG + ".report_progress";
    public static final String EXTRA_KBPS = TAG + ".kbps";
    public static final String EXTRA_SECONDS = TAG + ".seconds";
    public static final String EXTRA_ERROR = TAG + ".error";
    public static final String ACTION_DOWNLOAD_DONE = TAG + ".download_done";

    private static final int RUN_SPEED_TEST_MESSAGE = 5555;

    private int DELAY_IN_MILLISECONDS = 5000;

    private static final Logger logger = new Logger(DownloadSpeedService.class);

    @Inject
    private ISegment segIO;

    @Inject
    RestApiManager apiManager;

    SpeedTestHandler messageHandler;

    Timer timer = null;
    TimerTask timerTask = null;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if(intent != null) {
            Message msg = messageHandler.obtainMessage();

            DownloadDescriptor descriptor = intent.getParcelableExtra(EXTRA_FILE_DESC);
            if (descriptor != null) {
                msg.obj = descriptor;
                msg.what = RUN_SPEED_TEST_MESSAGE;
                messageHandler.sendMessage(msg);
            } else {
                logger.warn("missing file description");
            }
        }
        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        startThread();

        DELAY_IN_MILLISECONDS = getResources().getInteger(R.integer.delay_speed_test_in_milliseconds);

        super.onCreate();
    }

    private void startThread(){
        HandlerThread thread = new HandlerThread("SpeedTestThread", android.os.Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
        Looper serviceLooper = thread.getLooper();
        messageHandler = new SpeedTestHandler(serviceLooper);
    }

    private synchronized void performDownload(DownloadDescriptor file) {

        final long startTime;

        try {
            startTime = System.nanoTime();

            Request request = new Request.Builder()
                .url(file.getUrl())
                .build();

            apiManager.createSpeedTestClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException throwable) {
                    logger.error(throwable);
                    //If it times out, set a low value for download speed
                    setCurrentDownloadSpeed(0.01f);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        logger.debug("Download Speed Test Failed");
                    } else {
                        long length = response.body().string().length();
                        double seconds = (System.nanoTime() - startTime) / NS_PER_SEC;
                        if( seconds != 0 ) {
                            final float downloadSpeedKps = (float) ((length / seconds) / 1024);
                            setCurrentDownloadSpeed(downloadSpeedKps);
                            reportDownloadSpeed(downloadSpeedKps);
                        }
                    }
                }
            });
        }catch (Exception ex){
            logger.error(ex);
        }

    }

    private void reportDownloadSpeed(float downloadSpeedKps){
        try{

            if (NetworkUtil.isConnectedWifi(DownloadSpeedService.this)) {
                segIO.trackUserConnectionSpeed(ISegment.Values.WIFI,   downloadSpeedKps);
            } else if (NetworkUtil.isConnectedMobile(DownloadSpeedService.this)) {
                segIO.trackUserConnectionSpeed(ISegment.Values.CELL_DATA,   downloadSpeedKps);
            }

        }catch(Exception e){
            logger.error(e);
        }
    }

    private void setCurrentDownloadSpeed(float downloadSpeedKps){
        PrefManager manager = new PrefManager(this, PrefManager.Pref.WIFI);
        manager.put(PrefManager.Key.SPEED_TEST_KBPS, downloadSpeedKps);
    }

    public class SpeedTestHandler extends Handler {
        public SpeedTestHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int messageType = msg.what;

            if(messageType == RUN_SPEED_TEST_MESSAGE){
                final DownloadDescriptor file = (DownloadDescriptor) msg.obj;
                if(file != null){
                    scheduleNewDownload(file);
                }
            }
        }
    }

    private void scheduleNewDownload(final DownloadDescriptor file) {
        if(timerTask != null) {
            timerTask.cancel();
            timer.cancel();
            timerTask = null;
            timer = null;
        }

        if(file.shouldForceDownload()) {
            performDownload(file);
        } else {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    performDownload(file);
                }
            };

            timer = new Timer();

            timer.schedule(timerTask, DELAY_IN_MILLISECONDS);
        }
    }

}


text:
//-----------------------------------------------------------------------------
//
//	SwitchMultilevel.h
//
//	Implementation of the Z-Wave COMMAND_CLASS_SWITCH_MULTILEVEL
//
//	Copyright (c) 2010 Mal Lansell <openzwave@lansell.org>
//
//	SOFTWARE NOTICE AND LICENSE
//
//	This file is part of OpenZWave.
//
//	OpenZWave is free software: you can redistribute it and/or modify
//	it under the terms of the GNU Lesser General Public License as published
//	by the Free Software Foundation, either version 3 of the License,
//	or (at your option) any later version.
//
//	OpenZWave is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU Lesser General Public License for more details.
//
//	You should have received a copy of the GNU Lesser General Public License
//	along with OpenZWave.  If not, see <http://www.gnu.org/licenses/>.
//
//-----------------------------------------------------------------------------

#ifndef _SwitchMultilevel_H
#define _SwitchMultilevel_H

#include "CommandClass.h"

namespace OpenZWave
{
	class ValueBool;
	class ValueButton;
	class ValueByte;

	/** \brief Implements COMMAND_CLASS_SWITCH_MULTILEVEL (0x26), a Z-Wave device command class.
	 */
	class SwitchMultilevel: public CommandClass
	{
	public:
		static CommandClass* Create( uint32 const _homeId, uint8 const _nodeId ){ return new SwitchMultilevel( _homeId, _nodeId ); }
		virtual ~SwitchMultilevel(){}

		static uint8 const StaticGetCommandClassId(){ return 0x26; }
		static string const StaticGetCommandClassName(){ return "COMMAND_CLASS_SWITCH_MULTILEVEL"; }

		// From CommandClass
		virtual bool RequestState( uint32 const _requestFlags, uint8 const _instance, Driver::MsgQueue const _queue );
		virtual bool RequestValue( uint32 const _requestFlags, uint8 const _index, uint8 const _instance, Driver::MsgQueue const _queue );
		virtual uint8 const GetCommandClassId()const{ return StaticGetCommandClassId(); }
		virtual string const GetCommandClassName()const{ return StaticGetCommandClassName(); }
		virtual bool HandleMsg( uint8 const* _data, uint32 const _length, uint32 const _instance = 1 );
		virtual bool SetValue( Value const& _value );
		virtual void SetValueBasic( uint8 const _instance, uint8 const _value );
		virtual void SetVersion( uint8 const _version );

		virtual uint8 GetMaxVersion(){ return 3; }

	protected:
		virtual void CreateVars( uint8 const _instance );

	private:
		enum SwitchMultilevelDirection
		{
			SwitchMultilevelDirection_Up = 0,
			SwitchMultilevelDirection_Down,
			SwitchMultilevelDirection_Inc,
			SwitchMultilevelDirection_Dec
		};

		SwitchMultilevel( uint32 const _homeId, uint8 const _nodeId ): CommandClass( _homeId, _nodeId ){}

		bool SetLevel( uint8 const _instance, uint8 const _level );
		bool StartLevelChange( uint8 const _instance, SwitchMultilevelDirection const _direction );
		bool StopLevelChange( uint8 const _instance );
	};

} // namespace OpenZWave

#endif


text:
"""
WV2RadiometricCorrection
========================

This module reads parameters from a DigitalGlobe supplied xml file and applies
radiometric correction to WorldView-2 imagery according to the instructions
found here::

DigitalGlobe, 2010. Radiometric Use of WorldView-2 Imagery.
http://www.digitalglobe.com/downloads/Radiometric_Use_of_WorldView-2_Imagery.pdf

For usage instructions, execute::

    $ python WV2RadiometricCorrection.py -h

Notes
=====

This module gives results that are very close to, but not the same as, the Orfeo
Toolbox [Optical Calibration
module](https://www.orfeo-toolbox.org/CookBook/CookBooksu35.html). I think this
may be because the OTB module is using general parameters for WV-2 imagery while
this module is using specific parameters from the image's xml file. So, I am
reasonably certain this module is working as intended. On the other hand, I
really haven't investigated the issue. If you look into it, please let me know
what you find out. At some point I need to do some more testing and add in much
more thorough automated tests.
"""

from xml.etree.ElementTree import ElementTree as ET
from collections import OrderedDict
from datetime import datetime
from osgeo import gdal
from osgeo.gdalconst import *
import argparse, os, sys
import numpy as np

## Raster handling #########################################
# I'll want to integrate this module with the rest of OpticalRS by using the
# RasterDS module to do this stuff. For now, I'm doing it this way. ...this does
# have the benefit of making this a stand alone module relying only on the gdal
# import.

def open_raster(filename):
    """Take a file path as a string and return a gdal datasource object"""
    # register all of the GDAL drivers
    gdal.AllRegister()

    # open the image
    img = gdal.Open(filename, GA_ReadOnly)
    if img is None:
        print 'Could not open %s' % filename
        sys.exit(1)
    else:
        return img

def bandarr_from_ds(img):
    """Take a raster datasource and return a band array. Each band is read
    as an array and becomes one element of the band array."""
    for band in range(1,img.RasterCount + 1):
        barr = img.GetRasterBand(band).ReadAsArray()
        if band==1:
            bandarr = np.array([barr])
        else:
            bandarr = np.append(bandarr,[barr],axis=0)
    return bandarr

def output_gtif(bandarr, cols, rows, outfilename, geotransform, projection, no_data_value=-99, driver_name='GTiff', dtype=GDT_Float32):
    """Create a geotiff with gdal that will contain all the bands represented
    by arrays within bandarr which is itself array of arrays."""
    # make sure bandarr is a proper band array
    if len( bandarr.shape )==2:
        bandarr = np.array([ bandarr ])
    driver = gdal.GetDriverByName(driver_name)
    outDs = driver.Create(outfilename, cols, rows, len(bandarr), dtype)
    if outDs is None:
        print "Could not create %s" % outfilename
        sys.exit(1)
    for bandnum in range(1,len(bandarr) + 1):  # bandarr is zero based index while GetRasterBand is 1 based index
        outBand = outDs.GetRasterBand(bandnum)
        outBand.WriteArray(bandarr[bandnum - 1])
        outBand.FlushCache()
        outBand.SetNoDataValue(no_data_value)

    # georeference the image and set the projection
    outDs.SetGeoTransform(geotransform)
    outDs.SetProjection(projection)

    # build pyramids
    gdal.SetConfigOption('HFA_USE_RRD', 'YES')
    outDs.BuildOverviews(overviewlist=[2,4,8,16,32,64,128])

def output_gtif_like_img(img, bandarr, outfilename, no_data_value=-99, dtype=GDT_Float32):
    """Create a geotiff with attributes like the one passed in but make the
    values and number of bands as in bandarr."""
    cols = img.RasterXSize
    rows = img.RasterYSize
    geotransform = img.GetGeoTransform()
    projection = img.GetProjection()
    output_gtif(bandarr, cols, rows, outfilename, geotransform, projection, no_data_value, driver_name='GTiff', dtype=dtype)

## End of Raster Handling stuff ################################################

"""These values are taken from Table 4 in DigitalGlobe's Radiometric Use of WorldView-2
Imagery technical note. See references.txt for more info."""
Esun_od = OrderedDict((
        ('BAND_C', 1758.2229),
        ('BAND_B', 1974.2416),
        ('BAND_G', 1856.4104),
        ('BAND_Y', 1738.4791),
        ('BAND_R', 1559.4555),
        ('BAND_RE', 1342.0695),
        ('BAND_N', 1069.7302),
        ('BAND_N2', 861.2866),
    ))

def julian_date2(date):
    """Returns the Julian day number of a date. I got the code for this method
    from a post on the internet. I've included it just to check my results."""
    a = (14 - date.month)//12
    y = date.year + 4800 - a
    m = date.month + 12*a - 3
    return date.day + ((153*m + 2)//5) + 365*y + y//4 - y//100 + y//400 - 32045

def julian_date(date):
    """Returns the julian day of a date and includes the decimal portion. These
    calculations were taken from section 6.1.1 of Radiometric Use of WorldView-2
    Imagery. See references.txt for more information."""
    year = date.year
    month = date.month
    day = date.day
    UT = date.hour + date.minute/60.0 + date.second/3600.0
    if year <= 2:
        year = year - 1
        month += 12
    A = year // 100
    B = 2 - A + A // 4
    JD = int( 365.25 * (year + 4716) ) + int( 30.6001 * (month + 1) ) + day + UT / 24.0 + B - 1524.5
    return JD

## Methods for dealing with WV2 xml files #######################
def get_xml_filename(fname):
    """If filename has xml extension, just pass it back. If not, see
    if there's a file in the same directory with an xml file extension
    and pass that back. Deal with different cases.

    >>> get_xml_filename('porkchop.XML')
    'porkchop.XML'

    >>> get_xml_filename('porkchop.xml')
    'porkchop.xml'

    >>> get_xml_filename('porkchop.xML')
    'porkchop.xML'

    >>> get_xml_filename('porkchop.TIF')
    'porkchop.XML'

    >>> get_xml_filename('porkchop.tif')
    'porkchop.xml'

    >>> get_xml_filename('porkchop.Tif')
    'porkchop.xml'
    """
    # get file extension of input file
    fext = fname.split(os.path.extsep)[-1]
    if fext.lower() != 'xml': # Did we get passed something other than xml?
        # assume that extension case is consistent with what we've been passed
        if fext.isupper():
            fname = fname.replace(os.path.extsep+fext,os.path.extsep+'XML')
        elif fext.islower():
            fname = fname.replace(os.path.extsep+fext,os.path.extsep+'xml')
        else: # this would mean the extension is mixed case. Not likely
            fname = fname.replace(os.path.extsep+fext,os.path.extsep+'xml')
    return fname

def get_xmlroot(filepath):
    """Return ElementTree root of xml file. You can pass in the path to the actual
    xml file or a path to a tif with the same name as the xml file."""
    filepath = get_xml_filename(filepath)
    tree = ET()
    tree.parse(filepath)
    return tree

def absCalFactor_dict(xmlroot):
    """Get an ordered dictionary with the xml tags for the image bands as keys
    and the absCalFactors as values. We will assume that the order of the bands
    in the xml file is the same as the order of the bands in the tif image. This
    seems to hold true in my experience."""
    imd = xmlroot.find('IMD')
    bandtags = [ x.tag for x in imd.getchildren() if x.tag.startswith('BAND_') ]
    od = OrderedDict()
    for bt in bandtags:
        val = float( imd.find(bt + '/ABSCALFACTOR').text )
        od.update({bt:val})
    return od

def effectiveBandwidth_dict(xmlroot):
    """Get an ordered dictionary with the xml tags for the image bands as keys
    and the effectiveBandwidth as values. We will assume that the order of the bands
    in the xml file is the same as the order of the bands in the tif image. This
    seems to hold true in my experience."""
    imd = xmlroot.find('IMD')
    bandtags = [ x.tag for x in imd.getchildren() if x.tag.startswith('BAND_') ]
    od = OrderedDict()
    for bt in bandtags:
        val = float( imd.find(bt + '/EFFECTIVEBANDWIDTH').text )
        od.update({bt:val})
    return od

def firstLineTime(xmlroot):
    """Get firstLineTime from the xml. This assumes that we are dealing with a standard
    WV-2 product. Apparently the xml structure is different for Basic products. Then again,
    you would probably have to follow a different procedure for those products so it is a
    moot point."""
    date_string = xmlroot.find('IMD/MAP_PROJECTED_PRODUCT/EARLIESTACQTIME').text
    date_string = date_string.rsplit('.')[0] # ditch the decimal seconds because I can't figure out the next line with them and I don't think the distance from the earth to the sun changes much in less than a second
    return datetime.strptime(date_string,'%Y-%m-%dT%H:%M:%S')

def firstLineJD(xmlroot):
    """Get the firstLineTime with the previous method and return the result as a Julian Date."""
    return julian_date(firstLineTime(xmlroot))

def meanSunEl(xmlroot):
    """Get the mean sun elevation angle from the xml."""
    return float(xmlroot.find('IMD/IMAGE/MEANSUNEL').text)

def meanOffNadirViewAngle(xmlroot):
    """Get the mean off nadir view angle from the xml."""
    return float(xmlroot.find('IMD/IMAGE/MEANOFFNADIRVIEWANGLE').text)

def solarZenithAngle(xmlroot):
    """Calculate the solar zenith angle from the mean sun elevation."""
    return 90.0 - meanSunEl(xmlroot)

def earthSunDistance(xmlroot):
    """Calculate the earth to sun distance based on the Julian Date.
    The formula is from Radiometric Use of WorldView-2 Imagery (see references.txt)"""
    JD = firstLineJD(xmlroot)
    D = JD - 2451545.0
    g = 357.529 + 0.98560028 * D
    return 1.00014 - 0.01671 * np.cos( np.radians(g) ) - 0.00014 * np.cos( np.radians( 2 * g ) )

### End of Methods for dealing with WV2 xml ###############################

def dark_pixel_finder(bandarr,prcnt=0.001):
    """
    Note: I'm messing up the terminology here. I need to straighten this out.
    You probably shouldn't use this unless you're sure you know what you're
    doing.

    Find the darkest pixels in bandarr. Pixel darkness will be determined by
    ranking pixels according to the mean of the pixel values across all bands
    plus 2*std deviation. An array of the row,col coordinates of the darkest
    pixels will be returned.
    """
    # build an array of darkness values that will be of the same dimensions
    # as an individual band of the image
    darkness = bandarr.mean(axis=0) + 2 * bandarr.std(axis=0)
    # build an array of non-zero darkness values in the first row, row coordinates
    # in the second row, and column coordinates in the third row
    d = np.array([darkness[darkness.nonzero()],darkness.nonzero()[0],darkness.nonzero()[1]])
    # sort d by darkness values
    dsort = d[:,d[0,:].argsort()]
    # figure out the number of darkest pixels to get using prcnt of nonzero darkness values
    npix = int( len(dsort[0]) * prcnt )
    # slice the sorted array and transpose it to get an array of [row,col] pairs
    coords = dsort[1:,:npix].T
    return coords.astype(np.int16)

def dark_pixel_subtraction(bandarr,prcnt=0.001,verbose=False):
    """
    Note: I'm messing up the terminology here. I need to straighten this out.
    You probably shouldn't use this unless you're sure you know what you're
    doing.

    This method uses the dark_pixel_finder method to get pixel coordinates for
    the darkest pixels in the images and uses those pixels to calculate the value
    to subtract from each band in the image. If verbose is set to true, the values
    calculated for each band will be printed.

    The methods were taken from Equation 7.1 of Lesson 7: Compensating
    for variable water depth from UNESCO's BILKO documentation. That in turn
    was taken from Lyzenga, 1978 Passive remote sensing techniques for mapping
    water depth and bottom features. That was actually taken from Polcyn 1970, I
    think. The Bilko lesson uses the subtraction of 2 standard deviations as does
    Deidda and Sanna 2012 but I'm not seeing that subtraction in Polcyn 1970 and
    Lyzenga 1978.
    """
    coords = dark_pixel_finder(bandarr,prcnt)
    for bnum in range(len(bandarr)):
        barr = bandarr[bnum]
        dark = barr[coords[:,0],coords[:,1]]
        subvalue = mean_minus_2_stdev(dark)
        barr = barr - subvalue
        barr[np.where(barr<=0.0)] = 0.0
        bandarr[bnum] = barr
        if verbose:
            print "%.2f subtracted from band %i" % (subvalue,bnum+1)
    return bandarr

def dark_pixel_proof_output(img,prcnt=0.001,outfilename=None):
    """Produce a geotiff that shows where the dark pixels came from. This
    is pretty much just a testing method and should not see much use."""
    coords = dark_pixel_finder(img,prcnt)
    band = img.GetRasterBand(1)
    bandarr = np.zeros((band.YSize,band.XSize),int)
    bandarr[coords[:,0],coords[:,1]] = 1
    bandarr = np.array([bandarr])
    if outfilename == None:
        outfilename = img.GetDescription().replace('.tif','_dp_proof.tif')
    output_gtif_like_img(img,bandarr,outfilename)

def toa_radiance(bandarr,absCal,effBand):
    """Take an array radiometrically corrected image pixels (the standard WV2 product),
    the absolute radiometric calibration factor for the band (absCal), and the effective
    bandwidth (effBand) and return an array of top of atmosphere spectral radiance pixels.
    The formula used is toa_rad(pixel) = ( absCal * bandarr(pixel) ) / effBand
    The formula is from Radiometric Use of WorldView-2 Imagery (see references.txt)

    >>> toa_radiance(np.array([[1,2,3,4],[5,6,7,8]]),4,2)
    array([[ 2,  4,  6,  8],
           [10, 12, 14, 16]])
    """
    outarr = (absCal * bandarr) / effBand
    return outarr

def toa_radiance_multiband(bandarr,xmlorimagepath):
    """Take a band array (bandarr) representing a raster with multiple bands and
    use the toa_radiance method to modify the multi band array and then pass it back.

    xmlorimagepath can be the actual path to the xml file or it can be the path to a tif
    with the same file name. See get_xml_filename and get_xmlroot for details."""
    # get necessary values from the xml
    xmlroot = get_xmlroot(xmlorimagepath)
    abfd = absCalFactor_dict(xmlroot)
    ebd = effectiveBandwidth_dict(xmlroot)

    for band in range(len(bandarr)):
        toa_arr = toa_radiance(bandarr[band],abfd.values()[band],ebd.values()[band])
        if band==0:
            toabandarr = np.array([toa_arr])
        else:
            toabandarr = np.append(toabandarr,[toa_arr],axis=0)
    return toabandarr

def toa_reflectance(bandarr,absCal,effBand,eSun,distES,solarZenith):
    """Calculate top of atmosphere reflectance. The formula is from section 7 of Radiometric
    Use of WorldView-2 Imagery (see references.txt) bandarr here is an array for a single band."""
    toa_rad_arr = toa_radiance(bandarr,absCal,effBand)
    outarr = ( toa_rad_arr * (distES**2) * np.pi ) / ( eSun * np.cos( np.radians(solarZenith) ) )
    return np.clip(outarr, 0.0, 1.0)

def toa_reflectance_multiband(bandarr,xmlorimagepath):
    """Take a band array (bandarr) representing a raster with multiple bands and
    use the toa_reflectance method to modify the multi band array and then pass
    it back.

    xmlorimagepath can be the actual path to the xml file or it can be the path to a tif
    with the same file name. See get_xml_filename and get_xmlroot for details."""
    # get necessary values from the xml
    xmlroot = get_xmlroot(xmlorimagepath)
    abfd = absCalFactor_dict(xmlroot)
    ebd = effectiveBandwidth_dict(xmlroot)
    distES = earthSunDistance(xmlroot)
    solarZenith = solarZenithAngle(xmlroot)
    # loop through the bands
    for band in range( len(bandarr) ):
        toa_arr = toa_reflectance(bandarr[band],abfd.values()[band],ebd.values()[band],Esun_od.values()[band],distES,solarZenith)
        if band==0:
            toabandarr = np.array([toa_arr])
        else:
            toabandarr = np.append(toabandarr,[toa_arr],axis=0)
    return toabandarr

def output_toa_reflectance(img_path,outpath=None,xmlpath=None):
    """
    Calculate the top of atmosphere reflectance for all bands in img and write out
    a geotiff. If outpath is provided, that is where the geotif will be written
    otherwise, it will be written to the same directory as img with _toa_ref appended to
    the filename before the extension.

    This is the method to use if you want to operate from the python console."""
    img = open_raster(img_path)
    # get the array of band arrays - defined in common.py
    bandarr = bandarr_from_ds(img)

    if xmlpath:
        toabandarr = toa_reflectance_multiband(bandarr,xmlpath)
    else:
        toabandarr = toa_reflectance_multiband(bandarr,img_path)

    if outpath==None:
        fext = img_path.split(os.path.extsep)[-1]
        outpath = img_path.replace(os.path.extsep+fext,'_toa_ref'+os.path.extsep+fext)

    output_gtif_like_img(img, toabandarr, outpath)

def output_toa_radiance(img_path,outpath=None,xmlpath=None):
    """
    Use the toa_radiance method to calculate toa radiance for all bands in img and
    write out a geotiff. If outpath is provided, that is where the geotif will be written
    otherwise, it will be written to the same directory as img with _toa_rad appended to
    the filename before the extension.

    This is the method to use if you want to operate from the python console."""
    img = open_raster(img_path)
    # get the array of band arrays - defined in common.py
    bandarr = bandarr_from_ds(img)
    if xmlpath:
        toabandarr = toa_radiance_multiband(bandarr,xmlpath)
    else:
        toabandarr = toa_radiance_multiband(bandarr,img_path)

    if outpath==None:
        fext = img_path.split(os.path.extsep)[-1]
        outpath = img_path.replace(os.path.extsep+fext,'_toa_rad'+os.path.extsep+fext)

    output_gtif_like_img(img, toabandarr, outpath)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Perform top of atmosphere reflectance (default) or top of atmosphere radiance correction on DigitalGlobe WorldView-2 imagery by reading XML file and applying corrections based on data in the XML file.')
    parser.add_argument('infile', nargs='?', help='The file that you would like to apply corrections to.', default='doctest')
    parser.add_argument('outfile', nargs='?', help='The corrected output file. If not specified, the output will have the same file name as the input with \'_corrected\' appended to it.')
    parser.add_argument('-v','--verbose', help='Print a bunch of stuff that you probably aren\'t interested in.', action='store_true')
    parser.add_argument('--radiance', help='Return top of atmosphere radiance instead of continuing on a returning top of atmosphere reflectance.', action='store_true')
    parser.add_argument('--xmlfile', help='Path to the xml file that contains the DigitalGlobe image data. When left unspecified, we will look for a file with the same name as the input image file with a .xml file extension.')
    parser.add_argument('--darkpixel', help='Include dark pixel subtraction correction. Look at references.txt and the doc string for dark_pixel_subtraction method for more information.', action='store_true')
    parser.add_argument('--dp_fraction', type=float, help='The fraction of darkest pixels to use with the dark pixel subtraction. Default is 0.001. See the doc string for dark_pixel_finder and dark_pixel_subtraction for more information.')
    parser.add_argument('--doctest', help='Run doctests for this module.', action='store_true')

    args = parser.parse_args()

    if args.doctest or args.infile=='doctest':
        import doctest
        doctest.testmod()
        if not args.doctest:
            print "This module just got tested. If that was not what you were aiming for run with '-h' for help."
        sys.exit(1)

    if not args.outfile:
        if args.infile.find('.TIF') != -1:
            args.outfile = args.infile.replace('.TIF','_corrected.TIF')
        elif args.infile.find('.tif') != -1:
            args.outfile = args.infile.replace('.tif','_corrected.tif')
        else:
            raise Exception("Your input file doesn't seem to have a tif extension so I can not come up with an output file name for you.")

    if args.xmlfile:
        xml_path = args.xmlfile
    else:
        # this works because get_xml_filename works out all the details later on
        xml_path = args.infile

    img = open_raster(args.infile)
    bandarr = bandarr_from_ds(img)
    if args.radiance:
        bandarr = toa_radiance_multiband(bandarr,xml_path)
    else:
        bandarr = toa_reflectance_multiband(bandarr,xml_path)

    if args.darkpixel:
        bandarr = dark_pixel_subtraction(bandarr)

    output_gtif_like_img(img,bandarr,args.outfile)

    print 'Results written to: %s' % args.outfile


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_window_focused="false" android:drawable="@drawable/delete_text_click" />
    <item android:state_pressed="true" android:drawable="@drawable/delete_text_click" />
    <item android:state_focused="false" android:drawable="@drawable/delete_text_click" />
    <item android:drawable="@drawable/delete_text" />
</selector>


text:
# ----------------------------------------------------------------------------------
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

function Test-CreateAndGetService
{
	$rg = Create-ResourceGroupForTest
	try
	{
		$service = Create-DataMigrationService($rg)

		#Get all service
		$all = Get-AzureRmDataMigrationService -ResourceGroupName $rg.ResourceGroupName
		Assert-AreEqual 1 $all.Count

		#Get specific service
		$all = Get-AzureRmDataMigrationService -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name

		Assert-AreEqual $service.Name $all[0].Name
		Assert-AreEqual $rg.Location $all[0].Location
		Assert-AreEqual $service.Service.VirtualSubnetId $all[0].Service.VirtualSubnetId

		#Get random service - should get Not Found
		Assert-ThrowsContains { $all = Get-AzureRmDataMigrationService -ResourceGroupName $rg.ResourceGroupName -Name Get-ServiceName;} "NotFound"
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}

function Test-StopStartDataMigrationService
{
	$rg = Create-ResourceGroupForTest
	try
	{
		$service = Create-DataMigrationService($rg)
		#Stop Service
		Stop-AzureRmDataMigrationService -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name

		$all = Get-AzureRmDataMigrationService -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name
		Assert-AreEqual 1 $all.Count
		Assert-AreEqual "Stopped" $all[0].Service.ProvisioningState

		#Start Service
		Start-AzureRmDataMigrationService -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name

		$all = Get-AzureRmDataMigrationService -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name
		Assert-AreEqual 1 $all.Count
		Assert-AreEqual "Succeeded" $all[0].Service.ProvisioningState
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}

function Test-CreateAndGetProjectSqlSqlDb
{
	$rg = Create-ResourceGroupForTest

	try
	{
		$service = Create-DataMigrationService($rg)

		$project = Create-ProjectSqlSqlDb $rg $service

		#Get Project for a service
		$all = Get-AzureRmDataMigrationProject -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name

		#Service Will contain only One Project for this test case
		# Test case May FAIL if you are using Existing Service
		Assert-AreEqual $all.Count 1

		#Get specific projet
		$all = Get-AzureRmDataMigrationProject -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name

		Assert-AreEqual $project.Name $all[0].Name
		Assert-AreEqual SQL $all[0].Project.SourcePlatform
		Assert-AreEqual SQLDB $all[0].Project.TargetPlatform

		#Get random project should get Not Found
		Assert-ThrowsContains { $all = Get-AzureRmDataMigrationProject -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName Get-ProjectName;} "NotFound"
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}

function Test-RemoveService
{
	# Setup
	$rg = Create-ResourceGroupForTest

	try
	{
		$service = Create-DataMigrationService($rg)
		# Test using parameters
		Remove-AzureRmDataMigrationService -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -Force

		Assert-ThrowsContains { $all = Get-AzureRmDataMigrationService -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name ;} "NotFound"
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}

function Test-RemoveProject
{
	# Setup
	$rg = Create-ResourceGroupForTest

	try
	{
		$service = Create-DataMigrationService($rg)
		$project = Create-ProjectSqlSqlDb $rg $service
		# Test using parameters
		Remove-AzureRmDataMigrationProject -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -Force

		Assert-ThrowsContains { $all = Get-AzureRmDataMigrationProject -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name ;} "NotFound"
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}

function Test-ConnectToSourceSqlServer
{
	$rg = Create-ResourceGroupForTest

	try
	{
		$service = Create-DataMigrationService($rg)
		$project = Create-ProjectSqlSqlDb $rg $service
		$taskName = Get-TaskName
		$connectionInfo = New-SourceSqlConnectionInfo
		$userName = "psadmin"
		$password = [Microsoft.Azure.Commands.DataMigrationConfig]::GetConfigString("SQL_PASSWORD")
		$cred = Get-Creds $userName $password

		$task = New-AzureRmDataMigrationTask -TaskType ConnectToSourceSqlServer -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -SourceConnection $connectioninfo -SourceCred $cred

		$task = Get-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand

		Assert-AreEqual $taskName $task[0].Name
		Assert-AreEqual 1 $task.Count

		while(($task.ProjectTask.Properties.State -eq "Running") -or ($task.ProjectTask.Properties.State -eq "Queued"))
		{
			SleepTask 15
			$task = Get-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand
		}

		Assert-AreEqual "Succeeded" $task.ProjectTask.Properties.State

		Remove-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Force

		Assert-ThrowsContains { $all = Get-AzureRmDmsTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand ;} "NotFound"
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}

function Test-ConnectToTargetSqlDb
{
	$rg = Create-ResourceGroupForTest

	try
	{
		$service = Create-DataMigrationService($rg)
		$project = Create-ProjectSqlSqlDb $rg $service
		$taskName = Get-TaskName
		$connectionInfo = New-TargetSqlConnectionInfo
		$userName = "admin0"
		$password = [Microsoft.Azure.Commands.DataMigrationConfig]::GetConfigString("SQLDB_PASSWORD")
		$cred = Get-Creds $userName $password

		$task = New-AzureRmDataMigrationTask -TaskType ConnectToTargetSqlDb -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -TargetConnection $connectioninfo -TargetCred $cred

		$task = Get-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand

		Assert-AreEqual $taskName $task[0].Name
		Assert-AreEqual 1 $task.Count

		while(($task.ProjectTask.Properties.State -eq "Running") -or ($task.ProjectTask.Properties.State -eq "Queued"))
		{
			SleepTask 15
			$task = Get-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand
		}

		Assert-AreEqual "Succeeded" $task.ProjectTask.Properties.State

		Remove-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Force

		Assert-ThrowsContains { $all = Get-AzureRmDmsTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand ;} "NotFound"
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}

function Test-GetUserTableTask
{
	$rg = Create-ResourceGroupForTest

	try
	{
		$service = Create-DataMigrationService($rg)
		$project = Create-ProjectSqlSqlDb $rg $service
		$taskName = Get-TaskName
		$connectionInfo = New-SourceSqlConnectionInfo
		$userName = "psadmin"
		$password = [Microsoft.Azure.Commands.DataMigrationConfig]::GetConfigString("SQL_PASSWORD")
		$cred = Get-Creds $userName $password
		$selectedDbs = @("tpcc_528MB")

		$task = New-AzureRmDataMigrationTask -TaskType GetUserTablesSql -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -SourceConnection $connectioninfo -SourceCred $cred -SelectedDatabase $selectedDbs

		$task = Get-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand

		Assert-AreEqual $taskName $task[0].Name
		Assert-AreEqual 1 $task.Count

		while(($task.ProjectTask.Properties.State -eq "Running") -or ($task.ProjectTask.Properties.State -eq "Queued"))
		{
			SleepTask 15
			$task = Get-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand
		}

		Assert-AreEqual "Succeeded" $task.ProjectTask.Properties.State

		Remove-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Force

		Assert-ThrowsContains { $all = Get-AzureRmDmsTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand ;} "NotFound"
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}

function Test-MigrateSqlSqlDB
{
	$rg = Create-ResourceGroupForTest

	try
	{
		$service = Create-DataMigrationService($rg)
		$project = Create-ProjectSqlSqlDb $rg $service
		$taskName = Get-TaskName

		#Source Connection Details
		$sourceConnectionInfo = New-SourceSqlConnectionInfo
		$sourceUserName = "psadmin"
		$sourcePassword = [Microsoft.Azure.Commands.DataMigrationConfig]::GetConfigString("SQL_PASSWORD")
		$sourceCred = Get-Creds $sourceUserName $sourcePassword

		#Target Connection Details
		$targetConnectionInfo = New-TargetSqlConnectionInfo
		$targetUserName = "admin0"
		$targetPassword = [Microsoft.Azure.Commands.DataMigrationConfig]::GetConfigString("SQLDB_PASSWORD")
		$targetCred = Get-Creds $targetUserName $targetPassword

		$tableMap = New-Object 'system.collections.generic.dictionary[string,string]'
		$tableMap.Add("dbo.CUSTOMER", "dbo.CUSTOMER")
		$tableMap.Add("dbo.DISTRICT","dbo.DISTRICT")
		$tableMap.Add("dbo.HISTORY","dbo.HISTORY")
		$tableMap.Add("dbo.ITEM","dbo.ITEM")
		$tableMap.Add("dbo.NEW_ORDER","dbo.NEW_ORDER")
		$tableMap.Add("dbo.ORDER_LINE","dbo.ORDER_LINE")
		$tableMap.Add("dbo.ORDERS","dbo.ORDERS")
		$tableMap.Add("dbo.STOCK","dbo.STOCK")
		$tableMap.Add("dbo.WAREHOUSE","dbo.WAREHOUSE")

		$selectedDbs = New-AzureRmDmsSqlServerSqlDbSelectedDB -Name tpcc_528MB -TargetDatabaseName psTarget -TableMap $tableMap

		$migTask = New-AzureRmDmsTask -TaskType MigrateSqlServerSqlDb -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -SourceConnection $sourceConnectionInfo -SourceCred $sourceCred -TargetConnection $targetConnectionInfo -TargetCred $targetCred -SelectedDatabase  $selectedDbs

		$task = Get-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand

		Assert-AreEqual $taskName $task[0].Name
		Assert-AreEqual 1 $task.Count

		while(($task.ProjectTask.Properties.State -eq "Running") -or ($task.ProjectTask.Properties.State -eq "Queued"))
		{
			SleepTask 15
			$task = Get-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand
		}

		Assert-AreEqual "Succeeded" $task.ProjectTask.Properties.State

		Remove-AzureRmDataMigrationTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Force

		Assert-ThrowsContains { $all = Get-AzureRmDmsTask -ResourceGroupName $rg.ResourceGroupName -ServiceName $service.Name -ProjectName $project.Name -TaskName $taskName -Expand ;} "NotFound"
	}
	finally
	{
		Remove-ResourceGroupForTest $rg
	}
}


text:
Reports conditional expressions with then and <c>else</c> branches that are similar enough so that the expression can be moved
inside. This action shortens the code.

Example:

  double g(int a, int b) {
    return a == b ? Math.cos(0) : Math.cos(1);
  }

After the quick-fix is applied:

  double g(int a, int b) {
    return Math.cos(a == b ? 0 : 1);
  }

New in 2017.2


text:
class CGame
{
protected:
	LPDIRECT3D9 _d3d;
	LPDIRECT3DDEVICE9 _d3ddv;
	LPDIRECT3DSURFACE9 _BackBuffer;

	void _Init();

	DWORD _DeltaTime;		// Time between the last frame and current frame
	int _Mode;				// Screen mode
	int _IsFullScreen;		// Is running in fullscreen mode?
	int _FrameRate;

	int _ScreenWidth;
	int _ScreenHeight;
	int _Depth;

	D3DFORMAT _BackBufferFormat;

	HINSTANCE _hInstance;	// Handle of the game instance
	HWND _hWnd;				// Handle of the Game Window

	LPWSTR _Name;			// Name of game will be used as Window Class Name

	void _SetScreenDimension(int Mode);

	static LRESULT CALLBACK _WinProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

	void _InitWindow();
	void _InitDirectX();

	// Render a single frame
	void _RenderFrame();

	// Place holder for sub classes

	virtual void RenderFrame(LPDIRECT3DDEVICE9 d3ddv, int Delta);
	virtual void LoadResources(LPDIRECT3DDEVICE9 d3ddv);

public:
	LPDIRECT3D9 GetDirectX();
	LPDIRECT3DDEVICE9 GetDevice();
	LPDIRECT3DSURFACE9 GetBackBuffer();

	int GetMode();

	int GetScreenWidth();
	int GetScreenHeight();
	int GetDepth();

	int FrameRate;			// Desired frame rate of game

	CGame(HINSTANCE hInstance, LPWSTR Name, int Mode, int IsFullscreen, int FrameRate);
	~CGame();

	// Initialize the game with set parameters
	void Init();

	// Run game
	void Run();
};

#endif


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package plataformatcc;

/**
 *
 * @author Marcielli
 */
public class TelaPrincipal extends javax.swing.JFrame {

    static int check=0;

    /**
     * Creates new form TelaPrincipal
     */
    public TelaPrincipal(int numero) {
        initComponents();
        check = numero;

        if (check == 1) {
        MenuCadastro.setVisible(false);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu6 = new javax.swing.JMenu();
        jMenu7 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem9 = new javax.swing.JMenuItem();
        jMenuItem14 = new javax.swing.JMenuItem();
        jMenuItem11 = new javax.swing.JMenuItem();
        jMenuItem23 = new javax.swing.JMenuItem();
        jMenuItem24 = new javax.swing.JMenuItem();
        jMenuItem25 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jdpprincipal = new javax.swing.JDesktopPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        MenuCadastro = new javax.swing.JMenu();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenuItem22 = new javax.swing.JMenuItem();
        jMenuItem21 = new javax.swing.JMenuItem();
        jMenuItem20 = new javax.swing.JMenuItem();
        MenuTCC = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem26 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        MenuSair = new javax.swing.JMenuItem();
        jMenu5 = new javax.swing.JMenu();
        jMenuItem5 = new javax.swing.JMenuItem();

        jMenu6.setText("File");
        jMenuBar2.add(jMenu6);

        jMenu7.setText("Edit");
        jMenuBar2.add(jMenu7);

        jMenuItem4.setText("jMenuItem4");

        jMenuItem9.setText("jMenuItem9");

        jMenuItem14.setText("jMenuItem14");

        jMenuItem11.setText("jMenuItem11");

        jMenuItem23.setText("jMenuItem23");

        jMenuItem24.setText("jMenuItem24");

        jMenuItem25.setText("jMenuItem25");

        jMenuItem1.setText("jMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sistema de TCC");
        setPreferredSize(new java.awt.Dimension(999, 720));
        setResizable(false);
        getContentPane().setLayout(null);

        javax.swing.GroupLayout jdpprincipalLayout = new javax.swing.GroupLayout(jdpprincipal);
        jdpprincipal.setLayout(jdpprincipalLayout);
        jdpprincipalLayout.setHorizontalGroup(
            jdpprincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 999, Short.MAX_VALUE)
        );
        jdpprincipalLayout.setVerticalGroup(
            jdpprincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 720, Short.MAX_VALUE)
        );

        getContentPane().add(jdpprincipal);
        jdpprincipal.setBounds(0, 0, 999, 720);

        jMenu1.setText("Arquivo");

        MenuCadastro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/database_add.png"))); // NOI18N
        MenuCadastro.setText("Cadastro");

        jMenuItem6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/user_go.png"))); // NOI18N
        jMenuItem6.setText("Cadastrar Funcionário");
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem6ActionPerformed(evt);
            }
        });
        MenuCadastro.add(jMenuItem6);

        jMenuItem22.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/folder_table.png"))); // NOI18N
        jMenuItem22.setText("Cadastrar Cronograma");
        jMenuItem22.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem22ActionPerformed(evt);
            }
        });
        MenuCadastro.add(jMenuItem22);

        jMenuItem21.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/folder_user.png"))); // NOI18N
        jMenuItem21.setText("Cadastrar Grupo");
        jMenuItem21.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem21ActionPerformed(evt);
            }
        });
        MenuCadastro.add(jMenuItem21);

        jMenuItem20.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/folder_page_white.png"))); // NOI18N
        jMenuItem20.setText("Cadastrar Temas");
        jMenuItem20.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem20ActionPerformed(evt);
            }
        });
        MenuCadastro.add(jMenuItem20);

        jMenu1.add(MenuCadastro);

        MenuTCC.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/folder_explore.png"))); // NOI18N
        MenuTCC.setText("TCCs");

        jMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/application_view_tile.png"))); // NOI18N
        jMenuItem2.setText("Temas");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        MenuTCC.add(jMenuItem2);

        jMenuItem26.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/date.png"))); // NOI18N
        jMenuItem26.setText("Cronograma");
        jMenuItem26.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem26ActionPerformed(evt);
            }
        });
        MenuTCC.add(jMenuItem26);

        jMenu1.add(MenuTCC);
        jMenu1.add(jSeparator1);

        MenuSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/cancel.png"))); // NOI18N
        MenuSair.setText("Sair");
        MenuSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuSairActionPerformed(evt);
            }
        });
        jMenu1.add(MenuSair);

        jMenuBar1.add(jMenu1);

        jMenu5.setText("Ajuda");
        jMenu5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu5ActionPerformed(evt);
            }
        });

        jMenuItem5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/plataformatcc/lightbulb.png"))); // NOI18N
        jMenuItem5.setText("Sobre");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jMenu5.add(jMenuItem5);

        jMenuBar1.add(jMenu5);

        setJMenuBar(jMenuBar1);

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem20ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem20ActionPerformed
        ArquivoCadTemas1 obj=new ArquivoCadTemas1();
        jdpprincipal.add(obj);
        obj.setVisible(true);

    }//GEN-LAST:event_jMenuItem20ActionPerformed

    private void jMenuItem21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem21ActionPerformed
        ArquivoCadastroGrupo1 obj=new ArquivoCadastroGrupo1();
        jdpprincipal.add(obj);
        obj.setVisible(true);

    }//GEN-LAST:event_jMenuItem21ActionPerformed

    private void jMenuItem22ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem22ActionPerformed
        ArquivoCadCronograma1 obj=new ArquivoCadCronograma1();
        jdpprincipal.add(obj);
        obj.setVisible(true);

    }//GEN-LAST:event_jMenuItem22ActionPerformed

    private void jMenuItem26ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem26ActionPerformed
        ArquivoTCCCronograma2 obj=new ArquivoTCCCronograma2();
        jdpprincipal.add(obj);
        obj.setVisible(true);
    }//GEN-LAST:event_jMenuItem26ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        ArquivoTCCTemas2 obj=new ArquivoTCCTemas2();
        jdpprincipal.add(obj);
        obj.setVisible(true);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void MenuSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MenuSairActionPerformed
        System.exit(0);
    }//GEN-LAST:event_MenuSairActionPerformed

    private void jMenu5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu5ActionPerformed

    }//GEN-LAST:event_jMenu5ActionPerformed

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
        sobre obj=new sobre();
        jdpprincipal.add(obj);
        obj.setVisible(true);
    }//GEN-LAST:event_jMenuItem5ActionPerformed

    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
        ArquivoCadFuncionario obj=new ArquivoCadFuncionario();
        jdpprincipal.add(obj);
        obj.setVisible(true);

    }//GEN-LAST:event_jMenuItem6ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
            new TelaPrincipal(check).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu MenuCadastro;
    private javax.swing.JMenuItem MenuSair;
    private javax.swing.JMenu MenuTCC;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenu jMenu6;
    private javax.swing.JMenu jMenu7;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem11;
    private javax.swing.JMenuItem jMenuItem14;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem20;
    private javax.swing.JMenuItem jMenuItem21;
    private javax.swing.JMenuItem jMenuItem22;
    private javax.swing.JMenuItem jMenuItem23;
    private javax.swing.JMenuItem jMenuItem24;
    private javax.swing.JMenuItem jMenuItem25;
    private javax.swing.JMenuItem jMenuItem26;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JMenuItem jMenuItem9;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JDesktopPane jdpprincipal;
    // End of variables declaration//GEN-END:variables
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RawRabbit")]
[assembly: AssemblyTrademark("")]
[assembly: InternalsVisibleTo("RawRabbit.Enrichers.GlobalExecutionId")]
[assembly: InternalsVisibleTo("RawRabbit.Operations.Publish")]
[assembly: InternalsVisibleTo("RawRabbit.Operations.Subscribe")]
[assembly: InternalsVisibleTo("RawRabbit.Operations.Respond")]
[assembly: InternalsVisibleTo("RawRabbit.Operations.Request")]
[assembly: InternalsVisibleTo("RawRabbit.Operations.MessageSequence")]
[assembly: InternalsVisibleTo("RawRabbit.Operations.StateMachine")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]


text:
local sandbox_core_platform_menu = sandbox_core_platform_menu or {}

-- load modules
local menu      = require("platform/menu")
local raise     = require("sandbox/modules/raise")

-- get the platform menu options for the given action: config or global
function sandbox_core_platform_menu.options(action)

    -- get it
    local options, errors = menu.options(action)
    if not options then
        raise(errors)
    end

    -- ok?
    return options
end

-- return module
return sandbox_core_platform_menu


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\Trading\Types;

/**
 *
 * @property string $AdditionalInformation
 * @property \DTS\eBaySDK\Trading\Types\AddressType $Address
 * @property string $BestTimeToCall
 * @property string $Email
 * @property \DateTime $SubmittedTime
 * @property string $ItemID
 * @property string $ItemTitle
 * @property string $UserID
 * @property \DTS\eBaySDK\Trading\Types\MemberMessageExchangeArrayType $MemberMessage
 * @property \DTS\eBaySDK\Trading\Enums\AdFormatLeadStatusCodeType $Status
 * @property string $ExternalEmail
 * @property string $PurchaseTimeFrame
 * @property string $TradeInYear
 * @property string $TradeInMake
 * @property string $TradeInModel
 * @property boolean $FinancingAnswer
 * @property boolean $Answer1
 * @property boolean $Answer2
 */
class AdFormatLeadType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'AdditionalInformation' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'AdditionalInformation'
        ],
        'Address' => [
            'type' => 'DTS\eBaySDK\Trading\Types\AddressType',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'Address'
        ],
        'BestTimeToCall' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'BestTimeToCall'
        ],
        'Email' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'Email'
        ],
        'SubmittedTime' => [
            'type' => 'DateTime',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'SubmittedTime'
        ],
        'ItemID' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'ItemID'
        ],
        'ItemTitle' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'ItemTitle'
        ],
        'UserID' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'UserID'
        ],
        'MemberMessage' => [
            'type' => 'DTS\eBaySDK\Trading\Types\MemberMessageExchangeArrayType',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'MemberMessage'
        ],
        'Status' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'Status'
        ],
        'ExternalEmail' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'ExternalEmail'
        ],
        'PurchaseTimeFrame' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'PurchaseTimeFrame'
        ],
        'TradeInYear' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'TradeInYear'
        ],
        'TradeInMake' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'TradeInMake'
        ],
        'TradeInModel' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'TradeInModel'
        ],
        'FinancingAnswer' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'FinancingAnswer'
        ],
        'Answer1' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'Answer1'
        ],
        'Answer2' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'Answer2'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
const path = require('path');
const MultipageWebpackPlugin = require('../../src/plugin.js');
const webpack = require('webpack');

let config = {
  context: __dirname,
  entry: {
    a: './src/a/a.js',
    b: './src/b/b.js',
    c: './src/c/c.js',
    vendor: ['lodash']
  },
  output: {
    filename: '[name].chunk.js',
    path: path.resolve(__dirname,'./dist')
  },
  plugins: [
    new MultipageWebpackPlugin()
  ]
};

module.exports = config;