text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include <DirectML.h>
#ifndef _GAMING_XBOX
#include <dxgi1_4.h>
#endif

#include <wrl/client.h>
using Microsoft::WRL::ComPtr;

#include <wil/wrl.h>
#include <wil/result.h>

#include "core/providers/dml/dml_provider_factory.h"
#include "core/providers/dml/dml_provider_factory_creator.h"
#include "core/session/abi_session_options_impl.h"
#include "core/session/allocator_adapters.h"
#include "core/session/ort_apis.h"
#include "core/framework/error_code_helper.h"
#include "DmlExecutionProvider/src/ErrorHandling.h"
#include "DmlExecutionProvider/src/GraphicsUnknownHelper.h"
#include "DmlExecutionProvider/inc/DmlExecutionProvider.h"
#include "core/platform/env.h"

namespace onnxruntime {

struct DMLProviderFactory : IExecutionProviderFactory {
  DMLProviderFactory(IDMLDevice* dml_device,
                     ID3D12CommandQueue* cmd_queue) : dml_device_(dml_device),
                                                      cmd_queue_(cmd_queue) {}
  ~DMLProviderFactory() override {}

  std::unique_ptr<IExecutionProvider> CreateProvider() override;
  void SetDefaultRoundingMode(AllocatorRoundingMode rounding_mode);

  void SetMetacommandsEnabled(bool metacommands_enabled);

 private:
  ComPtr<IDMLDevice> dml_device_{};
  ComPtr<ID3D12CommandQueue> cmd_queue_{};
  AllocatorRoundingMode rounding_mode_ = AllocatorRoundingMode::Enabled;
  bool metacommands_enabled_ = true;
};

std::unique_ptr<IExecutionProvider> DMLProviderFactory::CreateProvider() {
  auto provider = Dml::CreateExecutionProvider(dml_device_.Get(), cmd_queue_.Get(), metacommands_enabled_);
  Dml::SetDefaultRoundingMode(provider.get(), rounding_mode_);
  return provider;
}

void DMLProviderFactory::SetDefaultRoundingMode(AllocatorRoundingMode rounding_mode) {
  rounding_mode_ = rounding_mode;
}

void DMLProviderFactory::SetMetacommandsEnabled(bool metacommands_enabled) {
  metacommands_enabled_ = metacommands_enabled;
}

std::shared_ptr<IExecutionProviderFactory> CreateExecutionProviderFactory_DML(IDMLDevice* dml_device,
                                                                              ID3D12CommandQueue* cmd_queue) {
#ifndef _GAMING_XBOX
  // Validate that the D3D12 devices match between DML and the command queue. This specifically asks for IUnknown in
  // order to be able to compare the pointers for COM object identity.
  ComPtr<IUnknown> d3d12_device_0;
  ComPtr<IUnknown> d3d12_device_1;
  ORT_THROW_IF_FAILED(dml_device->GetParentDevice(IID_PPV_ARGS(&d3d12_device_0)));
  ORT_THROW_IF_FAILED(cmd_queue->GetDevice(IID_PPV_ARGS(&d3d12_device_1)));

  if (d3d12_device_0 != d3d12_device_1) {
    ORT_THROW_HR(E_INVALIDARG);
  }
#endif

  ComPtr<ID3D12Device> d3d12_device;
  ORT_THROW_IF_FAILED(dml_device->GetParentDevice(IID_GRAPHICS_PPV_ARGS(d3d12_device.ReleaseAndGetAddressOf())));
  const Env& env = Env::Default();
  auto luid = d3d12_device->GetAdapterLuid();
  env.GetTelemetryProvider().LogExecutionProviderEvent(&luid);
  return std::make_shared<onnxruntime::DMLProviderFactory>(dml_device, cmd_queue);
}

void DmlConfigureProviderFactoryDefaultRoundingMode(IExecutionProviderFactory* factory, AllocatorRoundingMode rounding_mode) {
  auto dml_provider_factory = static_cast<DMLProviderFactory*>(factory);
  dml_provider_factory->SetDefaultRoundingMode(rounding_mode);
}

void DmlConfigureProviderFactoryMetacommandsEnabled(IExecutionProviderFactory* factory, bool metacommandsEnabled) {
  auto dml_provider_factory = static_cast<DMLProviderFactory*>(factory);
  dml_provider_factory->SetMetacommandsEnabled(metacommandsEnabled);
}

bool IsSoftwareAdapter(IDXGIAdapter1* adapter) {
    DXGI_ADAPTER_DESC1 desc;
    adapter->GetDesc1(&desc);

    // see here for documentation on filtering WARP adapter:
    // https://docs.microsoft.com/en-us/windows/desktop/direct3ddxgi/d3d10-graphics-programming-guide-dxgi#new-info-about-enumerating-adapters-for-windows-8
    auto isBasicRenderDriverVendorId = desc.VendorId == 0x1414;
    auto isBasicRenderDriverDeviceId = desc.DeviceId == 0x8c;
    auto isSoftwareAdapter = desc.Flags == DXGI_ADAPTER_FLAG_SOFTWARE;

    return isSoftwareAdapter || (isBasicRenderDriverVendorId && isBasicRenderDriverDeviceId);
}

std::shared_ptr<IExecutionProviderFactory> DMLProviderFactoryCreator::Create(int device_id) {
  return Create(device_id, /*skip_software_device_check*/ false);
}

std::shared_ptr<IExecutionProviderFactory> DMLProviderFactoryCreator::Create(int device_id, bool skip_software_device_check) {
#ifdef _GAMING_XBOX
    ComPtr<ID3D12Device> d3d12_device;
    D3D12XBOX_CREATE_DEVICE_PARAMETERS params = {};
    params.Version = D3D12_SDK_VERSION;
    params.GraphicsCommandQueueRingSizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
    params.GraphicsScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
    params.ComputeScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
    ORT_THROW_IF_FAILED(D3D12XboxCreateDevice(nullptr, &params, IID_GRAPHICS_PPV_ARGS(d3d12_device.ReleaseAndGetAddressOf())));
#else
  ComPtr<IDXGIFactory4> dxgi_factory;
  ORT_THROW_IF_FAILED(CreateDXGIFactory2(0, IID_GRAPHICS_PPV_ARGS(dxgi_factory.ReleaseAndGetAddressOf())));

  ComPtr<IDXGIAdapter1> adapter;
  ORT_THROW_IF_FAILED(dxgi_factory->EnumAdapters1(device_id, &adapter));

  // Disallow using DML with the software adapter (Microsoft Basic Display Adapter) because CPU evaluations are much
  // faster. Some scenarios though call for EP initialization without this check (as execution will not actually occur
  // anyway) such as operation kernel registry enumeration for documentation purposes.
  if (!skip_software_device_check)
  {
    ORT_THROW_HR_IF(E_INVALIDARG, IsSoftwareAdapter(adapter.Get()));
  }

  ComPtr<ID3D12Device> d3d12_device;
  ORT_THROW_IF_FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_GRAPHICS_PPV_ARGS(d3d12_device.ReleaseAndGetAddressOf())));
#endif

  D3D12_COMMAND_QUEUE_DESC cmd_queue_desc = {};
  cmd_queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  cmd_queue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT;

  ComPtr<ID3D12CommandQueue> cmd_queue;
  ORT_THROW_IF_FAILED(d3d12_device->CreateCommandQueue(&cmd_queue_desc, IID_GRAPHICS_PPV_ARGS(cmd_queue.ReleaseAndGetAddressOf())));

  DML_CREATE_DEVICE_FLAGS flags = DML_CREATE_DEVICE_FLAG_NONE;

  // In debug builds, enable the DML debug layer if the D3D12 debug layer is also enabled
#if _DEBUG && !_GAMING_XBOX
  ComPtr<ID3D12DebugDevice> debug_device;
  (void)d3d12_device->QueryInterface(IID_PPV_ARGS(&debug_device));  // ignore failure
  const bool is_d3d12_debug_layer_enabled = (debug_device != nullptr);

  if (is_d3d12_debug_layer_enabled) {
    flags |= DML_CREATE_DEVICE_FLAG_DEBUG;
  }
#endif

  ComPtr<IDMLDevice> dml_device;
  ORT_THROW_IF_FAILED(DMLCreateDevice1(d3d12_device.Get(),
                                   flags,
                                   DML_FEATURE_LEVEL_2_0,
                                   IID_PPV_ARGS(&dml_device)));

  return CreateExecutionProviderFactory_DML(dml_device.Get(), cmd_queue.Get());
}

}  // namespace onnxruntime

// [[deprecated]]
// This export should be deprecated.
// The OrtSessionOptionsAppendExecutionProvider_DML export on the OrtDmlApi should be used instead.
ORT_API_STATUS_IMPL(OrtSessionOptionsAppendExecutionProvider_DML, _In_ OrtSessionOptions* options, int device_id) {
API_IMPL_BEGIN
  options->provider_factories.push_back(onnxruntime::DMLProviderFactoryCreator::Create(device_id));
API_IMPL_END
  return nullptr;
}

// [[deprecated]]
// This export should be deprecated.
// The OrtSessionOptionsAppendExecutionProvider_DML1 export on the OrtDmlApi should be used instead.
ORT_API_STATUS_IMPL(OrtSessionOptionsAppendExecutionProviderEx_DML, _In_ OrtSessionOptions* options,
                    _In_ IDMLDevice* dml_device, _In_ ID3D12CommandQueue* cmd_queue) {
API_IMPL_BEGIN
  options->provider_factories.push_back(onnxruntime::CreateExecutionProviderFactory_DML(dml_device,
                                                                                cmd_queue));
API_IMPL_END
  return nullptr;
}

ORT_API_STATUS_IMPL(CreateGPUAllocationFromD3DResource, _In_ ID3D12Resource* d3d_resource, _Out_ void** dml_resource) {
  API_IMPL_BEGIN
#ifdef USE_DML
  *dml_resource = Dml::CreateGPUAllocationFromD3DResource(d3d_resource);
#else
  *dml_resource = nullptr;
#endif  // USE_DML
  return nullptr;
  API_IMPL_END
}

ORT_API_STATUS_IMPL(FreeGPUAllocation, _In_ void* ptr) {
  API_IMPL_BEGIN
#ifdef USE_DML
  Dml::FreeGPUAllocation(ptr);
#endif  // USE_DML
  return nullptr;
  API_IMPL_END
}

ORT_API_STATUS_IMPL(GetD3D12ResourceFromAllocation, _In_ OrtAllocator* ort_allocator, _In_ void* allocation, _Out_ ID3D12Resource** d3d_resource) {
  API_IMPL_BEGIN
#ifdef USE_DML
  auto wrapping_allocator = static_cast<onnxruntime::OrtAllocatorImplWrappingIAllocator*>(ort_allocator);
  auto allocator = wrapping_allocator->GetWrappedIAllocator();
  if (!allocator) {
    return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "No requested allocator available");
  }
  *d3d_resource = Dml::GetD3D12ResourceFromAllocation(allocator.get(), allocation);
  (*d3d_resource)->AddRef();
#else
  *d3d_resource = nullptr;
#endif  // USE_DML
  return nullptr;
  API_IMPL_END
}

static constexpr OrtDmlApi ort_dml_api_10_to_x = {
  &OrtSessionOptionsAppendExecutionProvider_DML,
  &OrtSessionOptionsAppendExecutionProviderEx_DML,
  &CreateGPUAllocationFromD3DResource,
  &FreeGPUAllocation,
  &GetD3D12ResourceFromAllocation
};

const OrtDmlApi* GetOrtDmlApi(_In_ uint32_t /*version*/) NO_EXCEPTION {
#ifdef USE_DML
  return &ort_dml_api_10_to_x;
#else
    return nullptr;
#endif
}


text:
package com.esri.samples.show_callout;

/**
 * Wrapper required for launching a JavaFX 11 app through Gradle or from a jar.
 */
public class ShowCalloutLauncher {

    public static void main(String[] args) {
        ShowCalloutSample.main(args);
    }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('Labels', '0002_labeltextbox'),
    ]

    operations = [
        migrations.AlterField(
            model_name='labeltemplate',
            name='name',
            field=models.CharField(max_length=100, unique=True),
        ),
    ]


text:
export enum FetchState { IDLE, FETCHING, FAILURE }

export type DateTree = { years: { id: string, months: { id: string, days: { id: string }[] }[] }[] }

/** The result of 'justified-layout' */
export interface JustifiedLayoutResult {
    containerHeight: number
    widowCount: number
    boxes: JustifiedLayoutBox[]
}
export interface JustifiedLayoutBox {
    aspectRatio: number
    left: number
    top: number
    width: number
    height: number
}

export interface GridSectionLayout {
    left: number
    top: number
    width: number
    height: number
    /** The index of the first photo to render (inclusive) */
    fromBoxIndex?: number
    /** The index of the last photo to render (exclusive) */
    toBoxIndex?: number
    boxes?: JustifiedLayoutBox[]
    /** The scale factor which was applied to this layout */
    scaleFactor?: number
    /**
     * The original layout if this layout was scaled.
     *
     * *Background*: When multiple small sections are shown in one row, the are block-aligned by scaling them up to
     * viewport width. In this case, the original (unscaled) layout is stored here
     */
    originalLayout?: GridSectionLayout
}

export interface GridLayout {
    /** The index of the first section to render (inclusive) */
    fromSectionIndex: number
    /** The index of the last section to render (exclusive) */
    toSectionIndex: number
    sectionLayouts: GridSectionLayout[]
}


text:
layout: page
title:  Agenda
excerpt: "Agenda Hack.lu 2016"
modified: 2016-03-09T16:00:00
---

Talk Agenda
===========

Tuesday 18 October 2016 (Talks)
-------------------------------

{: class="table table-striped"}

| Time | Talks and Speakers |
|:----:|:------------------:|
| 08:45 | Registration open & refreshment |
| 09:30 | |
| 10:15 | Refreshment break|
| 10:30 | |
| 11:15 | [Keynote: Stressed out? Denial of service attacks from the providers' perspective](http://2016.hack.lu/talks/#stressed-out-denial-of-service-attacks-from-the-providers-perspective) ([Alice Hutchings](http://2016.hack.lu/talks/#bio-alice-hutchings)) |
| 12:00 | Lunch |
| 13:00 | [Lightning talks](http://piratepad.net/GYg4ObNCsY)|
| 13:30 | [Exploiting and attacking seismological networks… remotely](http://2016.hack.lu/talks/#exploiting-and-attacking-seismological-networks-remotely) ([Bertin Bervis Bonilla](http://2016.hack.lu/talks/#bio-bertin-bervis-bonilla), [James Jara](http://2016.hack.lu/talks/#bio-james-jara)) |
| 14:15 | [Secrets in Soft Token: A security study of HID Global Soft Token](http://2016.hack.lu/talks/#hidden-secrets-in-soft-token-a-security-study-of-hid-global-soft-token) ([Mouad Abouhali](http://2016.hack.lu/talks/#bio-mouad-abouhali)) <!--- static: day -->|
| 15:00 | [KillTheHashes 30 million Malware DNA profiling exercise](http://2016.hack.lu/talks/#killthehashes-30-million-malware-dna-profiling-exercise) ([Luciano Martins](http://2016.hack.lu/talks/#bio-luciano-martins), [Rodrigo Cetera](http://2016.hack.lu/talks/#bio-rodrigo-cetera), [Javier Bassi](http://2016.hack.lu/talks/#bio-javier-bassi))|
| 15:45 | Refreshment break |
| 16:00 | [Unveiling the attack chain of Russian-speaking cybercriminals](http://2016.hack.lu/talks/#unveiling-the-attack-chain-of-russian-speaking-cybercriminals) ([Wayne Huang](http://2016.hack.lu/talks/#bio-wayne-huang), [Sun Huang](http://2016.hack.lu/talks/#bio-sun-huang))|
| 16:45 |[Of Mice and Keyboards: On the Security of Modern Wireless Desktop Sets](http://2016.hack.lu/talks/#of-mice-and-keyboards-on-the-security-of-modern-wireless-desktop-sets) ([Matthias Deeg](http://2016.hack.lu/talks/#bio-matthias-deeg) and [Gerhard Klostermeier](http://2016.hack.lu/talks/#bio-gerhard-klostermeier))<!--- static --> |
| 17:30 | [Windows systems & code signing protection](http://2016.hack.lu/talks/#windows-systems--code-signing-protection) ([Paul Rascagnères](http://2016.hack.lu/talks/#bio-paul-rascagnres))|
| 18:15 | [Cyber Grand Shellphish: Shellphish and the DARPA Cyber Grand Challenge](http://2016.hack.lu/talks/#cyber-grand-shellphish-shellphish-and-the-darpa-cyber-grand-challenge) ([Kevin Borgolte](http://2016.hack.lu/talks/#bio-kevin-borgolte))<!--- static -->|
{: class="table"}

Wednesday 19 October 2016 (Talks)
---------------------------------

| Time | Talks and Speakers |
|:----:|:------------------:|
| 08:45 | [The Metabrik Platform: Rapid Development of Reusable Security Tools](http://2016.hack.lu/talks/#the-metabrik-platform-rapid-development-of-reusable-security-tools) ([Patrice Auffret](http://2016.hack.lu/talks/#bio-patrice-auffret)) |
| 09:30 | [2016: The Infosec Crossroads](http://2016.hack.lu/talks/#the-infosec-crossroads) ([Saumil Shah](http://2016.hack.lu/talks/#bio-saumil-shah))|
| 10:15 | Refreshment break|
| 10:30 | [Exploit generation and JavaScript analysis automation with WinDBG](http://2016.hack.lu/talks/#exploit-generation-and-javascript-analysis-automation-with-windbg) ([Fitzl Csaba](http://2016.hack.lu/talks/#bio-fitzl-csaba), [Miklos Desbordes-Korcsev](http://2016.hack.lu/talks/#bio-miklos-desbordes-korcsev))|
| 11:15 | [Keynote: A Network of Sorrows: Small Adversaries and Small Allies](http://2016.hack.lu/talks/#a-network-of-sorrows-small-adversaries-and-small-allies) ([Quinn Norton](http://2016.hack.lu/talks/#bio-quinn-norton)) |
| 12:00 | Lunch |
| 13:00 | [Lightning talks](http://piratepad.net/GYg4ObNCsY)|
| 13:30 | [Exploiting new default accounts in SAP systems](http://2016.hack.lu/talks/#exploiting-new-default-accounts-in-sap-systems) ([Joris van de Vis](http://2016.hack.lu/talks/#bio-joris-van-de-vis)) |
| 14:15 | [badGPO - Using GPOs for Persistence and Lateral Movement](http://2016.hack.lu/talks/#badgpo---using-gpos-for-persistence-and-lateral-movement) ([Yves Kraft](http://2016.hack.lu/talks/#bio-yves-kraft-and-immanuel-willi), [Immanuel Willi](http://2016.hack.lu/talks/#bio-yves-kraft-and-immanuel-willi))|
| 15:00 | [Machine Duping: Pwning Deep Learning Systems](http://2016.hack.lu/talks/#machine-duping-pwning-deep-learning-systems) ([Clarence Chio](http://2016.hack.lu/talks/#bio-clarence-chio))|
| 15:45 | Refreshment break |
| 16:00 | [Credential Assessment: Mapping Privilege Escalation at Scale](http://2016.hack.lu/talks/#credential-assessment-mapping-privilege-escalation-at-scale) ([Matt Weeks](http://2016.hack.lu/talks/#bio-matt-weeks))|
| 16:45 | [When Crypto Fails](http://2016.hack.lu/talks/#when-crypto-fails) ( [Yaniv Balmas](http://2016.hack.lu/talks/#bio-yaniv-balmas), [Ben Herzog](http://2016.hack.lu/talks/#bio-ben-herzog))|
| 17:30 | [Bootstrapping an Architectural Research Platform](http://2016.hack.lu/talks/#bootstrapping-an-architectural-research-platform) ([Jacob I. Torrey](http://2016.hack.lu/talks/#bio-jacob-i-torrey)) |
| 18:15 | [Hadoop safari : Hunting for vulnerabilities](http://2016.hack.lu/talks/#hadoop-safari--hunting-for-vulnerabilities) ([Thomas DEBIZE](http://2016.hack.lu/talks/#bio-mahdi-braik-and-thomas-debize) and [Mahdi BRAIK](http://2016.hack.lu/talks/#bio-mahdi-braik-and-thomas-debize))<!--- static -->|
{: class="table"}

Thursday 20 October 2016 (Talks)
--------------------------------

| Time | Talks and Speakers |
|:----:|:------------------:|
| 08:45 | [BtleJuice: the Bluetooth Smart Man In The Middle Framework](http://2016.hack.lu/talks/#btlejuice-the-bluetooth-smart-man-in-the-middle-framework) ([Damien Cauquil](http://2016.hack.lu/talks/#bio-damien-cauquil))|
| 09:30 | [Where should I host my malware?](http://2016.hack.lu/talks/#where-should-i-host-my-malware) ([Attila Marosi](http://2016.hack.lu/talks/#bio-attila-marosi))|
| 10:15 | Refreshment break|
| 10:30 | [Interesting Malware - No, I'm not kidding…](http://2016.hack.lu/talks/#interesting-malware---no-im-not-kidding) ([Marion Marschalek](http://2016.hack.lu/talks/#bio-marion-marschalek))|
| 11:15 | [Keynote: Enhancing infrastructure cybersecurity in Europe](http://2016.hack.lu/talks/#enhancing-infrastructure-cybersecurity-in-europe) ([Rossella Mattioli](http://2016.hack.lu/talks/#bio-rossella-mattioli)) |
| 12:00 | Lunch |
| 13:00 | [Lightning talks](http://piratepad.net/GYg4ObNCsY)|
| 13:30 | [House intercoms attacks: when frontdoors become backdoors](http://2016.hack.lu/talks/#house-intercoms-attacks-when-frontdoors-become-backdoors) ([Sébastien Dudek](http://2016.hack.lu/talks/#bio-sbastien-dudek))|
| 14:15 | [When Practice Informs Technology](http://2016.hack.lu/talks/#when-practice-informs-technology) ([Mahsa Alimardani](http://2016.hack.lu/talks/#bio-mahsa-alimardani))|
| 15:00 | [Bridging political gaps with code](http://2016.hack.lu/talks/#bridging-political-gaps-with-code) ([Okhin](http://2016.hack.lu/talks/#bio-okhin))|
| 15:45 | Refreshment break |
| 16:00 | [WiFi Exploitation: How passive interception leads to active exploitation](http://2016.hack.lu/talks/#) ([Solomon Sonya](http://2016.hack.lu/talks/#))|
| 16:45 | [Fraud detection and forensics on telco networks](http://2016.hack.lu/talks/#fraud-detection-and-forensics-on-telco-networks) ([Vladimir Kropotov](http://2016.hack.lu/talks/#bio-vladimir-kropotov) and [Dmitry Kurbatov](http://2016.hack.lu/talks/#bio-dmitry-kurbatov))|
| 17:30 | [The Legend of Windows: A Link to the Hash](http://2016.hack.lu/talks/#the-legend-of-windows-a-link-to-the-hash) ([m4xk](http://2016.hack.lu/talks/#bio-m4xk) and [sıx](http://2016.hack.lu/talks/#bio-sx))|
| 18:15 | |
{: class="table"}

Workshop Agenda
===============

Tuesday 18 October 2016 (Workshops)
-----------------------------------

| Time | Hollenfels | Echternach - Diekirch |
|:----:|:----------:|:----------------------:|
| 13:00 |[Lightning talks](http://piratepad.net/GYg4ObNCsY)  | [Lightning talks](http://piratepad.net/GYg4ObNCsY)|
| 13:30 | [Advanced exploitation: ROP and protections bypass under Linux](http://2016.hack.lu/talks/#advanced-exploitation-rop-and-protections-bypass-under-linux) ([Julien Bachmann](http://2016.hack.lu/talks/#bio-julien-bachmann)) *ca. 4 h* <!--- static -->| [Introduction to Security Onion](http://2016.hack.lu/talks/#introduction-to-security-onion) ([David Szili](http://2016.hack.lu/talks/#bio-david-szili)) *ca. 3 h* <!--- static -->|
| 15:45 | Refreshment break |Refreshment break|
| 16:00 |workshop continued| workshop continued |
| 18:00 |end of workshop|  |
{: class="table"}

Wednesday 19 October 2016 (Workshops)
-------------------------------------

| Time | Hollenfels | Echternach - Diekirch |
|:----:|:----------:|:----------------------:|
| 09:00 | | |
| 09:30 | [Malware Triage IOCs - Using Open Data to Help Develop Robust Indicators](http://2016.hack.lu/talks/#malware-triage-iocs---using-open-data-to-help-develop-robust-indicators) ([Sergei Frankoff](http://2016.hack.lu/talks/#bio-sergei-frankoff), [Sean Wilson](http://2016.hack.lu/talks/#bio-sean-wilson)) *ca. 2 h*|  [The Fantastic 4 ... forensic domains: net, disk, mem, mal](http://2016.hack.lu/talks/#the-fantastic-4--forensic-domains-net-disk-mem-mal) ([David Durvaux](http://2016.hack.lu/talks/#bio-david-durvaux), [Christophe Vandeplas](http://2016.hack.lu/talks/#bio-christophe-vandeplas)) *ca. 2 h*|
| 10:15 | Refreshment break | Refreshment break|
| 10:30 | continue workshop | continue workshop|
| 12:00 | Lunch break | Lunch break|
| 13:00 |[Lightning talks](http://piratepad.net/GYg4ObNCsY)  | [Lightning talks](http://piratepad.net/GYg4ObNCsY)|
| 13:30 | [Android malware reverse engineering](http://2016.hack.lu/talks/#android-malware-reverse-engineering) ([Axelle Apvrille](http://2016.hack.lu/talks/#bio-axelle-apvrille)) *ca. 3 h*| [Introduction to Security Onion](http://2016.hack.lu/talks/#introduction-to-security-onion) ([David Szili](http://2016.hack.lu/talks/#bio-david-szili)) *ca. 3 h* <!--- static -->|
| 15:45 | Refreshment break |Refreshment break||
| 16:00 |workshop continued| workshop continued ||
| 18:00 |end of workshop|  ||
{: class="table"}

Thursday 20 October 2016 (Workshops)
------------------------------------

| Time | Hollenfels | Echternach - Diekirch |
|:----:|:----------:|:----------------------:|
| 09:00 | | |
| 09:30 | [ARM Shellcode Basics](http://2016.hack.lu/talks/#arm-shellcode-basics) ([Saumil Shah](http://2016.hack.lu/talks/#bio-saumil-shah)) | [Malware analysis made easy with Volatility plugins](http://2016.hack.lu/talks/#malware-analysis-made-easy-with-volatility-plugins) ([Thomas Chopitea](http://2016.hack.lu/talks/#bio-thomas-chopitea)) |
| 10:15 | Refreshment break | Refreshment break|
| 10:30 | workshop continued | workshop continued|
| 12:00 | Lunch break | Lunch break|
| 13:30 |[FastIR Collector](http://2016.hack.lu/talks/#fastir-collecto) ([Sébastien Larinier](http://2016.hack.lu/talks/#bio-sbastien-larinier)) *ca. 2 h* | [Nothing is beyond our pots - An Introductory Worskhop about Honeypots](http://2016.hack.lu/talks/#nothing-is-beyond-our-pots---an-introductory-worskhop-about-honeypots) ([Guillaume Arcas](http://2016.hack.lu/talks/#bio-guillaume-arcas))|
| 15:45 | Refreshment break |Refreshment break|
| 16:00 |end of workshop| workshop continued |
| 18:00 || end of workshop |
{: class="table"}

Monday 17 October 2016 (Special interest pre-hack meeting)
----------------------------------------------------------

| Time | Room | Title |
|:----:|:----:|:-----:|
| 14:00 - 18:00 | Hollenfels | [MISP summit](/misp-summit/) |
{: class="table table-striped"}


text:
module TasksManagement
  class ApplicationController < ActionController::Base
  end
end


text:
package lejos.nxt.addon;
import lejos.robotics.Touch;
import lejos.nxt.ADSensorPort;
import lejos.nxt.SensorConstants;

/*
 * WARNING: THIS CLASS IS SHARED BETWEEN THE classes AND pccomms PROJECTS.
 * DO NOT EDIT THE VERSION IN pccomms AS IT WILL BE OVERWRITTEN WHEN THE PROJECT IS BUILT.
 */

/**
 * Interface for the Mindsensors Touch Multiplexer.
 * This device allows up to three touch sensors to be attached to a single NXT
 * sensor port.
 *
 * @author Andy
 *
 */
public class TouchMUX {
    /** number of touch sensors supported by this device **/
    public static final int NUMBER_OF_SENSORS = 3;
    /** Bit ID returned by readSensors when sensor T1 is pressed **/
    public static final int ID_T1 = (1 << 0);
    /** Bit ID returned by readSensors when sensor T1 is pressed **/
    public static final int ID_T2 = (1 << 1);
    /** Bit ID returned by readSensors when sensor T1 is pressed **/
    public static final int ID_T3 = (1 << 2);

    private class MuxTouchSensor implements Touch
    {
        private int id;

        /**
         * Create an object to represent one touch sensor attached to the
         * multiplexer.
         * @param touchId The id of this sensor.
         */
        MuxTouchSensor(int touchId)
        {
            id = touchId;
        }

        /**
         * Check if the sensor is pressed.
         * @return true if sensor is pressed, false otherwise.
         */
        public boolean isPressed()
        {
            return (readSensors() & id) != 0;
        }
    }

    private ADSensorPort port;

    /** Instance for the touch sensor connected to port T1 **/
    public final Touch T1 = new MuxTouchSensor(ID_T1);
    /** Instance for the touch sensor connected to port T2 **/
    public final Touch T2 = new MuxTouchSensor(ID_T2);
    /** Instance for the touch sensor connected to port T3 **/
    public final Touch T3 = new MuxTouchSensor(ID_T3);

    /**
     * Create a object to provide access to a touch sensor multiplexer
     * @param port The NXT sensor port to which the multiplexer is attached
     */
    public TouchMUX(ADSensorPort port)
    {
        this.port = port;
        port.setTypeAndMode(SensorConstants.TYPE_CUSTOM, SensorConstants.MODE_RAW);
    }

    /**
     * Return a Touch interface providing access to the sensor specified by the
     * given id.
     * @param id a number between 0..{@link #NUMBER_OF_SENSORS}-1
     * @return the requested Touch interface
     */
    public synchronized Touch getInstance(int id)
    {
        switch(id)
        {
            case 0:
                return T1;
            case 1:
                return T2;
            case 2:
                return T3;
            default:
                throw new IllegalArgumentException("no such touch sensor port");
        }
    }

    /*
     * Following values provide High and Low limits for the various
     * sensor combinations, as supplied by Mindsensors.
     * Note however that these values assume the RAW readings obtained when the
     * sensor type is set to be a Lego light sensor. With the Lego firmware this
     * is not the actual A/D reading instead it is a value correct for the offset
     * and range of the sensor in the following way...
     * MIN_LS_READING = 200
     * MAX_LS_READING = 900
     * legoVal = MAX_AD_RAW - ((rawVal-MIN_LS_READING)*100)/((MAX_LS_READING - MIN_LS_READING)*100)/MAX_AD_RAW
     * which gives
     * legoVal = MAX_AD_RAW - ((rawVal - MIN_LS_READING)*MAX_AD_RAW)/(MAX_LS_READING - MIN_LS_READING)
     * To correct the values used we must adjust them as follows...
     * lejosVal = (MAX_AD_RAW - legoVal) * (MAX_LS_READING - MIN_LS_READING))/MAX_AD_RAW + MIN_LS_READING
     * The actual values used below have been corrected in this way.....
     * Note also that the Hi/Lo of the test has been changed because the values now drop in value..
     * Original values:
    private static final int L1 = 60;
    private static final int H1 = 160;
    private static final int L2 = 210;
    private static final int H2 = 290;
    private static final int L3 = 500;
    private static final int H3 = 599;
    private static final int L12 = 370;
    private static final int H12 = 460;
    private static final int L13 = 600;
    private static final int H13 = 658;
    private static final int L23 = 659;
    private static final int H23 = 723;
    private static final int L123 = 724;
    private static final int H123 = 800;
     * Adjusted values:
     */
    private static final int H1 = 859;
    private static final int L1 = 791;
    private static final int H2 = 756;
    private static final int L2 = 701;
    private static final int H3 = 558;
    private static final int L3 = 490;
    private static final int H12 = 647;
    private static final int L12 = 585;
    private static final int H13 = 489;
    private static final int L13 = 450;
    private static final int H23 = 449;
    private static final int L23 = 405;
    private static final int H123 = 404;
    private static final int L123 = 352;

    /**
     * Read the touch multiplexer and return a bit mask showing which sensors
     * are currently pressed. Returns ID_T1 if T1 is pressed, ID_T2 if T2 is
     * pressed and ID_T3 id T3 is pressed. If more then one sensor is pressed
     * the return will be an or of the values.
     * @return bit mask showing which sensor buttons are pressed.
     */
    public int readSensors()
    {
        int ret;
        int val = port.readRawValue();
        /*
         * Note the following code can be used to correct the RAW value to be
         * the same as the RAW value for a Lego light sensor. Allowing the use
         * of the original Mindsensor constants.
        if (val > 200)
            val -= 200;
        else
            val = 0;
        val = (val*100)/68;
        val = 1023 - val
         */
        if (L1 <= val && val < H1)
            ret = ID_T1;
        else if (L2 <= val && val < H2)
            ret = ID_T2;
        else if (L3 <= val && val < H3)
            ret = ID_T3;
        else if (L12 <= val && val < H12)
            ret = ID_T1|ID_T2;
        else if (L13 <= val && val < H13)
            ret = ID_T1|ID_T3;
        else if (L23 <= val && val < H23)
            ret = ID_T2|ID_T3;
        else if (L123 <= val && val < H123)
            ret = ID_T1|ID_T2|ID_T3;
        else
            ret = 0;
        return ret;
    }

}


text:
import argparse
import backtest
import trade

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("action", choices=["backtest", "trade"])
    args = parser.parse_args()
    if args.action == "backtest":
        backtest.backtest()
    if args.action == "trade":
        trade.trade()

if __name__ == "__main__":
    main()


text:
require 'net/http'

module Camb
  class Client
    def initialize(options = {})
      @host = options[:host] || "localhost"
      @port = options[:port] || 80
      @url = options[:url] || "/"
    end

    def client
      @client ||= Net::HTTP.new(@host, @port)
    end

    def request
      @request ||= Net::HTTP::Get.new(@url)
    end

    def response
      client.request(request)
    end
  end
end


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _locator = require('../models/locator.model');

var _locator2 = _interopRequireDefault(_locator);

var _utils = require('../helpers/utils');

var _utils2 = _interopRequireDefault(_utils);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Get locator
 * @returns {Locator}
 */
function getAppLocator(req, res) {
  var _q = { "app_type": req.params['app'] };

  _locator2.default.get(_q).then(function (locator) {
    return res.json(locator);
  }).catch(function (e) {
    return next(e);
  });
}

function getAppLocatorByKey(req, res) {

  var _q = { $and: [{ 'app_type': req.params.app }, { 'xpath.key': req.params.key }] };

  _locator2.default.get(_q).then(function (locator) {
    return res.json(locator);
  }).catch(function (e) {
    return next(e);
  });
}

function addUpdateLocator(req, res) {

  var _q = { $and: [{ 'app_type': req.body.app_type }, { 'xpath.key': req.body.xpath.key }] };

  _locator2.default.get(_q).then(function (locator) {
    if (locator && locator.length) {

      req.body.tags = arrayUnique(data[0].tags.concat(req.body.tags)); // todo: remove tags whenever applicable
      _locator2.default.findOneAndUpdate({ $and: [{ 'app_type': req.body.app_type }, { 'xpath.key': req.body.xpath.key }] }, { $set: { "tags": req.body.tags, "xpath.value": req.body.xpath.value } }, function (err, doc) {
        if (err) {
          res.json({
            "errors": {
              "errorMessage": err,
              "errorCode": "PROCESSING_ERROR"
            }
          });
        }

        doc.tags = req.body.tags;
        doc.xpath.value = req.body.xpath.value;

        res.json(doc);
      });
    } else {
      var xpath = new Xpath(req.body);
      xpath.save(function (err, xpathData) {
        if (err) {
          res.json({
            "errors": {
              "errorMessage": err,
              "errorCode": "PROCESSING_ERROR"
            }
          });
        }
        return res.json(xpathData);
      });
    }
  }).catch(function (e) {
    return next(e);
  });
}

/**
 * Get locator list.
 * @property {number} req.query.skip - Number of locator to be skipped.
 * @property {number} req.query.limit - Limit number of locator to be returned.
 * @returns {Locator[]}
 */
function list(req, res, next) {
  var _req$query = req.query,
      _req$query$limit = _req$query.limit,
      limit = _req$query$limit === undefined ? 50 : _req$query$limit,
      _req$query$skip = _req$query.skip,
      skip = _req$query$skip === undefined ? 0 : _req$query$skip;

  _locator2.default.list({ limit: limit, skip: skip }).then(function (locator) {
    return res.json(locator);
  }).catch(function (e) {
    return next(e);
  });
}

// todo: move to utils
function arrayUnique(array) {
  var a = array.concat();
  for (var i = 0; i < a.length; ++i) {
    for (var j = i + 1; j < a.length; ++j) {
      if (a[i] === a[j]) a.splice(j--, 1);
    }
  }

  return a;
};

exports.default = { getAppLocator: getAppLocator, getAppLocatorByKey: getAppLocatorByKey, addUpdateLocator: addUpdateLocator, list: list };
module.exports = exports['default'];
//# sourceMappingURL=locator.controller.js.map


text:
//
//  GameScene_Box2D.h
//  TumTum_Base
//
//  Created by ohtaisao on 2014/12/19.
//
//

#ifndef __TumTum_Base__GameScene_Box2D__
#define __TumTum_Base__GameScene_Box2D__

//#define LIQUIDFUN_SIMD_NEON 1

#include "cocos2d.h"
#include "Box2D.h"
#include "GLESDebugDraw.h"
#include "BallSprite.h"

using namespace cocos2d;

class GameScene_Box2D : public Layer
{
public:
    ~GameScene_Box2D();
    virtual bool init();
    virtual void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t transformFlags) override;
    static Scene *createGameScene_Box2D();
    CREATE_FUNC(GameScene_Box2D);
    void initPhysics();
    void update(float dt);

    BallSprite *createSprite(Vec2 &pos);

    //touch
    void onTouchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event);
    void onTouchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event);
    void onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event);

private:

    //衝突検知
    enum spriteType {
        kNone  = 0,
        kFloor,
        kBall
    };
    bool onContactBegin(PhysicsContact& contact);
    //std::function<void(PhysicsContact& contact, const PhysicsContactPostSolve& solve)> onContactPostSolve;
    void onContactPostSolve(PhysicsContact& contact, const PhysicsContactPostSolve& solve);

    //ボール充填
private:
    //ボールが満杯になった事を検知
    bool isFullBoll(BallSprite *ball);
    //ボール満タン
    void fillBoll();
    //消された分のボールを補充
    void refillBoll();
    std::vector<Vec2> _delballPos;

    //ボールが壁に接触している事を検知
    void isContactWall(Rect box);

    // in isContactWall
    Rect _floor, _leftwall, _rightwall, _ceil;

    //隣接ボールハイライト
    void setHilightAllAdjacent();
    void srchAllAdjacent(BallSprite* cur_ball);
    void srchNextAdjacent(BallSprite* cur_ball);
    void setHilightTypeAll(BallSprite::ballHilightType type);
    bool isExistTouch();

    //ボール削除
private:
    void delTouchedBalls();
    std::vector<BallSprite*> _bollArray;

private:
    b2World *_world;
    GLESDebugDraw *_debugDraw;

protected:
    void onDraw(const cocos2d::Mat4 &transform, uint32_t transformFlags);

    cocos2d::EventListenerTouchOneByOne* _touchListener;
    cocos2d::EventListenerKeyboard* _keyboardListener;
    cocos2d::CustomCommand _customCmd;
};

#endif /* defined(__TumTum_Base__GameScene_Box2D__) */


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>

						Apache CloudStack 4.12.0.0 Root Admin API Reference

createManagementNetworkIpRange

Creates a Management network IP range.

Request parameters

Parameter Name	Description	Required

gateway	The gateway for the management network.	true

netmask	The netmask for the management network.	true

podid	UUID of POD, where the IP range belongs to.	true

startip	The starting IP address.	true

endip	The ending IP address.	false

forsystemvms	Specify if range is dedicated for CPVM and SSVM.	false

vlan	Optional. The vlan id the ip range sits on, default to Null when it is not specificed which means you network is not on any Vlan	false

Response Tags

Response Name	Description

id	the ID of the Pod

allocationstate	the allocation state of the Pod

endip	the ending IP for the Pod

forsystemvms	indicates if range is dedicated for CPVM and SSVM

gateway	the gateway of the Pod

name	the name of the Pod

netmask	the netmask of the Pod

startip	the starting IP for the Pod

vlanid	indicates Vlan ID for the range

zoneid	the Zone ID of the Pod

zonename	the Zone name of the Pod

capacity(*)	the capacity of the Pod

capacityallocated	the capacity currently in allocated

capacitytotal	the total capacity available

capacityused	the capacity currently in use

clusterid	the Cluster ID

clustername	the Cluster name

name	the capacity name

percentused	the percentage of capacity currently in use

podid	the Pod ID

podname	the Pod name

type	the capacity type

zoneid	the Zone ID

zonename	the Zone name

Copyright © 2015 The Apache Software Foundation, Licensed under the
                   Apache License, Version 2.0.

                Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo  and the Apache feather logo are trademarks of The Apache Software Foundation.


text:
namespace models
{
namespace neural
{

using namespace debug;

InputLayer::InputLayer(int num) :
    Layer(num, "INPUT")
{
    setActivationFunction(new LinearAF);
}

void InputLayer::insertInput(const std::vector<double> & input)
{
    std::vector<double> inputBuffer;

    if (input.size() > neuronCount())
    {
        std::copy(input.begin() + input.size() - neuronCount(), input.end(),
                std::back_inserter(inputBuffer));
    }
    else
    {
        std::copy(input.begin(), input.end(), std::back_inserter(inputBuffer));
    }

    _buffer.clear();

//  for (std::vector<boost::shared_ptr<Neuron> >::iterator it = _neurons.begin(); it
//          != _neurons.end(); ++it)
    for(unsigned i=0; i<neuronCount(); ++i)
    {
        boost::shared_ptr<Neuron> neuron = _neurons[i];

        std::vector<double> tmpInput;
        tmpInput.push_back(inputBuffer[i]);

        neuron->insertInput(tmpInput, _bias, *_activationFunction);
        _buffer.push_back(neuron->getOutput());
    }

    printSeq("Buffers in " + _name + ": ", _buffer);

    stepDone();
}

//void InputLayer::insertInput(const std::vector<double> & input)
//{
//  _buffer.clear();
//
//  if (input.size() > neuronCount())
//  {
//      std::copy(input.begin()+input.size()-neuronCount(), input.end(), std::back_inserter(_buffer));
//  }
//  else
//  {
//      std::copy(input.begin(), input.end(), _buffer.begin());
//  }
//
//  stepDone();
//}

}
}


text:
; Modification of TinySafeBoot for RS-485
; (c) Karlis Goba 2016
; See below for licensing, copyright and credits
;***********************************************************************
;***********************************************************************
;***********************************************************************
; TinySafeBoot - The Universal Bootloader for AVR ATtinys and ATmegas
;***********************************************************************
;***********************************************************************
;***********************************************************************
;
;-----------------------------------------------------------------------
; Written in 2011-2015 by Julien Thomas
;
; This program is free software; you can redistribute it and/or
; modify it under the terms of the GNU General Public License
; as published by the Free Software Foundation; either version 3
; of the License, or (at your option) any later version.
; This program 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 General Public License for more details.
; You should have received a copy of the GNU General Public License
; along with this program; if not, see:
; http://www.gnu.org/licenses/
;-----------------------------------------------------------------------
;
;***********************************************************************
; FUSES
;***********************************************************************
;
; * BOOTRST activated lets the MCU jump into the Bootloader Section
;     (rather than $0000) with every hardware Reset.
; * BODLEVEL should be set to avoid flash corruption during unsafe
;     device power-up.
; * BOOTSZ=10 (512 words) or BOOTSZ=11 (256 words) to reserve 512 bytes
;     for a Bootloader Section.
; * BLB to MODE 2 or 3 protects Bootloader Section from undesirable
;     write access by firmware.
; * LOCKBITS may be set to Mode 3 (LB-Mode 3) in a security environment.
;
; ATMega328P: Low 0xFF High 0xDE Ext 0xFD
;
;***********************************************************************
; OVERVIEW
;***********************************************************************
;
; TSB assembly source is organized in 4 segments (approx. line numbers)
;
; ~   50 ... Global definitions
; ~  240 ... TSB Installer for ATtinys
; ~  470 ... TSB for ATtinys
; ~ 1180 ... TSB for ATmegas
;
;***********************************************************************
; ADJUSTMENTS FOR INDIVIDUAL ASSEMBLY
;***********************************************************************
;
; This Sourcecode is directly compatible to: AVRASM2, GAVRASM
;
.nolist
;
;-----------------------------------------------------------------------
; SPECIFY TARGET AVR
;-----------------------------------------------------------------------
;
.include "m328Pdef.inc"
;
;
.list
;
;-----------------------------------------------------------------------
; BUILD INFO
;-----------------------------------------------------------------------
; YY = Year - MM = Month - DD = Day
.set    YY      =       15
.set    MM      =       8
.set    DD      =       26
;
.set BUILDSTATE = $F0   ; version management option
;
;
;-----------------------------------------------------------------------
; PORTS
;-----------------------------------------------------------------------
;
; Important Note: B0/B1 are defaults for database templates
;
.equ    RXPORT  = PORTD
.equ    RXPIN   = PIND
.equ    RXDDR   = DDRD
.equ    RXBIT   = 0
.equ    TXPORT  = PORTD
.equ    TXDDR   = DDRD
.equ    TXBIT   = 1

.equ    TEPORT  = PORTD
.equ    TEDDR   = DDRD
.equ    TEBIT   = 2

.equ    REPORT  = PORTD
.equ    REDDR   = DDRD
.equ    REBIT   = 3

;-----------------------------------------------------------------------
; *** Changes below this line are on your own risk! ***
;-----------------------------------------------------------------------
;
;
;
;***********************************************************************
; AUTO-ADJUST FOR DIFFERENT ASSEMBLY OPTIONS
;***********************************************************************
;
; Autodetect ATtiny / ATmega and set TINYMEGA switch accordingly

.ifdef RWW_START_ADDR
        .if RWW_START_ADDR == RWW_STOP_ADDR
        .equ TINYMEGA = 0
        .message "DETECTED ATTINY DEFINITIONS"
        .else
        .equ TINYMEGA = 1
        .message "DETECTED ATMEGA DEFINITIONS"
        .endif
.else
        .equ TINYMEGA = 0
        .message "DETECTED ATTINY DEFINITIONS"
.endif

.if FLASHEND > ($7fff)
        .error "SORRY! DEVICES OVER 64 KB NOT SUPPORTED YET."
        .exit
.endif

;-----------------------------------------------------------------------
; Workarounds for devices with renamed or missing definitions
;-----------------------------------------------------------------------
;
.ifndef SPMCSR                  ; SPMEN / PGERS / ...
        .equ SPMCSR = SPMCR
.endif

.ifndef MCUSR                   ; PORF / EXTRF / BORF / WDRF
        .equ MCUSR = MCUCSR
.endif

; Detect Attiny441/841 to amend missing pagesize and apply 4-page mode

.set FOURPAGES = 0

.if ((SIGNATURE_000 == $1E) && (SIGNATURE_002 == $15) && (SIGNATURE_001 == $92))
                .equ PAGESIZE = 32
                .set FOURPAGES = 1
                .message "ATTINY441: 4-PAGE-ERASE MODE"
.endif

.if ((SIGNATURE_000 == $1E) && (SIGNATURE_002 == $15) && (SIGNATURE_001 == $93))
                .equ PAGESIZE = 32
                .set FOURPAGES = 1
                .message "ATTINY841: 4-PAGE-ERASE MODE"
.endif

;-----------------------------------------------------------------------
; Universal Constants and Registers
;-----------------------------------------------------------------------

.equ    REQUEST         = '?'           ; request / answer / go on
.equ    CONFIRM         = '!'           ; confirm / attention

; Current bootloader date coded into 16-bit number
.equ    BUILDDATE   = YY * 512 + MM * 32 + DD

; Other
.equ    INFOLEN         = 8              ; *Words* of Device Info
.equ    BUFFER          = SRAM_START

; Registers (in use by TSB-Firmware and TSB-Installer for ATtinys)
.def    avecl   = r4                    ; application vector temp low
.def    avech   = r5                    ; application vector temp high
.def    bclkl   = r6                    ; baudclock low byte
.def    bclkh   = r7                    ; baudclock high byte
.def    tmp1    = r16                   ; these are
.def    tmp2    = r17                   ; universal
.def    tmp3    = r18                   ; temporary
.def    tmp4    = r19                   ; registers
.def    bcnt    = r20                   ; page bytecounter

;
;
;***********************************************************************
;***********************************************************************
;***********************************************************************
; START OF TSB FOR ATTINYS
;***********************************************************************
;***********************************************************************
;***********************************************************************
;
; TSB for ATmegas is always coded directly to target address.

.if TINYMEGA == 1

.message "ASSEMBLY OF TSB FOR ATMEGA"

.equ    BOOTSTART       = (FLASHEND+1)-512      ; = 1024 Bytes
;.equ    BOOTSTART       = (0x3FFF+1)-512      ; = 1024 Bytes
.equ    LASTPAGE        = BOOTSTART - PAGESIZE  ; = 1 page below TSB!

.org    BOOTSTART

RESET:
        cli

        in tmp4, MCUSR                  ; check reset condition
        sbrc tmp4, WDRF                 ; in case of a Watchdog reset
        ;rjmp APPJUMP                    ; immediately leave TSB [disabled by KG]
        clr     tmp1
        out     0x34, tmp1              ; disable watchdog
        ldi     tmp2, 0x18
        sts     0x60, tmp2              ; enable change (WDCE)
        sts     0x60, tmp1              ; disable WDE

        ldi tmp1, low (RAMEND)          ; write ramend low
        out SPL, tmp1                   ; into SPL (stackpointer low)
.ifdef SPH
        ldi tmp1, high(RAMEND)          ; write ramend high for ATtinys
        out SPH, tmp1                   ; with SRAM > 256 bytes
.endif

;-----------------------------------------------------------------------
; ACTIVATION CHECK
;-----------------------------------------------------------------------

WaitRX:
        sbi TXDDR, TXBIT                ; if RX=TX (One-Wire), port is
        ;sbi RXDDR, RXBIT                ; driven open collector style,   [KG removed]
        sbi RXPORT, RXBIT               ; else RX is input with pullup
        sbi TXPORT, TXBIT               ; and TX preset logical High
        sbi REDDR, REBIT                ; configure receive enable as output [KG]
        sbi TEDDR, TEBIT                ; configure transmit enable as output [KG]

; coldstart (power-up) - wait for RX to stabilize
WRX0To:
        sbic RXPIN, RXBIT               ; 1st stage - loop while RX = 0
        rjmp WRXSTo                     ; if RX = 1, start COM Timeout
        sbiw xl, 1                      ; use X for fast countdown
        brcc WRX0To                     ; if timed out with 0 level
        rjmp APPJUMP                    ; goto APPJUMP in LASTPAGE
WRXSTo:                                 ; else
        rcall ZtoLASTPAGE               ; set Z to start'o'LASTPAGE
        adiw zl, 2                      ; skip first 2 bytes
        lpm xh, z+                      ; load TIMEOUT byte
        ldi xl, 128

WRX1To:
        dec tmp1                        ; inner counter to delay
        brne WRX1To                     ; for debouncing/denoising
        sbis RXPIN, RXBIT               ; if serial startbit occurs
        rjmp Activate                   ; go Activate
        sbiw xl, 1                      ; use X for down counter
        brcc WRX1To                     ; to Timeout
        ;rjmp APPJUMP                   ; Timeout! Goto APPJUMP

;-----------------------------------------------------------------------
; ATMEGA APPJUMP = SIMPLE JUMP TO $0000 (ORIGINAL RESET VECTOR)
;-----------------------------------------------------------------------
; Boot Reset Vector (BOOTRST) must be activated for TSB on ATmegas.
; After timeout or executing commands, TSB for ATmegas will simply
; handover to the App by a (relative or absolute) jump to $0000.

APPJUMP:
        rcall SPMwait                   ; make sure everything's done
        clr tmp1
        out RXPORT, tmp1                ; reset PORT and DDR to zero
.if TXPORT != RXPORT
        out TXPORT, tmp1
.endif
        out TXDDR, tmp1
.if REDDR != TXDDR
        out REDDR, tmp1
.endif
.if TEDDR != TXDDR
        out TEDDR, tmp1
.endif

.if FLASHEND >= ($1fff)
        jmp  $0000                      ; absolute jump
.else
        rjmp $0000                      ; relative jump
.endif

;-----------------------------------------------------------------------
; BAUDRATE CALIBRATION CYCLE
;-----------------------------------------------------------------------

Activate:
        clr xl                          ; clear temporary
        clr xh                          ; baudrate counter
        ldi tmp1, 6                     ; number of expected bit-changes
actw1:
        sbic RXPIN, RXBIT               ; idle 1-states (stopbits, ones)
        rjmp actw1
actw2:
        adiw xl, 1                      ; precision measuring loop
        sbis RXPIN, RXBIT               ; count clock cycles
        rjmp actw2                      ; while RX is 0-state
        dec tmp1
        brne actw1
actwx:
        movw bclkl, xl                  ; save result in bclk

;-----------------------------------------------------------------------
; CHECK PASSWORD / EMERGENCY ERASE
;-----------------------------------------------------------------------

CheckPassword:
chpw0:  ser tmp4                        ; tmp4 = 255 enables comparison
chpw1:  lpm tmp3, z+                    ; load pw character from Z
        and tmp3, tmp4                  ; tmp3 = 0 disables comparison
        cpi tmp3, 255                   ; byte value 255 indicates
        breq chpwx                      ; end of password -> success
chpw2:  rcall Receivebyte               ; else receive next character
        cpi tmp1, 0                     ; rxbyte = 0 will branch
        breq chpwee                     ; to confirm emergency erase
        cp  tmp1, tmp3                  ; compare password with rxbyte
        breq chpw0                      ; if equal check next character
        clr  tmp4                       ; tmp4 = 0 to loop forever
        rjmp chpw1                      ; all to smoothen power profile
chpwee:
        rcall RequestConfirm            ; request confirmation
        brts chpa                       ; not confirmed, leave
        rcall RequestConfirm            ; request 2nd confirmation
        brts chpa                       ; can't be mistake now
        rcall EmergencyErase            ; go, emergency erase!
        rjmp  Mainloop
chpa:
        rjmp APPJUMP                    ; start application
chpwx:
;       rjmp SendDeviceInfo             ; go on to SendDeviceInfo

;-----------------------------------------------------------------------
; SEND DEVICEINFO
;-----------------------------------------------------------------------

SendDeviceInfo:
        ldi zl, low (DEVICEINFO*2)      ; load address of deviceinfo
        ldi zh, high(DEVICEINFO*2)      ; low and highbyte
        ldi bcnt, INFOLEN*2
        rcall SendFromFlash

;-----------------------------------------------------------------------
; MAIN LOOP TO RECEIVE AND EXECUTE COMMANDS
;-----------------------------------------------------------------------

Mainloop:
        clr zl                          ; clear Z pointer
        clr zh                          ; which is frequently used
        rcall SendConfirm               ; send CONFIRM via RS232
        rcall Receivebyte               ; receive command via RS232
        rcall CheckCommands             ; check command letter
        rjmp Mainloop                   ; and loop on

;-----------------------------------------------------------------------
; CHANGE USER DATA IN LASTPAGE
;-----------------------------------------------------------------------

ChangeSettings:
        rcall GetNewPage                ; get new LASTPAGE contents
        brtc ChangeS0                   ; from Host (if confirmed)
        ret
ChangeS0:
        rcall ZtoLASTPAGE               ; re-write LASTPAGE
        rcall EraseFlashPage
        rcall WritePage                 ; erase and write LASTPAGE

;-----------------------------------------------------------------------
; SEND USER DATA FROM LASTPAGE
;-----------------------------------------------------------------------

ControlSettings:
        rcall ZtoLASTPAGE               ; point to LASTPAGE
;       rcall SendPageFromFlash

;-----------------------------------------------------------------------
; SEND DATA FROM FLASH MEMORY
;-----------------------------------------------------------------------

SendPageFromFlash:
        ldi bcnt, low (PAGESIZE*2)      ; whole Page to send
SendFromFlash:
        rcall SPMwait                   ; (re)enable RWW read access
        lpm tmp1, z+                    ; read directly from flash
        rcall Transmitbyte              ; and send out to RS232
        dec bcnt                        ; bcnt is number of bytes
        brne SendFromFlash
        ret

;-----------------------------------------------------------------------
; READ APPLICATION FLASH
;-----------------------------------------------------------------------
; read and transmit application flash area (pagewise)

ReadAppFlash:
RAF0:
        rcall RwaitConfirm
        brts RAFx
        rcall SendPageFromFlash
RAF1:
        cpi zl, low (LASTPAGE*2)        ; count up to last byte
        brne RAF0                       ; below LASTPAGE
        cpi zh, high(LASTPAGE*2)
        brne RAF0
RAFx:
        ret

;-----------------------------------------------------------------------
; WRITE APPLICATION FLASH
;-----------------------------------------------------------------------
; Write Appflash pagewise, don't modify anything for ATmegas

WriteAppFlash:
        rcall EraseAppFlash             ; Erase whole app flash
Flash2:
        rcall GetNewPage                ; get next page from host
        brts FlashX                     ; stop on user's behalf
Flash3:
        rcall WritePage                 ; write page data into flash
Flash4:
        cpi zh, high(LASTPAGE*2-1)      ; end of available Appflash?
        brne Flash2                     ; if Z reached last location
        cpi zl, low (LASTPAGE*2-1)      ; then we are finished
        brne Flash2                     ; else go on
FlashX:
        ret                             ; we're already finished!

;-----------------------------------------------------------------------
; WRITE FLASH PAGE FROM BUFFER, VERIFYING AND VERIFY-ERROR-HANDLING
;-----------------------------------------------------------------------

WritePage:
        rcall YtoBUFFER                 ; Y=BUFFER, bcnt=PAGESIZE*2
        rcall SPMwait
WrPa1:
        ld r0, y+                       ; fill R0/R1 with word
        ld r1, y+                       ; from buffer position Y / Y+1
        ldi tmp1, 0b00000001            ; set only SPMEN in SPMCSR
        out SPMCSR, tmp1                ; to activate page buffering
        spm                             ; store word in page buffer
        adiw zl, 2                      ; and forward to next word
        subi bcnt, 2
        brne WrPa1
        ; Z = start of next page now
        subi zl, low (PAGESIZE*2)       ; point back Z to
        sbci zh, high(PAGESIZE*2)       ; start of current page
        ; Z = back on current page's start
WrPa2:
        ldi tmp1, 0b00000101            ; enable PRWRT + SPMEN
        out SPMCSR, tmp1                ; in SPMCSR
        spm                             ; write whole page to flash
WrPa3:
        in tmp1, SPMCSR                 ; wait for flash write finished
        sbrc tmp1, 0                    ; skip if SPMEN (bit0) cleared
        rjmp WrPa3                      ; ITS BEEN WRITTEN
        subi zl, low (65536-PAGESIZE*2)      ; same effect as
        sbci zh, high(65536-PAGESIZE*2)      ; Z = Z + PAGESIZE*2
        rjmp SPMwait
        ;ret

;-----------------------------------------------------------------------
; CHECK COMMANDS
;-----------------------------------------------------------------------

CheckCommands:
        cpi tmp1, 'c'                   ; read LASTPAGE
        breq ControlSettings
        cpi tmp1, 'C'                   ; write LASTPAGE
        breq ChangeSettings
        cpi tmp1, 'f'                   ; read Appflash
        breq ReadAppFlash
        cpi tmp1, 'F'                   ; write Appflash
        breq WriteAppFlash
        cpi tmp1, 'e'                   ; read EEPROM
        breq EepromRead
        cpi tmp1, 'E'                   ; write EEPROM
        breq EEpromWrite
        rjmp APPJUMP                    ; else start application

;-----------------------------------------------------------------------
; EEPROM READ/WRITE ACCESS
;-----------------------------------------------------------------------

EepromWrite:
EEWr0:
        rcall GetNewPage                ; get EEPROM datablock
        brts EERWFx                     ; or abort on host's demand
EEWr1:
        rcall YtoBUFFER                 ; Y = Buffer and Bcnt = blocksize
EEWr2:
        ld tmp1, y+                     ; read EEPROM byte from buffer
        rcall EEWriteByte
        dec bcnt                        ; count down block byte counter
        brne EEWr2                      ; loop on if block not finished
        rjmp EeWr0

;-----------------------------------------------------------------------

EEpromRead:
EeRe1:
        rcall RwaitConfirm              ; wait to confirm
        brts EERWFx                     ; else we are finished
        ldi bcnt, low(PAGESIZE*2)       ; again PAGESIZE*2 is blocksize
EERe2:
        out EEARL, zl                   ; current EEPROM address low
        .ifdef  EEARH
        out EEARH, zh                   ; current EEPROM address high
        .endif
        sbi EECR, 0                     ; set EERE - EEPROM read enable
        in tmp1, EEDR                   ; read byte from current address
        rcall Transmitbyte              ; send out to RS232
        adiw zl,1                       ; count up EEPROM address
        dec bcnt                        ; count down block byte counter
        brne EERe2                      ; loop on if block not finished
        rjmp EERe1
EERWFx:
        ret

;-----------------------------------------------------------------------

EEWriteByte:
        out EEDR, tmp1                  ; write to EEPROM data register
        out EEARL, zl                   ; current EEPROM address low
        .ifdef  EEARH
        out EEARH, zh                   ; high EEARH for some attinys
        .endif
        sbi EECR, 2                     ; EEPROM master prog enable
        sbi EECR, 1                     ; EEPE initiate prog cycle
EeWB:
        sbic EECR, 1                    ; wait write cycle to complete
        rjmp EeWB                       ; before we can go on
        adiw zl,1                       ; count up EEPROM address
        ret

;-----------------------------------------------------------------------
; GET NEW PAGE
;-----------------------------------------------------------------------

GetNewPage:
        rcall RequestConfirm            ; check for Confirm
        brts GNPx                       ; abort if not confirmed
GNP0:
        rcall YtoBUFFER                 ; Y = BUFFER, bcnt = PAGESIZE*2
GNP1:
        rcall ReceiveByte               ; receive serial byte
        st y+, tmp1                     ; and store in buffer
        dec bcnt                        ; until full page loaded
        brne GNP1                       ; loop on
GNPx:
        ret                             ; finished
;-----------------------------------------------------------------------
; REQUEST TO CONFIRM / AWAIT CONFIRM COMMAND
;-----------------------------------------------------------------------

RequestConfirm:
        ldi tmp1, REQUEST               ; send request character
        rcall Transmitbyte              ; prompt to confirm (or not)

RwaitConfirm:
        rcall ReceiveByte               ; get host's reply
        clt                             ; set T=0 for confirmation
        cpi tmp1, CONFIRM               ; if host HAS sent CONFIRM
        breq RCx                        ; return with the T=0
        set                             ; else set T=1 (NOT CONFIRMED)
RCx:
        ret                             ; whether confirmed or not

;-----------------------------------------------------------------------
; FLASH ERASE TOP-TO-BOTTOM ( (BOOTSTART-1) ... $0000)
;-----------------------------------------------------------------------

EraseAppFlash:
        rcall ZtoLASTPAGE               ; point Z to LASTPAGE, directly
EAF0:
        subi zl, low (PAGESIZE*2)
        sbci zh, high(PAGESIZE*2)
        rcall EraseFlashPage
        brne EAF0                       ; until first page reached
EAFx:   ret                             ; and leave with Z = $0000

;-----------------------------------------------------------------------
; EMERGENCY ERASE OF FLASH / EEPROM / USERDATA
;-----------------------------------------------------------------------

EmergencyErase:
        rcall EraseAppFlash             ; erase Application Flash
        ser tmp1                        ; byte value for EEPROM writes
EEE0:
        rcall EEWriteByte               ; write EEPROM byte, Z = Z + 1
        cpi zh, high(EEPROMEND+1)+2     ; EEPROMEND
        brne EEE0                       ; and loop on until finished

        rcall ZtoLASTPAGE               ; LASTPAGE is to be erased
;        rcall EraseFlashPage

;-----------------------------------------------------------------------
; ERASE ONE FLASH PAGE
;-----------------------------------------------------------------------

EraseFlashPage:
        ldi tmp1, 0b00000011            ; enable PGERS + SPMEN
        out SPMCSR, tmp1                ; in SPMCSR and erase current
        spm                             ; page by SPM (MCU halted)

; Waiting for SPM to be finished is *obligatory* on ATmegas!
SPMwait:
        in tmp1, SPMCSR
        sbrc tmp1, 0                    ; wait previous SPMEN
        rjmp SPMwait
        ldi tmp1, 0b00010001            ; set RWWSRE and SPMEN
        out SPMCSR, tmp1
        spm
        ret

;-----------------------------------------------------------------------
; OTHER SUBROUTINES
;-----------------------------------------------------------------------

YtoBUFFER:
        ldi yl, low (BUFFER)            ; reset pointer
        ldi yh, high(BUFFER)            ; to programming buffer
        ldi bcnt, low(PAGESIZE*2)       ; and often needed
        ret

;-----------------------------------------------------------------------

ZtoLASTPAGE:
        ldi zl, low (LASTPAGE*2)        ; reset Z to LASTPAGE start
        ldi zh, high(LASTPAGE*2)
        ret

;-----------------------------------------------------------------------
; RS232 RECEIVE BYTE
;-----------------------------------------------------------------------

ReceiveByte:
        ;sbi RXPORT, RXBIT               ; again set pullup for RX [KG removed]
Recb1:
        sbic RXPIN, RXBIT               ; wait for startbit (0)
        rjmp Recb1                      ; loop while stop state (1)
Recb2:
        ldi tmp2, 8                     ; bitcounter
        rcall Waithalfbitcell           ; tune to center of startbit
Recb3:
        rcall Waitbitcell               ; tune to center of bitcell
        lsr tmp1                        ; right shift 0 into bit 7
        sbic RXPIN, RXBIT               ; if RXD bit is 1
        sbr tmp1, 0b10000000            ; set bit 7
Recb4:
        dec tmp2                        ; count down bitcounter
        brne Recb3                      ; loop until 8 bits collected
        rjmp Waitbitcell                ; wait into center of stopbit

;-----------------------------------------------------------------------
; RS232 SEND CONFIRM CHARACTER
;-----------------------------------------------------------------------

SendConfirm:
        ldi tmp1, CONFIRM
        ;rjmp Transmitbyte

;-----------------------------------------------------------------------
; RS232 TRANSMIT BYTE
;-----------------------------------------------------------------------

TransmitByte:
        sbi REPORT, REBIT               ; disable receive [KG]
        sbi TEPORT, TEBIT               ; enable transmit [KG]
        rcall Waitbitcell               ; ensure safe RX-TX transition
        rcall Trx0                      ; transmit 0 = startbit
        ldi tmp2, 8                     ; set bitcounter
Trxbit:                                 ; transmit byte loop
        sbrc tmp1, 0
        rcall Trx1                      ; sent logical 1 bitcell
        sbrs tmp1, 0                    ; or
        rcall Trx0                      ; sent logical 0 bitcell
        lsr tmp1                        ; shift out that bit
        dec tmp2                        ; count down
        brne Trxbit                     ; loop until all bits sent
        rcall Trx1
        cbi TEPORT, TEBIT               ; disable transmit [KG]
        cbi REPORT, REBIT               ; enable receive [KG]
        ret
Trx1:
        ;sbi TXDDR, TXBIT                ; if RX=TX (One-Wire), result is [KG removed]
        ;cbi RXDDR, RXBIT                ; pullup to Vcc for "1" (high-Z) [KG removed]
        sbi TXPORT, TXBIT               ; else portbit actively driven
        rjmp Waitbitcell
Trx0:
        ;sbi TXDDR, TXBIT                ; set TX driver for output [KG removed]
        cbi TXPORT, TXBIT               ; set portbit to active "0"
;       rjmp Waitbitcell                ; continue with Waitbitcell

;-----------------------------------------------------------------------
; RS232 PRECISION TIMING
;-----------------------------------------------------------------------

Waitbitcell:
        movw xl, bclkl                  ; load bitcell clock timer
wbc1:
        sbiw xl, 24                     ; same number of clocks
        nop                             ; as in calibration loop
        brcc wbc1
wbcx:
        ret

Waithalfbitcell:
        movw xl, bclkl                  ; load bitcell clock timer
        lsr xh                          ; shiftout bit 0 of xh to carry
        ror xl                          ; carry shifted in bit 7 of xl
        rjmp wbc1                       ; run timer with 1/2 divider

DebugTest:
        ldi tmp1, REQUEST               ; send request character
        rcall Transmitbyte              ; prompt to confirm (or not)
        rjmp  DebugTest

;-----------------------------------------------------------------------
; DEVICE INFO BLOCK = PERMANENT DATA
;-----------------------------------------------------------------------

DEVICEINFO:
.message "DEVICE INFO BLOCK FOR ATMEGA"
.db "TSB", low (BUILDDATE), high (BUILDDATE), BUILDSTATE
.db SIGNATURE_000, SIGNATURE_001, SIGNATURE_002, low (PAGESIZE)
.dw BOOTSTART-PAGESIZE
.dw EEPROMEND
.db $AA, $AA

.message "ASSEMBLY OF TSB FOR ATMEGA SUCCESSFULLY FINISHED!"

.endif               ; closing TSB for ATmega sourcecode;

;***********************************************************************
; END OF TSB FOR ATMEGAS
;***********************************************************************

.exit

;***********************************************************************
;***********************************************************************
;***********************************************************************
; END OF CONDITIONAL ASSEMBLY SOURCE OF TSB FOR ATTINYS AND ATMEGAS
;***********************************************************************
;***********************************************************************
;***********************************************************************


text:
'use strict';

Template.repoMeteorPackage.onRendered(function(){
  var
    self = this,
    repoDetails = self.data.repoDetails
  ;

  if (repoDetails && repoDetails.pkgInfo && repoDetails.pkgInfo.enabled){
    self.$('.ui.checkbox').checkbox('check');
  }
  else {
    self.$('.ui.checkbox').checkbox('uncheck');
  }
});

Template.repoMeteorPackage.created = function(){
  var self = this;
  self.updating = new ReactiveVar(false);
};

Template.repoMeteorPackage.helpers({
  updating: function(){
    return Template.instance().updating.get();
  },
});

Template.repoMeteorPackage.events({
  'click .ui.checkbox': function(e, instance){
    var
      data = instance.data,
      pkgInfo = data.repoDetails && data.repoDetails.pkgInfo
    ;

    if (pkgInfo) {
      instance.updating.set(true);
      Meteor.call('toggleMeteorPackage', {
        id: data._id,
        fullName: data.full_name,
        pkgName: pkgInfo.name,
        pkgVersion: pkgInfo.version,
        pkgSummary: pkgInfo.summary,
        gitUrl: data.html_url
      }, function(err, result){
        instance.updating.set(false);
        if (result.enabled !== undefined){
          instance.data.repoDetails.pkgInfo.enabled = result.enabled;
          var status = 'uncheck';
          if (result.enabled){
            status = 'check';
          }
          instance.$('.ui.checkbox').checkbox(status);
        }
      });
    }
  },
});


text:
namespace NorthwindWindowsStore.ViewModel
{
    using System;

    public partial class SummaryOfSalesByQuarterViewModel
    {
        public DateTime? ShippedDate { get; set; }
        public int OrderID { get; set; }
        public decimal? Subtotal { get; set; }
    }
}


text:
var _ = require('underscore');
var MapnikRenderer = require('../../renderers/mapnik');

function RendererStatsReporter(renderCache, statsInterval) {
    this.renderCache = renderCache;
    this.statsInterval = statsInterval || 6e4;
    this.renderersStatsIntervalId = null;
}

module.exports = RendererStatsReporter;

RendererStatsReporter.prototype.start = function() {
    var self = this;
    this.renderersStatsIntervalId = setInterval(function() {
        var renderCacheEntries = self.renderCache.renderers;

        if (!renderCacheEntries) {
            return null;
        }

        global.statsClient.gauge('windshaft.rendercache.count', _.keys(renderCacheEntries).length);

        var renderersStats = _.filter(renderCacheEntries, function(cacheEntry) {
            return cacheEntry.renderer && cacheEntry.renderer.constructor === MapnikRenderer.adaptor &&
                cacheEntry.renderer.renderer._pool;
        }).reduce(
            function(_rendererStats, cacheEntry) {
                if (cacheEntry.renderer.renderer._pool) {
                    _rendererStats.pool.count += cacheEntry.renderer.renderer._pool.getPoolSize();
                    _rendererStats.pool.unused += cacheEntry.renderer.renderer._pool.availableObjectsCount();
                    _rendererStats.pool.waiting += cacheEntry.renderer.renderer._pool.waitingClientsCount();
                }

                if (cacheEntry.renderer.renderer._tileCache && cacheEntry.renderer.renderer._tileCache.results) {
                    _rendererStats.cache = Object.keys(cacheEntry.renderer.renderer._tileCache.results).reduce(
                        function(cacheStats, key) {
                            if (key.match(/^utf/)) {
                                cacheStats.grid += 1;
                            } else {
                                cacheStats.png += 1;
                                var buf = cacheEntry.renderer.renderer._tileCache.results[key][1];
                                if (buf) {
                                    cacheStats.pngBufferSize += buf.length || 0;
                                }
                            }
                            return cacheStats;
                        },
                        _rendererStats.cache
                    );
                }

                return _rendererStats;
            },
            {
                pool: {
                    count: 0,
                    unused: 0,
                    waiting: 0
                },
                cache: {
                    pngBufferSize: 0,
                    png: 0,
                    grid: 0
                }
            }
        );

        global.statsClient.gauge('windshaft.mapnik-cache.png', renderersStats.cache.png);
        global.statsClient.gauge('windshaft.mapnik-cache.png-size', renderersStats.cache.pngBufferSize);
        global.statsClient.gauge('windshaft.mapnik-cache.grid', renderersStats.cache.grid);

        global.statsClient.gauge('windshaft.mapnik-pool.count', renderersStats.pool.count);
        global.statsClient.gauge('windshaft.mapnik-pool.unused', renderersStats.pool.unused);
        global.statsClient.gauge('windshaft.mapnik-pool.waiting', renderersStats.pool.waiting);
    }, this.statsInterval);

};

RendererStatsReporter.prototype.stop = function() {
    clearInterval(this.renderersStatsIntervalId);
    this.renderersStatsIntervalId = null;
};


text:
package org.jbb.permissions.impl;

import static org.mockito.BDDMockito.given;

import com.google.common.collect.Lists;
import java.util.Comparator;
import java.util.List;
import org.jbb.install.InstallUpdateAction;
import org.jbb.install.InstallationData;
import org.jbb.lib.test.MockCommonsConfig;
import org.jbb.members.api.base.MemberService;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PermissionsConfig.class, MockCommonsConfig.class,
    MockPermissionsConfig.class})
public abstract class BaseIT {

    public static boolean installed;

    @Autowired
    MemberService memberService;

    @Autowired
    List<InstallUpdateAction> installActions;

    @Before
    public void setUp() {
        given(memberService.getAllMembersSortedByRegistrationDate())
                .willReturn(Lists.newArrayList());
        if (!installed) {
            installActions.sort(Comparator.comparing(InstallUpdateAction::fromVersion));
            installActions.forEach(action -> action.install(InstallationData.builder().build()));
            installed = true;
        }
    }

}


text:
#if defined CORE_M4
#include "LPC43xx.h"                    /* LPC43xx definitions                */
#endif

#ifdef CORE_M0
#include "LPC43xx_M0.h"                /* LPC43xx definitions                */
#endif

#include "type.h"
#include "scu.h"

void scu_pinmux(unsigned port, unsigned pin, unsigned mode, unsigned func)
{
  volatile unsigned int * const scu_base=(unsigned int*)(LPC_SCU_BASE);
  scu_base[(PORT_OFFSET*port+PIN_OFFSET*pin)/4]=mode+func;
} /* scu_pinmux */


text:
A few scripts I threw together to automate portions of setting up a pile of Raspberry Pi 4s with an SSD rootfs.

I'm guessing none of this will be necessary anymore once the RPI4 firmware is updated to support boot from USB devices.

Note that a fair amount of this is cobbled together from various fixes and snippets found on stackoverflow/elsewhere. If I left off attribution somewhere, please let me know.

Assumptions:
 - Scripts are run from a workstation running a modern Ubuntu with automount at `/media/$USERNAME/[label]`.
 - Raspbian is being used on the Raspberry Pis.
 - Raspberry Pis are using automatic DHCP-based wired addresses. These scripts don't assist in any way with network configuration.

Equipment needed for each RPI:
 - SD Card
 - SSD
 - Your favorite USB3-SATA (or USB3-NVME) adapter. Tip: Try it out under Raspbian beforehand, and tweak the usb-storage.quirks kernel parameter and/or modprobe blacklist config in `bind-ssd-to-sdcard.sd` to suit if you run into issues (poor performance, errors in dmesg) with UAS.

Before running these scripts:
 1. Write a Raspbian image to each SSD and SD card (using dd or whatnot).
 1. Use gparted to remove the `boot` partition from the SSD, relabel the `rootfs` partition to `ssdroot`, and resize it to fill the disk. [TODO: script this part.]

Running the scripts (for each SSD+SD card pair):
 1. Unplug and plug in the SSD and SD card to ensure the kernel has re-read the partition tables.
 1. Run both `update-partuuid-sdcard.sh` and `update-partuuid-ssd.sh` to generate and write random PARTUUIDs.
 1. Unplug/plug in again, and ensure all three partitions are mounted (`boot` and `rootfs` from the SD card; `ssdroot` from the SSD)
 1. Run `bind-ssd-to-sdcard.sh`
 1. Insert the SD card and attach the SSD to the RPI. Because the cmdline.txt on the SDCard references the PARTUUID of the SSD, mismatched SSD/SD cards will not boot.


text:
package org.apache.directmemory.conf;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class ConfigurationTest
{
    @Test
    public void testBaseConfiguration()
    {
        assertTrue( Configuration.getNumberOfBuffers() > 0 );
        assertTrue( Configuration.getInitialCapacity() > 0 );
        assertTrue( Configuration.getRamMegaBytes() > 0 );
        assertTrue( Configuration.getConcurrencyLevel() > 0 );
        assertTrue( Configuration.getDisposalTime() > 0L );
    }

    @Test
    public void testYamlConfiguration()
    {
        Configuration.configureFromYaml();
        assertTrue( Configuration.getNumberOfBuffers() > 0 );
        assertTrue( Configuration.getInitialCapacity() > 0 );
        assertTrue( Configuration.getRamMegaBytes() > 0 );
        assertTrue( Configuration.getConcurrencyLevel() > 0 );
        assertTrue( Configuration.getDisposalTime() > 0L );
    }
}


text:
from FeatureGenerator import *
from TfidfFeatureGenerator import *
import pandas as pd
import numpy as np
from scipy.sparse import vstack
import cPickle
from sklearn.decomposition import TruncatedSVD
from helpers import *

class SvdFeatureGenerator(FeatureGenerator):

    def __init__(self, name='svdFeatureGenerator'):
        super(SvdFeatureGenerator, self).__init__(name)

    def process(self, df):

        n_train = df[~df['target'].isnull()].shape[0]
        print 'SvdFeatureGenerator, n_train:',n_train
        n_test  = df[df['target'].isnull()].shape[0]
        print 'SvdFeatureGenerator, n_test:',n_test

        tfidfGenerator = TfidfFeatureGenerator('tfidf')
        featuresTrain = tfidfGenerator.read('train')
        xHeadlineTfidfTrain, xBodyTfidfTrain = featuresTrain[0], featuresTrain[1]

        xHeadlineTfidf = xHeadlineTfidfTrain
        xBodyTfidf = xBodyTfidfTrain
        if n_test > 0:
            # test set is available
            featuresTest  = tfidfGenerator.read('test')
            xHeadlineTfidfTest,  xBodyTfidfTest  = featuresTest[0],  featuresTest[1]
            xHeadlineTfidf = vstack([xHeadlineTfidfTrain, xHeadlineTfidfTest])
            xBodyTfidf = vstack([xBodyTfidfTrain, xBodyTfidfTest])

        # compute the cosine similarity between truncated-svd features
        svd = TruncatedSVD(n_components=50, n_iter=15)
        xHBTfidf = vstack([xHeadlineTfidf, xBodyTfidf])
        svd.fit(xHBTfidf) # fit to the combined train-test set (or the full training set for cv process)
        print 'xHeadlineTfidf.shape:'
        print xHeadlineTfidf.shape
        xHeadlineSvd = svd.transform(xHeadlineTfidf)
        print 'xHeadlineSvd.shape:'
        print xHeadlineSvd.shape

        xHeadlineSvdTrain = xHeadlineSvd[:n_train, :]
        outfilename_hsvd_train = "train.headline.svd.pkl"
        with open(outfilename_hsvd_train, "wb") as outfile:
            cPickle.dump(xHeadlineSvdTrain, outfile, -1)
        print 'headline svd features of training set saved in %s' % outfilename_hsvd_train

        if n_test > 0:
            # test set is available
            xHeadlineSvdTest = xHeadlineSvd[n_train:, :]
            outfilename_hsvd_test = "test.headline.svd.pkl"
            with open(outfilename_hsvd_test, "wb") as outfile:
                cPickle.dump(xHeadlineSvdTest, outfile, -1)
            print 'headline svd features of test set saved in %s' % outfilename_hsvd_test

        xBodySvd = svd.transform(xBodyTfidf)
        print 'xBodySvd.shape:'
        print xBodySvd.shape

        xBodySvdTrain = xBodySvd[:n_train, :]
        outfilename_bsvd_train = "train.body.svd.pkl"
        with open(outfilename_bsvd_train, "wb") as outfile:
            cPickle.dump(xBodySvdTrain, outfile, -1)
        print 'body svd features of training set saved in %s' % outfilename_bsvd_train

        if n_test > 0:
            # test set is available
            xBodySvdTest = xBodySvd[n_train:, :]
            outfilename_bsvd_test = "test.body.svd.pkl"
            with open(outfilename_bsvd_test, "wb") as outfile:
                cPickle.dump(xBodySvdTest, outfile, -1)
            print 'body svd features of test set saved in %s' % outfilename_bsvd_test

        simSvd = np.asarray(map(cosine_sim, xHeadlineSvd, xBodySvd))[:, np.newaxis]
        print 'simSvd.shape:'
        print simSvd.shape

        simSvdTrain = simSvd[:n_train]
        outfilename_simsvd_train = "train.sim.svd.pkl"
        with open(outfilename_simsvd_train, "wb") as outfile:
            cPickle.dump(simSvdTrain, outfile, -1)
        print 'svd sim. features of training set saved in %s' % outfilename_simsvd_train

        if n_test > 0:
            # test set is available
            simSvdTest = simSvd[n_train:]
            outfilename_simsvd_test = "test.sim.svd.pkl"
            with open(outfilename_simsvd_test, "wb") as outfile:
                cPickle.dump(simSvdTest, outfile, -1)
            print 'svd sim. features of test set saved in %s' % outfilename_simsvd_test

        return 1

    def read(self, header='train'):

        filename_hsvd = "%s.headline.svd.pkl" % header
        with open(filename_hsvd, "rb") as infile:
            xHeadlineSvd = cPickle.load(infile)

        filename_bsvd = "%s.body.svd.pkl" % header
        with open(filename_bsvd, "rb") as infile:
            xBodySvd = cPickle.load(infile)

        filename_simsvd = "%s.sim.svd.pkl" % header
        with open(filename_simsvd, "rb") as infile:
            simSvd = cPickle.load(infile)

        print 'xHeadlineSvd.shape:'
        print xHeadlineSvd.shape
        #print type(xHeadlineSvd)
        print 'xBodySvd.shape:'
        print xBodySvd.shape
        #print type(xBodySvd)
        print 'simSvd.shape:'
        print simSvd.shape
        #print type(simSvd)

        return [xHeadlineSvd, xBodySvd, simSvd.reshape(-1, 1)]
        #return [simSvd.reshape(-1, 1)]

 #   Copyright 2017 Cisco Systems, Inc.
 #
 #   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.


text:
/*
 * process.cpp
 *
 *  Created on: Jun 23, 2015
 *      Author: Fabian Tschopp
 */

#include "process.hpp"
#include "filesystem_utils.hpp"
#include "utils.hpp"
#include "caffe/layers/memory_data_layer.hpp"

namespace caffe_neural {

int ExportFilters(Net<float> *net, std::string output_folder,
                  bofs::path input_name, int st, int y, int x, bool store_diff) {
  std::vector<std::string> names = net->blob_names();
  std::vector<boost::shared_ptr<Blob<float>>>blobs = net->blobs();

  for (unsigned int i = 0; i < names.size(); ++i) {
    std::string name = names[i];
    shared_ptr<Blob<float>> blob = blobs[i];

    const float* cpu_ptr = blob->cpu_data();
    const float* cpu_diff_ptr = nullptr;
    if (store_diff) {
      cpu_diff_ptr = blob->cpu_diff();
    }

    for (int n = 0; n < blob->num(); ++n) {
      for (int c = 0; c < blob->channels(); ++c) {

        cv::Mat mat(blob->height(), blob->width(), CV_32FC1);
        cv::Mat matd(blob->height(), blob->width(), CV_32FC1);

        for (int h = 0; h < blob->height(); ++h) {
#pragma omp parallel for
          for (int w = 0; w < blob->width(); ++w) {
            mat.at<float>(h, w) = *(cpu_ptr + w);
          }
          cpu_ptr += blob->width();
        }

        if (store_diff) {
          for (int h = 0; h < blob->height(); ++h) {
  #pragma omp parallel for
            for (int w = 0; w < blob->width(); ++w) {
              matd.at<float>(h, w) = *(cpu_diff_ptr + w);
            }
            cpu_diff_ptr += blob->width();
          }
        }

        bofs::path outp(output_folder);

        std::stringstream ssp;
        ssp << "/";
        ssp << input_name.stem().string();
        ssp << "_" << st << "_" << y << "_" << x;

        std::stringstream ssf;
        ssf << "/";
        ssf << name;
        ssf << "_" << n << "_" << c;
        ssf << ".png";

        std::stringstream ssfd;
        ssfd << "/";
        ssfd << name;
        ssfd << "_" << n << "_" << c << "_diff";
        ssfd << ".png";

        bofs::path outpl = outp;
        outpl /= (ssp.str());
        bofs::create_directories(outpl);
        bofs::path filep = outpl;
        filep /= (ssf.str());

        bofs::path filepd = outpl;
        filepd /= (ssfd.str());

        cv::Mat outfc;
        cv::Mat outuc;

        {
          double minVal, maxVal;
          cv::minMaxLoc(mat, &minVal, &maxVal);

          mat.convertTo(outfc, CV_32FC1, 1.0 / (maxVal - minVal),
                    -minVal * 1.0 / (maxVal - minVal));
          outfc.convertTo(outuc, CV_8UC1, 255.0, 0.0);

          cv::imwrite(filep.string(), outuc);
        }
        if (store_diff) {
          double minVal, maxVal;
          cv::minMaxLoc(matd, &minVal, &maxVal);

          matd.convertTo(outfc, CV_32FC1, 1.0 / (maxVal - minVal),
                    -minVal * 1.0 / (maxVal - minVal));
          outfc.convertTo(outuc, CV_8UC1, 255.0, 0.0);

          cv::imwrite(filepd.string(), outuc);
        }
      }
    }
  }
  return 0;
}

int Process(caffe_neural::ToolParam &tool_param, CommonSettings &settings) {

  if (tool_param.train_size() <= settings.param_index) {
    LOG(FATAL)<< "Train parameter index does not exist.";
  }

  ProcessParam process_param = tool_param.process(settings.param_index);
  InputParam input_param = process_param.input();
  OutputParam output_param = process_param.output();

  if(!output_param.has_output()) {
    LOG(FATAL) << "Processing output path missing.";
  }

  std::string outpath = output_param.output();
  std::string format = output_param.has_format() ? output_param.format() : ".tif";
  std::transform(format.begin(), format.end(), format.begin(), ::tolower);
  bool fp32out = output_param.has_fp32_out() ? output_param.fp32_out() : false;
  if(fp32out) {
    format = ".tif";
  }
  std::set<std::string> filetypes = CreateImageTypesSet();
  if (filetypes.find(format) == filetypes.end()) {
    format = ".tif";
  }

  if(!(input_param.has_patch_size() && input_param.has_padding_size() && input_param.has_labels() && input_param.has_channels())) {
    LOG(FATAL) << "Patch size, padding size, label count or channel count parameter missing.";
  }
  int patch_size = input_param.patch_size();
  int padding_size = input_param.padding_size();
  unsigned int nr_labels = input_param.labels();
  unsigned int nr_channels = input_param.channels();

  if(!(process_param.has_process_net())) {
    LOG(FATAL) << "Processing network prototxt argument missing.";
  }

  std::string process_net = process_param.process_net();

  Net<float> net(process_net, caffe::TEST, Caffe::GetDefaultDevice());

  if(process_param.has_caffemodel()) {
    std::string caffe_model = process_param.caffemodel();
    net.CopyTrainedLayersFrom(caffe_model);
  }

  ProcessImageProcessor image_processor(patch_size, nr_labels);

  int imagecrop = 0;
  if(input_param.has_preprocessor()) {

    PreprocessorParam preprocessor_param = input_param.preprocessor();

    image_processor.SetBorderParams(input_param.has_padding_size(), padding_size / 2);
    image_processor.SetRotationParams(preprocessor_param.has_rotation() && preprocessor_param.rotation());
    image_processor.SetPatchMirrorParams(preprocessor_param.has_mirror() && preprocessor_param.mirror());
    image_processor.SetNormalizationParams(preprocessor_param.has_normalization() && preprocessor_param.normalization());

    if(preprocessor_param.has_histeq()) {
      PrepHistEqParam histeq_param = preprocessor_param.histeq();
      std::vector<float> label_boost(nr_labels, 1.0);
      for(int i = 0; i < histeq_param.label_boost().size(); ++i) {
        label_boost[i] = histeq_param.label_boost().Get(i);
      }
      image_processor.SetLabelHistEqParams(true, histeq_param.has_patch_prior()&&histeq_param.patch_prior(), histeq_param.has_masking()&&histeq_param.masking(), label_boost);
    }

    if(preprocessor_param.has_crop()) {
      PrepCropParam crop_param = preprocessor_param.crop();
      image_processor.SetCropParams(crop_param.has_imagecrop()?crop_param.imagecrop():0, crop_param.has_labelcrop()?crop_param.labelcrop():0);
      imagecrop = crop_param.has_imagecrop()?crop_param.imagecrop():0;
    }

    if(preprocessor_param.has_clahe()) {
      PrepClaheParam clahe_param = preprocessor_param.clahe();
      image_processor.SetClaheParams(true, clahe_param.has_clip()?clahe_param.clip():4.0);
    }

    if(preprocessor_param.has_blur()) {
      PrepBlurParam blur_param = preprocessor_param.blur();
      image_processor.SetBlurParams(true, blur_param.has_mean()?blur_param.mean():0.0, blur_param.has_std()?blur_param.std():0.1, blur_param.has_ksize()?blur_param.ksize():5);
    }
  }

  int error;
  std::vector<bofs::path> process_set = LoadProcessSetItems(filetypes, input_param.raw_images(),&error);

  for (unsigned int i = 0; i < process_set.size(); ++i) {
    LOG(INFO) << "Processing file: " << process_set[i];

    std::vector<cv::Mat> image_stack;

    std::string type = bofs::extension(process_set[0]);
    std::transform(type.begin(), type.end(), type.begin(), ::tolower);

    if(type == ".tif" || type == ".tiff") {
      // TIFF and multipage TIFF mode
      image_stack = LoadTiff(process_set[i].string(),
          nr_channels);
    } else {
      // All other image types
      cv::Mat image = cv::imread(process_set[i].string(),
          nr_channels == 1 ? CV_LOAD_IMAGE_GRAYSCALE:CV_LOAD_IMAGE_COLOR);
      image_stack.push_back(image);
    }

    std::vector<std::vector<cv::Mat>> output_stack;
    for (unsigned int st = 0; st < image_stack.size(); ++st) {
      image_processor.ClearImages();

      LOG(INFO) << "Processing subdirectory: " << st;

      cv::Mat image = image_stack[st];

      std::vector<cv::Mat> labels;
      image_processor.SubmitImage(image, i, labels);

      cv::Mat padimage = image_processor.raw_images()[0];

      int image_size_x = image.cols;
      int image_size_y = image.rows;

      std::vector<cv::Mat> outimgs;
      for(unsigned int k = 0; k < nr_labels; ++k) {
        cv::Mat outimg(image_size_y, image_size_x, CV_32FC1);
        outimgs.push_back(outimg);
      }

      for (int yoff = 0; yoff < (image_size_y - 1) / patch_size + 1; ++yoff) {
        for (int xoff = 0; xoff < (image_size_x - 1) / patch_size + 1; ++xoff) {

          int xoffp = xoff * patch_size;
          int yoffp = yoff * patch_size;

          if(xoffp + patch_size > image_size_x) {
            xoffp = image_size_x - patch_size;
          }

          if(yoffp + patch_size > image_size_y) {
            yoffp = image_size_y - patch_size;
          }

          cv::Rect roi(xoffp, yoffp,
              padding_size + patch_size - imagecrop,
              padding_size + patch_size - imagecrop);
          cv::Mat crop = padimage(roi);

          std::vector<cv::Mat> images;
          std::vector<int_tp> labels;

          images.push_back(crop);
          labels.push_back(0);

          boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>(
              (&net)->layers()[0])->AddMatVector(images, labels);

          float loss = 0.0;
          const vector<Blob<float>*>& result = net.ForwardPrefilled(&loss);

          if(process_param.has_filter_output()) {
            FilterOutputParam filter_param = process_param.filter_output();
            if(filter_param.has_output_filters() && filter_param.output_filters() && filter_param.has_output()) {
              ExportFilters(&net, filter_param.output(), process_set[i], st, yoff, xoff, false);
            }
          }

          const float* cpuresult = result[0]->cpu_data();

#pragma omp parallel for
          for (unsigned int k = 0; k < nr_labels; ++k) {
            for (int y = 0; y < patch_size; ++y) {
              for (int x = 0; x < patch_size; ++x) {
                (outimgs[k].at<float>(y + yoffp,
                        x + xoffp)) =
                cpuresult[(k * patch_size + y) * patch_size + x];
              }
            }
          }

          if (settings.graphic) {
            for (unsigned int k = 0; k < nr_labels; ++k) {
              cv::imshow(OCVDBGW, outimgs[k]);
              cv::waitKey(100);
            }
          }

        }
      }
      output_stack.push_back(outimgs);
    }

    // Output stacks only supported with multipage TIFFs
    if(output_stack.size() > 1) {
      format = ".tif";
    }

    bofs::path outp(outpath);
    bofs::create_directories(outp);

    unsigned int nr_out_labels = ((output_param.has_out_all_labels() && output_param.out_all_labels()) || nr_labels > 2)?nr_labels:1;

    // In the two label case, export the second and not the first label output
    unsigned int label_offset = nr_out_labels==1?1:0;

    for(unsigned int k = 0; k < nr_out_labels; ++k) {
      bofs::path outpl = outp;
      if(nr_out_labels > 1) {
        outpl /= ("/" + ZeroPadNumber(k,std::log10(nr_labels)+1));
        bofs::create_directories(outpl);
      }
      bofs::path filep = outpl;
      filep /= ("/" + process_set[i].stem().string()+format);

      std::vector<cv::Mat> saveout(output_stack.size());
      for(unsigned int st = 0; st < output_stack.size();++st) {
        if(fp32out) {
          output_stack[st][k+label_offset].convertTo(saveout[st], CV_32FC1, 1.0, 0.0);
        } else {
          output_stack[st][k+label_offset].convertTo(saveout[st], CV_8UC1, 255.0, 0.0);
        }
      }

      if(format == ".tif" || format == ".tiff") {
        SaveTiff(saveout,filep.string());
      } else {
        cv::imwrite(filep.string(),saveout[0]);
      }
    }
  }
  return 0;
}
}  // namespace caffe_neural