text:
//===========================================================================
//=-------------------------------------------------------------------------=
//= Module history:                                                         =
//= - November 25 2005 - Oscar Chavarro: Original base version              =
//= - December 7 2005 - Fabio Aroca / Eduardo Mendoza: importJOGLimage and  =
//=   getImageJOGL methods added                                            =
//= - March 14 2006 - Oscar Chavarro: quality check                         =
//===========================================================================

package vsdk.toolkit.render.jogl;

// Java base classes
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;

// JOGL classes
import javax.media.opengl.GL2;
import javax.media.opengl.GLProfile;
// import javax.media.opengl.glu.GLU;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureIO;
import com.jogamp.opengl.util.texture.TextureData;
//import com.jogamp.opengl.cg.CGparameter;
//import com.jogamp.opengl.cg.CgGL;

// VitralSDK classes
import vsdk.toolkit.common.VSDK;
import vsdk.toolkit.media.RGBImage;
import vsdk.toolkit.common.RendererConfiguration;

class _JoglRGBImageRendererImageAssociation extends JoglRenderer
{
    public int glList;
    public Texture renderer;
    public RGBImage image;
}

public class JoglRGBImageRenderer extends JoglRenderer
{
    private static ArrayList<_JoglRGBImageRendererImageAssociation> compiledImages = new ArrayList<_JoglRGBImageRendererImageAssociation>();
    //private static GLU glu = null;

    /**
    This method generates an OpenGL/JOGL MipMap structure, assoiates it with
    the given image reference and activates.

    The method keeps track of all images activated, and take that history into
    account to pass the image data to the graphics hardware only once. Note that
    this method creates and use an OpenGL/JOGL compilation list for each image,
    to ensure optimal performance.
    @return The OpenGL display list associated with this visualization
    \todo
    In applications with changing images, the memory list of compiled lists
    and the list themselves should be cleared, or not used. This will lead to
    the creation of new methods.
    */
    private static int activateBase(GL2 gl, RGBImage img)
    {
        //- 1. Initialization of texture parameters -----------------------
        int x_tam = img.getXSize();
        int y_tam = img.getYSize();
        int lists[] = new int[1];

        /*
        if ( (x_tam % 4) == 0 ) {
            gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4);
          }
          else if ( (x_tam % 2) == 0 ) {
            gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 2);
          }
          else {
            gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1);
        }

        if ( glu == null ) {
            glu = new GLU();
        }
        */

        //- 2. Seek if there is a precompiled glList for this image -------
        boolean glListIsCompiled = false;
        _JoglRGBImageRendererImageAssociation item = null;

        int i;
        for ( i = 0; i < compiledImages.size(); i++ ) {
            item = compiledImages.get(i);
            if ( item.image == img ) {
                glListIsCompiled = true;
                break;
            }
        }

        //- 3. If there is no glList, create it ---------------------------
        if ( glListIsCompiled == false ) {
            //----
            item = new _JoglRGBImageRendererImageAssociation();
            item.image = img;
            item.glList = 1;
            compiledImages.add(item);

            //----
            //gl.glGenTextures(1, lists, 0);
            //item.glList=lists[0];
            //gl.glBindTexture(gl.GL_TEXTURE_2D, item.glList);

            try {
		GLProfile glprof;
                TextureData textureData;

                glprof = GLProfile.get(GLProfile.GL2);
                textureData = new TextureData(
		   glprof,
                   3, // int internalFormat (number of components)
                   x_tam, // int width
                   y_tam, // int height
                   0, // int border
                   gl.GL_RGB, // int pixelFormat
                   gl.GL_UNSIGNED_BYTE, // int pixelType
                   true, // boolean mipmap
                   false, // boolean dataIsCompressed
                   false, // boolean mustFlipVertically
                   img.getRawImageDirectBuffer(), // Buffer buffer
                   null // TextureData.Flusher flusher
                );
                item.renderer = TextureIO.newTexture(textureData);
                item.glList = item.renderer.getTextureObject(gl);
            }
            catch ( Exception e ) {
                System.err.println(e);
            }
            /*
            //glu.gluBuild2DMipmaps(gl.GL_TEXTURE_2D, 3, x_tam, y_tam, gl.GL_RGB,
            //                  gl.GL_UNSIGNED_BYTE, img.getRawImageDirectBuffer());
            gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, 3, x_tam, y_tam, 0, gl.GL_RGB,
                            gl.GL_UNSIGNED_BYTE, img.getRawImageDirectBuffer());
            */
        }

        //- 4. Use the image's glList -------------------------------------
        //if ( glListIsCompiled == false ) {
            if ( item == null ) {
                VSDK.reportMessage(null, VSDK.WARNING, "JoglRGBImageRenderer.activate", "null item");
                return -1;
            }
            if ( item.renderer == null ) {
                VSDK.reportMessage(null, VSDK.WARNING, "JoglRGBImageRenderer.activate", "null item renderer");
                return -1;
            }
            item.renderer.bind(gl);
            item.renderer.enable(gl);
/*
          }
          else {
            gl.glCallList(item.glList);
        }
*/
        /*
        if ( item != null ) {
            gl.glBindTexture(gl.GL_TEXTURE_2D, item.glList);
        }
        */
        return item.glList;
    }

    public static int activate(GL2 gl, RGBImage img)
    {
        int list = activateBase(gl, img);

        //-----------------------------------------------------------------
        return list;
    }

    public static int activateAsNormalMap(GL2 gl, RGBImage img, RendererConfiguration quality)
    {
        int list = -1;
        //-----------------------------------------------------------------
        return list;
    }

    public static void deactivate(GL2 gl, RGBImage img)
    {
        _JoglRGBImageRendererImageAssociation item = null;

        try {
            int i;
            for ( i = 0; i < compiledImages.size(); i++ ) {
                item = compiledImages.get(i);
                if ( item.image == img ) {
                    item.renderer.disable(gl);
                    return;
                }
            }
        }
        catch ( Exception e ) {
            VSDK.reportMessage(null, VSDK.WARNING, "JoglRGBImageRenderer.deactivate", "Error unloading image.");

	}
    }

    public static void unload(GL2 gl, RGBImage img)
    {
        _JoglRGBImageRendererImageAssociation item = null;

        try {
            int i;
            for ( i = 0; i < compiledImages.size(); i++ ) {
                item = compiledImages.get(i);
                if ( item.image == img ) {
                    item.renderer.disable(gl);
                    //item.renderer.dispose();
                    item.renderer = null;
                    compiledImages.remove(i);
                    return;
                }
            }
        }
        catch ( Exception e ) {
            VSDK.reportMessage(null, VSDK.WARNING, "JoglRGBImageRenderer.unload", "Error unloading image.");

	}
    }

    public static void draw(GL2 gl, RGBImage img)
    {
        gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1);
        gl.glRasterPos2f(-1, -1);
        gl.glDrawPixels(img.getXSize(), img.getYSize(),
                        gl.GL_RGB, gl.GL_UNSIGNED_BYTE,
                        img.getRawImageDirectBuffer());
    }

    public static ByteBuffer importJOGLimage(GL2 gl) {
        int[] view= new int[4];
        //IntBuffer vpBuffer = BufferUtils.newIntBuffer(16);
        gl.glGetIntegerv(gl.GL_VIEWPORT, view,0);
        int width = view[2], height = view[3];

        ByteBuffer bb = ByteBuffer.allocateDirect(3 * width * height);
        gl.glReadBuffer(gl.GL_FRONT_LEFT);
        gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1);
        gl.glReadPixels( -1, -1, width, height, gl.GL_RGB, gl.GL_UNSIGNED_BYTE,
                        bb);
        gl.glFlush();
        return bb;
    }

    public static void getImageJOGL(GL2 gl, RGBImage image) {
        int[] view= new int[4];
        gl.glGetIntegerv(gl.GL_VIEWPORT, view,0);
        int width = view[2], height = view[3];

        image.init(width, height);

        // TODO: Check if this can be done without duplication!
        ByteBuffer bb = importJOGLimage(gl).duplicate();

        int pos = 0;

        for (int y =image.getYSize()-1; y >=0; y--) {
            for (int x = 0; x < image.getXSize(); x++) {
                image.putPixel(x,y, bb.get(pos), bb.get(pos + 1),
                               bb.get(pos + 2));
                pos += 3;
            }
        }
    }

    public static RGBImage getImageJOGL(GL2 gl) {
        RGBImage image = new RGBImage();

        getImageJOGL(gl, image);
        return image;
    }

}

//===========================================================================
//= EOF                                                                     =
//===========================================================================


text:
// Copyright 2012 Henrik Feldt
//
// 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.

using MassTransit.NLogIntegration.Logging;
using NUnit.Framework;

namespace MassTransit.Transports.AzureServiceBus.Tests
{
	[SetUpFixture]
	public class NLogContextSetup
	{
		[SetUp]
		public void SetUpLogging()
		{
			Logging.Logger.UseLogger(new NLogLogger());
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
#pragma comment(lib, "DbgHelp.lib")

#ifndef PROCESSOR_ARCHITECTURE_ARM64
#define PROCESSOR_ARCHITECTURE_ARM64 12
#endif

#ifndef PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64
#define PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 13
#endif
#ifndef PROCESSOR_ARCHITECTURE_IA32_ON_ARM64
#define PROCESSOR_ARCHITECTURE_IA32_ON_ARM64 14
#endif

#ifndef IMAGE_FILE_MACHINE_TARGET_HOST
#define IMAGE_FILE_MACHINE_TARGET_HOST                                         \
  0x0001 // Useful for indicating we want to interact with the host and not a
         // WoW guest.
#endif

/// #define PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64   13
#ifndef IMAGE_FILE_MACHINE_ARM64
//// IMAGE_FILE_MACHINE_ARM64 is Windows
#define IMAGE_FILE_MACHINE_ARM64 0xAA64 // ARM64 Little-Endian
#endif

#ifndef IMAGE_FILE_MACHINE_RISCV32
#define IMAGE_FILE_MACHINE_RISCV32 0x5032
#endif
#ifndef IMAGE_FILE_MACHINE_RISCV64
#define IMAGE_FILE_MACHINE_RISCV64 0x5064
#endif
#ifndef IMAGE_FILE_MACHINE_RISCV128
#define IMAGE_FILE_MACHINE_RISCV128 0x5128
#endif

#ifndef IMAGE_FILE_MACHINE_CHPE_X86
#define IMAGE_FILE_MACHINE_CHPE_X86 0x3A64 /// defined in ntimage.h
#endif

#ifndef IMAGE_SUBSYSTEM_XBOX_CODE_CATALOG
#define IMAGE_SUBSYSTEM_XBOX_CODE_CATALOG 17 // XBOX Code Catalog
#endif

typedef enum ReplacesGeneralNumericDefines {
// Directory entry macro for CLR data.
#ifndef IMAGE_DIRECTORY_ENTRY_COMHEADER
  IMAGE_DIRECTORY_ENTRY_COMHEADER = 14,
#endif // IMAGE_DIRECTORY_ENTRY_COMHEADER
} ReplacesGeneralNumericDefines;
#define STORAGE_MAGIC_SIG 0x424A5342 // BSJB

#pragma pack(1)
struct STORAGESIGNATURE {
  ULONG Signature;     // Magic signature for physical metadata : 0x424A5342.
  USHORT MajorVersion; // Major version, 1 (ignore on read)
  USHORT MinorVersion; // Minor version, 0 (ignore on read)
  ULONG ExtraData;     // offset to next structure of information
  ULONG Length;        // Length of version string in bytes
};
#pragma pack()

namespace pecoff {
struct key_value_t {
  uint32_t index;
  const wchar_t *value;
};

std::wstring Machine(uint32_t index) {
  // https://docs.microsoft.com/en-us/windows/desktop/Debug/pe-format#machine-types
  const key_value_t machines[] = {
      {IMAGE_FILE_MACHINE_UNKNOWN, L"UNKNOWN"},
      {IMAGE_FILE_MACHINE_TARGET_HOST, L"WoW Gest"},
      {IMAGE_FILE_MACHINE_I386, L"Intel 386"},
      {IMAGE_FILE_MACHINE_R3000, L"MIPS little-endian, 0x160 big-endian"},
      {IMAGE_FILE_MACHINE_R4000, L"MIPS little-endian"},
      {IMAGE_FILE_MACHINE_R10000, L"MIPS little-endian"},
      {IMAGE_FILE_MACHINE_WCEMIPSV2, L"MIPS little-endian WCE v2"},
      {IMAGE_FILE_MACHINE_ALPHA, L"Alpha_AXP"},
      {IMAGE_FILE_MACHINE_SH3, L"Hitachi SH3 "},
      {IMAGE_FILE_MACHINE_SH3DSP, L"Hitachi SH3 DSP"},
      {IMAGE_FILE_MACHINE_SH3E, L"Hitachi SH3E"},
      {IMAGE_FILE_MACHINE_SH4, L"Hitachi SH4"},
      {IMAGE_FILE_MACHINE_SH5, L"Hitachi SH5"},
      {IMAGE_FILE_MACHINE_ARM, L"ARM Little-Endian"},
      {IMAGE_FILE_MACHINE_THUMB, L"ARM Thumb/Thumb-2 Little-Endian"},
      {IMAGE_FILE_MACHINE_ARMNT, L"ARM Thumb-2 Little-Endian"},
      {IMAGE_FILE_MACHINE_AM33, L"Matsushita AM33 "},
      {IMAGE_FILE_MACHINE_POWERPC, L"Power PC little endian"},
      {IMAGE_FILE_MACHINE_POWERPCFP, L"Power PC with floating point support "},
      {IMAGE_FILE_MACHINE_IA64, L"Intel Itanium"},
      {IMAGE_FILE_MACHINE_MIPS16, L"MIPS"},
      {IMAGE_FILE_MACHINE_ALPHA64, L"ALPHA64"},
      {IMAGE_FILE_MACHINE_MIPSFPU, L"MIPS with FPU"},
      {IMAGE_FILE_MACHINE_MIPSFPU16, L"MIPS16 with FPU"},
      {IMAGE_FILE_MACHINE_TRICORE, L"Infineon"},
      {IMAGE_FILE_MACHINE_CEF, L"IMAGE_FILE_MACHINE_CEF"},
      {IMAGE_FILE_MACHINE_EBC, L"EFI Byte Code"},
      {IMAGE_FILE_MACHINE_AMD64, L"AMD64 (K8)"},
      {IMAGE_FILE_MACHINE_M32R, L"Mitsubishi M32R little endian "},
      {IMAGE_FILE_MACHINE_ARM64, L"ARM64 Little-Endian"},
      {IMAGE_FILE_MACHINE_CEE, L"IMAGE_FILE_MACHINE_CEE"},
      {IMAGE_FILE_MACHINE_CHPE_X86, L"Hybrid PE"},
      {IMAGE_FILE_MACHINE_RISCV32, L"RISC-V 32-bit"},
      {IMAGE_FILE_MACHINE_RISCV64, L"RISC-V 64-bit"},
      {IMAGE_FILE_MACHINE_RISCV128, L"RISC-V 128-bit"}
      //
  };
  for (const auto &kv : machines) {
    if (kv.index == index) {
      return kv.value;
    }
  }
  return L"UNKNOWN";
}
// https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_image_file_header
std::vector<std::wstring> Characteristics(uint32_t index,
                                          uint32_t dllindex = 0) {
  std::vector<std::wstring> csv;
  const key_value_t cs[] = {
      {IMAGE_FILE_RELOCS_STRIPPED, L"Relocation info stripped"},
      // Relocation info stripped from file.
      {IMAGE_FILE_EXECUTABLE_IMAGE, L"Executable"},
      // File is executable  (i.e. no unresolved external references).
      {IMAGE_FILE_LINE_NUMS_STRIPPED, L"PE line numbers stripped"},
      // Line nunbers stripped from file.
      {IMAGE_FILE_LOCAL_SYMS_STRIPPED, L"Symbol stripped"},
      // Local symbols stripped from file.
      {IMAGE_FILE_AGGRESIVE_WS_TRIM, L"Aggressively trim the working set"},
      // Aggressively trim working set
      {IMAGE_FILE_LARGE_ADDRESS_AWARE, L"Large address aware"},
      // App can handle >2gb addresses
      {IMAGE_FILE_BYTES_REVERSED_LO, L"obsolete"},
      // Bytes of machine word are reversed.
      {IMAGE_FILE_32BIT_MACHINE, L"Support 32-bit words"},
      // 32 bit word machine.
      {IMAGE_FILE_DEBUG_STRIPPED, L"Debug info stripped"},
      // Debugging info stripped from file in .DBG file
      {IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, L"Removable run from swap"},
      // If Image is on removable media, copy and run from the swap file.
      {IMAGE_FILE_NET_RUN_FROM_SWAP, L"Net run from swap"},
      // If Image is on Net, copy and run from the swap file.
      {IMAGE_FILE_SYSTEM, L"System"},
      // System File.
      {IMAGE_FILE_DLL, L"Dynamic Link Library"},
      // File is a DLL.
      {IMAGE_FILE_UP_SYSTEM_ONLY, L"Uni-processor only"},
      // File should only be run on a UP machine
      {IMAGE_FILE_BYTES_REVERSED_HI, L"obsolete"}
      // Bytes of machine word are reversed.
  };
  // USHORT  DllCharacteristics;
  const key_value_t dcs[] = {
      {IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA, L"High entropy VA"},
      {IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE, L"Dynamic base"},
      {IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY, L"Force integrity check"},
      {IMAGE_DLLCHARACTERISTICS_NX_COMPAT, L"NX compatible"},
      {IMAGE_DLLCHARACTERISTICS_NO_ISOLATION, L"No isolation"},
      {IMAGE_DLLCHARACTERISTICS_NO_SEH, L"No SEH"},
      {IMAGE_DLLCHARACTERISTICS_NO_BIND, L"Do not bind"},
      {IMAGE_DLLCHARACTERISTICS_APPCONTAINER, L"AppContainer"},
      {IMAGE_DLLCHARACTERISTICS_WDM_DRIVER, L"WDM driver"},
      {IMAGE_DLLCHARACTERISTICS_GUARD_CF, L"Control Flow Guard"},
      {IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE, L"Terminal server aware"}
      //
  };
  for (const auto &kv : cs) {
    if ((kv.index & index) != 0) {
      csv.push_back(kv.value);
    }
  }
  for (const auto &kv : dcs) {
    if ((kv.index & dllindex) != 0) {
      csv.push_back(kv.value);
    }
  }
  return csv;
}

std::wstring Subsystem(uint32_t index) {
  const key_value_t subs[] = {
      {IMAGE_SUBSYSTEM_UNKNOWN, L"UNKNOWN"},
      {IMAGE_SUBSYSTEM_NATIVE, L"Device drivers and native Windows processes "},
      {IMAGE_SUBSYSTEM_WINDOWS_GUI, L"Windows GUI"},
      {IMAGE_SUBSYSTEM_WINDOWS_CUI, L"Windows CUI"},
      {IMAGE_SUBSYSTEM_OS2_CUI, L"OS/2  character subsytem"},
      {IMAGE_SUBSYSTEM_POSIX_CUI, L"Posix character subsystem"},
      {IMAGE_SUBSYSTEM_NATIVE_WINDOWS, L"Native Win9x driver"},
      {IMAGE_SUBSYSTEM_WINDOWS_CE_GUI, L"Windows CE"},
      {IMAGE_SUBSYSTEM_EFI_APPLICATION, L"EFI Application"},
      {IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, L"EFI Boot Service Driver"},
      {IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER, L"EFI Runtime Driver"},
      {IMAGE_SUBSYSTEM_EFI_ROM, L"EFI ROM image"},
      {IMAGE_SUBSYSTEM_XBOX, L"Xbox system"},
      {IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION, L"Windows Boot Application"},
      {IMAGE_SUBSYSTEM_XBOX_CODE_CATALOG, L"XBOX Code Catalog"}
      //
  };
  for (const auto &kv : subs) {
    if (kv.index == index) {
      return kv.value;
    }
  }
  return L"UNKNOWN";
}

std::wstring fromutf8(std::string_view sv) {
  auto sz =
      MultiByteToWideChar(CP_UTF8, 0, sv.data(), (int)sv.size(), nullptr, 0);
  std::wstring output;
  output.resize(sz);
  // C++17 string::data() has non const function
  MultiByteToWideChar(CP_UTF8, 0, sv.data(), (int)sv.size(), output.data(), sz);
  return output;
}

std::wstring fromascii(std::string_view sv) {
  auto sz =
      MultiByteToWideChar(CP_ACP, 0, sv.data(), (int)sv.size(), nullptr, 0);
  std::wstring output;
  output.resize(sz);
  MultiByteToWideChar(CP_ACP, 0, sv.data(), (int)sv.size(), output.data(), sz);
  return output;
}

inline std::wstring DllName(memview mv, LPVOID nh, ULONG nva) {
  auto va =
      ImageRvaToVa((PIMAGE_NT_HEADERS)nh, (LPVOID)mv.data(), nva, nullptr);
  if (va == nullptr) {
    return L"";
  }
  std::string name;
  name.reserve(256);
  auto dn = reinterpret_cast<char *>(va);
  auto end = mv.data() + mv.size();
  for (auto it = dn; it < end && *it != 0; it++) {
    name.push_back(*it);
  }
  return fromascii(name);
}

inline std::wstring ClrMessage(memview mv, LPVOID nh, ULONG clrva) {
  auto va =
      ImageRvaToVa((PIMAGE_NT_HEADERS)nh, (LPVOID)mv.data(), clrva, nullptr);
  auto end = mv.data() + mv.size();
  if (va == nullptr || (char *)va + sizeof(IMAGE_COR20_HEADER) > end) {
    return L"";
  }
  auto clrh = reinterpret_cast<PIMAGE_COR20_HEADER>(va);
  auto va2 = ImageRvaToVa((PIMAGE_NT_HEADERS)nh, (LPVOID)mv.data(),
                          clrh->MetaData.VirtualAddress, nullptr);
  if (va2 == nullptr || (const char *)va2 + sizeof(STORAGESIGNATURE) > end) {
    return L"";
  }
  auto clrmsg = reinterpret_cast<const STORAGESIGNATURE *>(va2);
  if ((const char *)clrmsg + clrmsg->Length > end) {
    return L"";
  }
  return fromutf8(std::string_view(
      (const char *)clrmsg + sizeof(STORAGESIGNATURE), clrmsg->Length));
}

template <typename NtHeaderT>
std::optional<pe_minutiae_t> pecoff_dump(memview mv, NtHeaderT *nh,
                                         base::error_code &ec) {
  pe_minutiae_t pm;
  pm.machine = Machine(nh->FileHeader.Machine);
  pm.characteristics = Characteristics(nh->FileHeader.Characteristics,
                                       nh->OptionalHeader.DllCharacteristics);
  pm.osver = {nh->OptionalHeader.MajorOperatingSystemVersion,
              nh->OptionalHeader.MinorOperatingSystemVersion};
  pm.subsystem = Subsystem(nh->OptionalHeader.Subsystem);
  pm.linkver = {nh->OptionalHeader.MajorLinkerVersion,
                nh->OptionalHeader.MinorLinkerVersion};
  pm.imagever = {nh->OptionalHeader.MajorImageVersion,
                 nh->OptionalHeader.MinorImageVersion};
  pm.isdll = ((nh->FileHeader.Characteristics & IMAGE_FILE_DLL) != 0);

  // https://docs.microsoft.com/zh-cn/windows/desktop/api/winnt/ns-winnt-_image_data_directory
  auto clre =
      &(nh->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COMHEADER]);
  auto end = mv.data() + mv.size();
  if (clre->Size == sizeof(IMAGE_COR20_HEADER)) {
    // Exists IMAGE_COR20_HEADER
    pm.clrmsg = ClrMessage(mv, (PVOID)nh, clre->VirtualAddress);
  }
  auto import_ =
      &(nh->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]);
  if (import_->Size == 0) {
    return std::make_optional<>(pm);
  }
  auto va = ImageRvaToVa((PIMAGE_NT_HEADERS)nh, (PVOID)mv.data(),
                         import_->VirtualAddress, nullptr);
  if (va == nullptr || (const char *)va + import_->Size >= end) {
    return std::make_optional<>(pm);
  }
  auto imdes = reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>(va);
  while (imdes->Name != 0) {
    //
    // ASCIIZ
    auto dnw = DllName(mv, (LPVOID)nh, imdes->Name);
    if (!dnw.empty()) {
      pm.depends.push_back(dnw);
    }
    imdes++;
  }
  return std::make_optional<pe_minutiae_t>(std::move(pm));
}

std::optional<pe_minutiae_t> inquisitive_pecoff(std::wstring_view sv,
                                                base::error_code &ec) {

  mapview mv;
  ec = mv.mapfile(sv, sizeof(IMAGE_DOS_HEADER) + sizeof(IMAGE_NT_HEADERS32));
  if (ec) {
    return std::nullopt;
  }
  auto h = mv.cast<IMAGE_DOS_HEADER>(0);
  if (h == nullptr) {
    ec = base::make_error_code(L"file size too small, cast error");
    return std::nullopt;
  }
  // PE/PE+ lIMAGE_NT_HEADERS32 ayout
  auto nh = mv.cast<IMAGE_NT_HEADERS32>(h->e_lfanew);
  if (nh == nullptr) {
    ec = base::make_error_code(L"file size too small, cast NT header error");
    return std::nullopt;
  }
  switch (nh->OptionalHeader.Magic) {
  case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
    return pecoff_dump(mv.subview(0), (PIMAGE_NT_HEADERS64)nh, ec);
  case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
    return pecoff_dump(mv.subview(0), (PIMAGE_NT_HEADERS32)nh, ec);
  case IMAGE_ROM_OPTIONAL_HDR_MAGIC: {
    // ROM
  } break;
  default:
    break;
  }
  return std::nullopt;
}
} // namespace pecoff


text:
using System;
using System.Web.Mvc;
using BaselineSolution.Framework.Infrastructure.Attributes;

namespace BaselineSolution.WebApp.Components.Models.SelectLists
{
    public interface IOptionsBuilder<out TOption>
    {
        /// <summary>
        ///     Returns the select list with one or more options preselected where the option value is equal to the property value.
        /// </summary>
        /// <param name="optionValueFunction">The function that takes an <typeparamref name="TOption"/> and returns the value that should be used for the option tag</param>
        /// <param name="optionTextFunction">The function that takes an <typeparamref name="TOption"/> and returns the text that should be used for the option tag</param>
        /// <param name="optionHtmlAttributesFunction">The function that takes an <typeparamref name="TOption"/> and returns the html attributes that should be set on the option tag</param>
        /// <returns>The select list with one or more options preselected where the option value is equal to the property value.</returns>
        [NotNull]
        MvcHtmlString Options([NotNull] Func<TOption, string> optionValueFunction,
                              [NotNull] Func<TOption, string> optionTextFunction,
                              [CanBeNull] Func<TOption, object> optionHtmlAttributesFunction);

        /// <summary>
        ///     Returns the select list with one or more options preselected where the option value is equal to the property value.
        /// </summary>
        /// <param name="optionValueFunction">The function that takes an <typeparamref name="TOption"/> and returns the value that should be used for the option tag</param>
        /// <param name="optionTextFunction">The function that takes an <typeparamref name="TOption"/> and returns the text that should be used for the option tag</param>
        /// <returns>The select list with one or more options preselected where the option value is equal to the property value.</returns>
        [NotNull]
        MvcHtmlString Options([NotNull] Func<TOption, string> optionValueFunction,
                              [NotNull] Func<TOption, string> optionTextFunction);

        /// <summary>
        ///     Returns the select list with one or more options preselected where the option value is equal to the property value.
        /// </summary>
        /// <param name="optionValueFunction">The function that takes an <typeparamref name="TOption"/> and returns the value that should be used for the option tag</param>
        /// <param name="optionTextFunction">The function that takes an <typeparamref name="TOption"/> and returns the text that should be used for the option tag</param>
        /// <param name="optionHtmlAttributesFunction">The function that takes an <typeparamref name="TOption"/> and returns the html attributes that should be set on the option tag</param>
        /// <returns>The select list with one or more options preselected where the option value is equal to the property value.</returns>
        [NotNull]
        MvcHtmlString Options([NotNull] Func<TOption, int> optionValueFunction,
                              [NotNull] Func<TOption, string> optionTextFunction,
                              [CanBeNull] Func<TOption, object> optionHtmlAttributesFunction);

        /// <summary>
        ///     Returns the select list with one or more options preselected where the option value is equal to the property value.
        /// </summary>
        /// <param name="optionValueFunction">The function that takes an <typeparamref name="TOption"/> and returns the value that should be used for the option tag</param>
        /// <param name="optionTextFunction">The function that takes an <typeparamref name="TOption"/> and returns the text that should be used for the option tag</param>
        /// <returns>The select list with one or more options preselected where the option value is equal to the property value.</returns>
        [NotNull]
        MvcHtmlString Options([NotNull] Func<TOption, int> optionValueFunction,
                              [NotNull] Func<TOption, string> optionTextFunction);
    }
}


text:
<?php

namespace Tests\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class HomeTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertEquals('Home page :D', $crawler->text());
    }

    public function testNonAcceptedHttpMethod()
    {
        $client = static::createClient();
        $crawler = $client->request('POST', '/');

        $this->assertEquals(405, $client->getResponse()->getStatusCode());
        $this->assertContains('No route found for "POST /"', $crawler->text());
        $this->assertContains('Method Not Allowed (Allow: GET, HEAD)', $crawler->text());
    }
}


text:
namespace aura {

namespace {

const char* kRootWindowHostWinKey = "__AURA_REMOTE_ROOT_WINDOW_HOST_WIN__";

// Sets the keystate for the virtual key passed in to down or up.
void SetKeyState(uint8* key_states, bool key_down, uint32 virtual_key_code) {
  DCHECK(key_states);

  if (key_down)
    key_states[virtual_key_code] |= 0x80;
  else
    key_states[virtual_key_code] &= 0x7F;
}

// Sets the keyboard states for the Shift/Control/Alt/Caps lock keys.
void SetVirtualKeyStates(uint32 flags) {
  uint8 keyboard_state[256] = {0};
  ::GetKeyboardState(keyboard_state);

  SetKeyState(keyboard_state, !!(flags & ui::EF_SHIFT_DOWN), VK_SHIFT);
  SetKeyState(keyboard_state, !!(flags & ui::EF_CONTROL_DOWN), VK_CONTROL);
  SetKeyState(keyboard_state, !!(flags & ui::EF_ALT_DOWN), VK_MENU);
  SetKeyState(keyboard_state, !!(flags & ui::EF_CAPS_LOCK_DOWN), VK_CAPITAL);

  ::SetKeyboardState(keyboard_state);
}

}  // namespace

void HandleOpenFile(const base::string16& title,
                    const base::FilePath& default_path,
                    const base::string16& filter,
                    const OpenFileCompletion& on_success,
                    const FileSelectionCanceled& on_failure) {
  DCHECK(aura::RemoteRootWindowHostWin::Instance());
  aura::RemoteRootWindowHostWin::Instance()->HandleOpenFile(title,
                                                            default_path,
                                                            filter,
                                                            on_success,
                                                            on_failure);
}

void HandleOpenMultipleFiles(const base::string16& title,
                             const base::FilePath& default_path,
                             const base::string16& filter,
                             const OpenMultipleFilesCompletion& on_success,
                             const FileSelectionCanceled& on_failure) {
  DCHECK(aura::RemoteRootWindowHostWin::Instance());
  aura::RemoteRootWindowHostWin::Instance()->HandleOpenMultipleFiles(
      title,
      default_path,
      filter,
      on_success,
      on_failure);
}

void HandleSaveFile(const base::string16& title,
                    const base::FilePath& default_path,
                    const base::string16& filter,
                    int filter_index,
                    const base::string16& default_extension,
                    const SaveFileCompletion& on_success,
                    const FileSelectionCanceled& on_failure) {
  DCHECK(aura::RemoteRootWindowHostWin::Instance());
  aura::RemoteRootWindowHostWin::Instance()->HandleSaveFile(title,
                                                            default_path,
                                                            filter,
                                                            filter_index,
                                                            default_extension,
                                                            on_success,
                                                            on_failure);
}

void HandleSelectFolder(const base::string16& title,
                        const SelectFolderCompletion& on_success,
                        const FileSelectionCanceled& on_failure) {
  DCHECK(aura::RemoteRootWindowHostWin::Instance());
  aura::RemoteRootWindowHostWin::Instance()->HandleSelectFolder(title,
                                                                on_success,
                                                                on_failure);
}

RemoteRootWindowHostWin* g_instance = NULL;

RemoteRootWindowHostWin* RemoteRootWindowHostWin::Instance() {
  if (g_instance)
    return g_instance;
  return Create(gfx::Rect());
}

RemoteRootWindowHostWin* RemoteRootWindowHostWin::Create(
    const gfx::Rect& bounds) {
  g_instance = g_instance ? g_instance : new RemoteRootWindowHostWin(bounds);
  return g_instance;
}

RemoteRootWindowHostWin::RemoteRootWindowHostWin(const gfx::Rect& bounds)
    : remote_window_(NULL),
      delegate_(NULL),
      host_(NULL),
      ignore_mouse_moves_until_set_cursor_ack_(false) {
  prop_.reset(new ui::ViewProp(NULL, kRootWindowHostWinKey, this));
}

RemoteRootWindowHostWin::~RemoteRootWindowHostWin() {
  g_instance = NULL;
}

void RemoteRootWindowHostWin::Connected(IPC::Sender* host, HWND remote_window) {
  CHECK(host_ == NULL);
  host_ = host;
  remote_window_ = remote_window;
}

void RemoteRootWindowHostWin::Disconnected() {
  CHECK(host_ != NULL);
  host_ = NULL;
  remote_window_ = NULL;
}

bool RemoteRootWindowHostWin::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(RemoteRootWindowHostWin, message)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_MouseMoved, OnMouseMoved)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_MouseButton, OnMouseButton)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_KeyDown, OnKeyDown)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_KeyUp, OnKeyUp)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_Character, OnChar)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_VisibilityChanged,
                        OnVisibilityChanged)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_TouchDown,
                        OnTouchDown)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_TouchUp,
                        OnTouchUp)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_TouchMoved,
                        OnTouchMoved)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_FileSaveAsDone,
                        OnFileSaveAsDone)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_FileOpenDone,
                        OnFileOpenDone)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_MultiFileOpenDone,
                        OnMultiFileOpenDone)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_SelectFolderDone,
                        OnSelectFolderDone)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_SetCursorPosAck,
                        OnSetCursorPosAck)
    IPC_MESSAGE_HANDLER(MetroViewerHostMsg_WindowSizeChanged,
                        OnWindowSizeChanged)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void RemoteRootWindowHostWin::HandleOpenURLOnDesktop(
    const base::FilePath& shortcut,
    const base::string16& url) {
  if (!host_)
    return;
  host_->Send(new MetroViewerHostMsg_OpenURLOnDesktop(shortcut, url));
}

void RemoteRootWindowHostWin::HandleOpenFile(
    const base::string16& title,
    const base::FilePath& default_path,
    const base::string16& filter,
    const OpenFileCompletion& on_success,
    const FileSelectionCanceled& on_failure) {
  if (!host_)
    return;

  // Can only have one of these operations in flight.
  DCHECK(file_open_completion_callback_.is_null());
  DCHECK(failure_callback_.is_null());

  file_open_completion_callback_ = on_success;
  failure_callback_ = on_failure;

  host_->Send(new MetroViewerHostMsg_DisplayFileOpen(title,
                                                     filter,
                                                     default_path,
                                                     false));
}

void RemoteRootWindowHostWin::HandleOpenMultipleFiles(
    const base::string16& title,
    const base::FilePath& default_path,
    const base::string16& filter,
    const OpenMultipleFilesCompletion& on_success,
    const FileSelectionCanceled& on_failure) {
  if (!host_)
    return;

  // Can only have one of these operations in flight.
  DCHECK(multi_file_open_completion_callback_.is_null());
  DCHECK(failure_callback_.is_null());
  multi_file_open_completion_callback_ = on_success;
  failure_callback_ = on_failure;

  host_->Send(new MetroViewerHostMsg_DisplayFileOpen(title,
                                                     filter,
                                                     default_path,
                                                     true));
}

void RemoteRootWindowHostWin::HandleSaveFile(
    const base::string16& title,
    const base::FilePath& default_path,
    const base::string16& filter,
    int filter_index,
    const base::string16& default_extension,
    const SaveFileCompletion& on_success,
    const FileSelectionCanceled& on_failure) {
  if (!host_)
    return;

  MetroViewerHostMsg_SaveAsDialogParams params;
  params.title = title;
  params.default_extension = default_extension;
  params.filter = filter;
  params.filter_index = filter_index;
  params.suggested_name = default_path;

  // Can only have one of these operations in flight.
  DCHECK(file_saveas_completion_callback_.is_null());
  DCHECK(failure_callback_.is_null());
  file_saveas_completion_callback_ = on_success;
  failure_callback_ = on_failure;

  host_->Send(new MetroViewerHostMsg_DisplayFileSaveAs(params));
}

void RemoteRootWindowHostWin::HandleSelectFolder(
    const base::string16& title,
    const SelectFolderCompletion& on_success,
    const FileSelectionCanceled& on_failure) {
  if (!host_)
    return;

  // Can only have one of these operations in flight.
  DCHECK(select_folder_completion_callback_.is_null());
  DCHECK(failure_callback_.is_null());
  select_folder_completion_callback_ = on_success;
  failure_callback_ = on_failure;

  host_->Send(new MetroViewerHostMsg_DisplaySelectFolder(title));
}

Window* RemoteRootWindowHostWin::GetAshWindow() {
  return GetRootWindow();
}

void RemoteRootWindowHostWin::SetDelegate(RootWindowHostDelegate* delegate) {
  delegate_ = delegate;
}

RootWindow* RemoteRootWindowHostWin::GetRootWindow() {
  return delegate_->AsRootWindow();
}

gfx::AcceleratedWidget RemoteRootWindowHostWin::GetAcceleratedWidget() {
  if (remote_window_)
    return remote_window_;
  // Getting here should only happen for ash_unittests.exe and related code.
  return ::GetDesktopWindow();
}

void RemoteRootWindowHostWin::Show() {
}

void RemoteRootWindowHostWin::Hide() {
  NOTIMPLEMENTED();
}

void RemoteRootWindowHostWin::ToggleFullScreen() {
}

gfx::Rect RemoteRootWindowHostWin::GetBounds() const {
  gfx::Rect r(gfx::Point(0, 0), aura::RootWindowHost::GetNativeScreenSize());
  return r;
}

void RemoteRootWindowHostWin::SetBounds(const gfx::Rect& bounds) {
  delegate_->OnHostResized(bounds.size());
}

gfx::Insets RemoteRootWindowHostWin::GetInsets() const {
  return gfx::Insets();
}

void RemoteRootWindowHostWin::SetInsets(const gfx::Insets& insets) {
}

gfx::Point RemoteRootWindowHostWin::GetLocationOnNativeScreen() const {
  return gfx::Point(0, 0);
}

void RemoteRootWindowHostWin::SetCursor(gfx::NativeCursor native_cursor) {
  if (!host_)
    return;
  host_->Send(
      new MetroViewerHostMsg_SetCursor(uint64(native_cursor.platform())));
}

void RemoteRootWindowHostWin::SetCapture() {
}

void RemoteRootWindowHostWin::ReleaseCapture() {
}

bool RemoteRootWindowHostWin::QueryMouseLocation(gfx::Point* location_return) {
  aura::client::CursorClient* cursor_client =
      aura::client::GetCursorClient(GetRootWindow());
  if (cursor_client && !cursor_client->IsMouseEventsEnabled()) {
    *location_return = gfx::Point(0, 0);
    return false;
  }
  POINT pt;
  GetCursorPos(&pt);
  *location_return =
      gfx::Point(static_cast<int>(pt.x), static_cast<int>(pt.y));
  return true;
}

bool RemoteRootWindowHostWin::ConfineCursorToRootWindow() {
  return true;
}

void RemoteRootWindowHostWin::UnConfineCursor() {
}

void RemoteRootWindowHostWin::OnCursorVisibilityChanged(bool show) {
  NOTIMPLEMENTED();
}

void RemoteRootWindowHostWin::MoveCursorTo(const gfx::Point& location) {
  VLOG(1) << "In MoveCursorTo: " << location.x() << ", " << location.y();
  if (!host_)
    return;

  // This function can be called in cases like when the mouse cursor is
  // restricted within a viewport (For e.g. LockCursor) which assumes that
  // subsequent mouse moves would be received starting with the new cursor
  // coordinates. This is a challenge for Windows ASH for the reasons
  // outlined below.
  // Other cases which don't expect this behavior should continue to work
  // without issues.

  // The mouse events are received by the viewer process and sent to the
  // browser. If we invoke the SetCursor API here we continue to receive
  // mouse messages from the viewer which were posted before the SetCursor
  // API executes which messes up the state in the browser. To workaround
  // this we invoke the SetCursor API in the viewer process and ignore
  // mouse messages until we received an ACK from the viewer indicating that
  // the SetCursor operation completed.
  ignore_mouse_moves_until_set_cursor_ack_ = true;
  VLOG(1) << "In MoveCursorTo. Sending IPC";
  host_->Send(new MetroViewerHostMsg_SetCursorPos(location.x(), location.y()));
}

void RemoteRootWindowHostWin::SetFocusWhenShown(bool focus_when_shown) {
  NOTIMPLEMENTED();
}

void RemoteRootWindowHostWin::PostNativeEvent(
    const base::NativeEvent& native_event) {
}

void RemoteRootWindowHostWin::OnDeviceScaleFactorChanged(
    float device_scale_factor) {
  NOTIMPLEMENTED();
}

void RemoteRootWindowHostWin::PrepareForShutdown() {
}

void RemoteRootWindowHostWin::OnMouseMoved(int32 x, int32 y, int32 flags) {
  if (ignore_mouse_moves_until_set_cursor_ack_)
    return;

  gfx::Point location(x, y);
  ui::MouseEvent event(ui::ET_MOUSE_MOVED, location, location, flags);
  delegate_->OnHostMouseEvent(&event);
}

void RemoteRootWindowHostWin::OnMouseButton(
    int32 x, int32 y, int32 extra, ui::EventType type, ui::EventFlags flags) {
  gfx::Point location(x, y);
  ui::MouseEvent mouse_event(type, location, location, flags);

  if (type == ui::ET_MOUSEWHEEL) {
    ui::MouseWheelEvent wheel_event(mouse_event, 0, extra);
    delegate_->OnHostMouseEvent(&wheel_event);
  } else if (type == ui::ET_MOUSE_PRESSED) {
    // TODO(shrikant): Ideally modify code in event.cc by adding automatic
    // tracking of double clicks in synthetic MouseEvent constructor code.
    // Non-synthetic MouseEvent constructor code does automatically track
    // this. Need to use some caution while modifying synthetic constructor
    // as many tests and other code paths depend on it and apparently
    // specifically depend on non implicit tracking of previous mouse event.
    if (last_mouse_click_event_ &&
        ui::MouseEvent::IsRepeatedClickEvent(mouse_event,
                                             *last_mouse_click_event_)) {
      mouse_event.SetClickCount(2);
    } else {
      mouse_event.SetClickCount(1);
    }
    last_mouse_click_event_ .reset(new ui::MouseEvent(mouse_event));
    delegate_->OnHostMouseEvent(&mouse_event);
  } else {
    delegate_->OnHostMouseEvent(&mouse_event);
  }
}

void RemoteRootWindowHostWin::OnKeyDown(uint32 vkey,
                                        uint32 repeat_count,
                                        uint32 scan_code,
                                        uint32 flags) {
  DispatchKeyboardMessage(ui::ET_KEY_PRESSED, vkey, repeat_count, scan_code,
                          flags, false);
}

void RemoteRootWindowHostWin::OnKeyUp(uint32 vkey,
                                      uint32 repeat_count,
                                      uint32 scan_code,
                                      uint32 flags) {
  DispatchKeyboardMessage(ui::ET_KEY_RELEASED, vkey, repeat_count, scan_code,
                          flags, false);
}

void RemoteRootWindowHostWin::OnChar(uint32 key_code,
                                     uint32 repeat_count,
                                     uint32 scan_code,
                                     uint32 flags) {
  DispatchKeyboardMessage(ui::ET_KEY_PRESSED, key_code, repeat_count,
                          scan_code, flags, true);
}

void RemoteRootWindowHostWin::OnVisibilityChanged(bool visible) {
  if (visible)
    delegate_->OnHostActivated();
}

void RemoteRootWindowHostWin::OnTouchDown(int32 x,
                                          int32 y,
                                          uint64 timestamp,
                                          uint32 pointer_id) {
  ui::TouchEvent event(ui::ET_TOUCH_PRESSED,
                       gfx::Point(x, y),
                       pointer_id,
                       base::TimeDelta::FromMicroseconds(timestamp));
  delegate_->OnHostTouchEvent(&event);
}

void RemoteRootWindowHostWin::OnTouchUp(int32 x,
                                        int32 y,
                                        uint64 timestamp,
                                        uint32 pointer_id) {
  ui::TouchEvent event(ui::ET_TOUCH_RELEASED,
                       gfx::Point(x, y),
                       pointer_id,
                       base::TimeDelta::FromMicroseconds(timestamp));
  delegate_->OnHostTouchEvent(&event);
}

void RemoteRootWindowHostWin::OnTouchMoved(int32 x,
                                           int32 y,
                                           uint64 timestamp,
                                           uint32 pointer_id) {
  ui::TouchEvent event(ui::ET_TOUCH_MOVED,
                       gfx::Point(x, y),
                       pointer_id,
                       base::TimeDelta::FromMicroseconds(timestamp));
  delegate_->OnHostTouchEvent(&event);
}

void RemoteRootWindowHostWin::OnFileSaveAsDone(bool success,
                                               const base::FilePath& filename,
                                               int filter_index) {
  if (success)
    file_saveas_completion_callback_.Run(filename, filter_index, NULL);
  else
    failure_callback_.Run(NULL);
  file_saveas_completion_callback_.Reset();
  failure_callback_.Reset();
}

void RemoteRootWindowHostWin::OnFileOpenDone(bool success,
                                             const base::FilePath& filename) {
  if (success)
    file_open_completion_callback_.Run(base::FilePath(filename), 0, NULL);
  else
    failure_callback_.Run(NULL);
  file_open_completion_callback_.Reset();
  failure_callback_.Reset();
}

void RemoteRootWindowHostWin::OnMultiFileOpenDone(
    bool success,
    const std::vector<base::FilePath>& files) {
  if (success)
    multi_file_open_completion_callback_.Run(files, NULL);
  else
    failure_callback_.Run(NULL);
  multi_file_open_completion_callback_.Reset();
  failure_callback_.Reset();
}

void RemoteRootWindowHostWin::OnSelectFolderDone(
    bool success,
    const base::FilePath& folder) {
  if (success)
    select_folder_completion_callback_.Run(base::FilePath(folder), 0, NULL);
  else
    failure_callback_.Run(NULL);
  select_folder_completion_callback_.Reset();
  failure_callback_.Reset();
}

void RemoteRootWindowHostWin::OnSetCursorPosAck() {
  DCHECK(ignore_mouse_moves_until_set_cursor_ack_);
  ignore_mouse_moves_until_set_cursor_ack_ = false;
}

void RemoteRootWindowHostWin::OnWindowSizeChanged(uint32 width, uint32 height) {
  SetBounds(gfx::Rect(0, 0, width, height));
}

void RemoteRootWindowHostWin::DispatchKeyboardMessage(ui::EventType type,
                                                      uint32 vkey,
                                                      uint32 repeat_count,
                                                      uint32 scan_code,
                                                      uint32 flags,
                                                      bool is_character) {
  if (base::MessageLoop::current()->IsNested()) {
    SetVirtualKeyStates(flags);

    uint32 message = is_character ? WM_CHAR :
        (type == ui::ET_KEY_PRESSED ? WM_KEYDOWN : WM_KEYUP);
    ::PostThreadMessage(::GetCurrentThreadId(),
                        message,
                        vkey,
                        repeat_count | scan_code >> 15);
  } else {
    ui::KeyEvent event(type,
                       ui::KeyboardCodeForWindowsKeyCode(vkey),
                       flags,
                       is_character);
    delegate_->OnHostKeyEvent(&event);
  }
}

}  // namespace aura


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RaiseFault async="false" continueOnError="false" enabled="true" name="RF-Return-CORS-Headers">
    <DisplayName>RF-Return-OPTIONS-Response</DisplayName>
    <FaultRules/>
    <Properties/>
    <FaultResponse>
        <Set>
            <Headers>
                *
                origin, x-requested-with, content-type, accept, accept-Encoding, If-Modified-Since, x-fapi-auth-date, x-fapi-customer-ip-address, x-fapi-interaction-id, Authorization, x-idempotency-key, x-customer-user-agent
                3628800
                GET, PUT, POST, OPTIONS
            </Headers>
            <Payload/>
            <StatusCode>200</StatusCode>
            <ReasonPhrase>OK</ReasonPhrase>
        </Set>
    </FaultResponse>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <ShortFaultReason>false</ShortFaultReason>
</RaiseFault>


text:
package org.qi4j.api.query.grammar;

import org.qi4j.api.association.GenericAssociationInfo;
import org.qi4j.api.association.ManyAssociation;
import org.qi4j.api.composite.Composite;
import org.qi4j.api.composite.CompositeInstance;
import org.qi4j.api.association.Association;
import org.qi4j.api.association.AssociationStateHolder;
import org.qi4j.api.query.QueryExpressionException;
import org.qi4j.api.util.Classes;
import org.qi4j.functional.Function;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Member;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;

/**
* TODO
*/
public class AssociationFunction<T>
        implements Function<Composite, Association<T>>
{
    private AssociationFunction<?> traversedAssociation;
    private ManyAssociationFunction<?> traversedManyAssociation;
    private final AccessibleObject accessor;

    public AssociationFunction( AssociationFunction<?> traversedAssociation, ManyAssociationFunction<?> traversedManyAssociation, AccessibleObject accessor )
    {
        this.traversedAssociation = traversedAssociation;
        this.traversedManyAssociation = traversedManyAssociation;
        this.accessor = accessor;

        Type returnType = Classes.TYPE_OF.map( accessor );
        if( !Association.class.isAssignableFrom( Classes.RAW_CLASS.map( returnType ) ) &&
            !ManyAssociation.class.isAssignableFrom( Classes.RAW_CLASS.map( returnType ) ) )
        {
            throw new QueryExpressionException( "Unsupported association type:" + returnType );
        }
        Type associationTypeAsType = GenericAssociationInfo.getAssociationType( returnType );
        if( !( associationTypeAsType instanceof Class ) )
        {
            throw new QueryExpressionException( "Unsupported association type:" + associationTypeAsType );
        }
    }

    public AssociationFunction<?> getTraversedAssociation()
    {
        return traversedAssociation;
    }

    public ManyAssociationFunction<?> getTraversedManyAssociation()
    {
        return traversedManyAssociation;
    }

    public AccessibleObject getAccessor()
    {
        return accessor;
    }

    @Override
    public Association<T> map( Composite entity )
    {
        try
        {
            Object target = entity;
            if (traversedAssociation != null)
            {
                Association<?> association = traversedAssociation.map( entity );
                if (association == null)
                    return null;
                target = association.get();
            }
            else if (traversedManyAssociation != null)
                throw new IllegalArgumentException( "Cannot evaluate a ManyAssociation" );

            if (target == null)
                return null;

            CompositeInstance handler = (CompositeInstance) Proxy.getInvocationHandler( target );
            return ((AssociationStateHolder)handler.state()).associationFor( accessor );
        } catch( IllegalArgumentException e )
        {
            throw e;
        } catch( Throwable e )
        {
            throw new IllegalArgumentException( e );
        }
    }

    @Override
    public String toString()
    {
        if (traversedAssociation != null)
            return traversedAssociation.toString()+"."+ ((Member)accessor).getName();
        else
            return ((Member)accessor).getName();
    }
}


text:
require 'spec_helper'

describe UsersProject do
  describe "Associations" do
    it { should belong_to(:project) }
    it { should belong_to(:user) }
  end

  describe "Validation" do
    it { should validate_presence_of(:user_id) }
    it { should validate_presence_of(:project_id) }
  end

  describe "Delegate methods" do
    it { should respond_to(:user_name) }
    it { should respond_to(:user_email) }
  end
end
# == Schema Information
#
# Table name: users_projects
#
#  id             :integer         not null, primary key
#  user_id        :integer         not null
#  project_id     :integer         not null
#  created_at     :datetime
#  updated_at     :datetime
#  project_access :integer         default(0), not null
#


text:
package cn.intelvision.request.face;

import cn.intelvision.request.ZenoRequest;
import cn.intelvision.response.face.InfoGetPersonListResponse;

/**
 * Created by pc on 2016/3/16.
 */
public class InfoGetPersonListRequest extends ZenoRequest<InfoGetPersonListResponse> {
    @Override
    public String getApi() {
        return "/face/info/get_person_list";
    }
}


text:
/**
 * 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.
 */
package org.hyperledger.pbft

import java.net.InetSocketAddress

import akka.actor.ActorRef
import org.hyperledger.common.PublicKey
import org.hyperledger.network.Version
import org.hyperledger.pbft.PbftSettings.NodeConfig

import scalaz._
import Scalaz._

object ConnectionManagement {
  def empty = new ConnectionManagement(Map.empty, Map.empty)

  sealed trait Connection {
    def peer: ActorRef
  }
  case class PendingConnection(remoteAddress: InetSocketAddress, peer: ActorRef)
  case class ReplicaConnection(
    remoteAddress: InetSocketAddress,
    version: Version,
    publicKey: PublicKey,
    peer: ActorRef) extends Connection
  case class ClientConnection(
    remoteAddress: InetSocketAddress,
    version: Version,
    peer: ActorRef) extends Connection

  sealed trait ConnectionError
  case object AlreadyConnected extends ConnectionError
  case object UnknownConnection extends ConnectionError
}
case class ConnectionManagement(
  pendingConnections: Map[InetSocketAddress, ConnectionManagement.PendingConnection],
  activeConnections: Map[InetSocketAddress, ConnectionManagement.Connection]) {
  import ConnectionManagement._

  def connected(peer: ActorRef, remoteAddress: InetSocketAddress): ConnectionError \/ ConnectionManagement =
    if (pendingConnections.contains(remoteAddress))
      \/.left(AlreadyConnected)
    else
      \/.right(copy(pendingConnections = pendingConnections + (remoteAddress -> PendingConnection(remoteAddress, peer))))

  def timeout(remoteAddress: InetSocketAddress) = copy(pendingConnections = pendingConnections - remoteAddress)

  def disconnected(version: Version) = copy(activeConnections = activeConnections - version.addrFrom.address)

  def handshakeComplete(settings: PbftSettings,
    peer: ActorRef,
    remoteAddress: InetSocketAddress,
    version: Version): (ConnectionManagement, Connection) = {

    val conn = settings.otherNodes.find(_.address == version.addrFrom)
      .map(n => ReplicaConnection(remoteAddress, version, n.publicKey, peer))
      .getOrElse(ClientConnection(remoteAddress, version, peer))

    val updated = copy(
      pendingConnections = pendingConnections - remoteAddress,
      activeConnections = activeConnections + (version.addrFrom.address -> conn))

    (updated, conn)
  }
}


text:
namespace WebTemplate.Models
{
    using System;
    using System.Collections.Generic;

    public partial class tb_m_rate_visa
    {
        public int id_rate_visa { get; set; }
        public string destination { get; set; }
        public Nullable<double> visa { get; set; }
        public Nullable<System.DateTime> start_date { get; set; }
        public Nullable<System.DateTime> end_date { get; set; }
        public Nullable<bool> active_flag { get; set; }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Peucedanum capillaceum DC.

### Remarks
null


text:
if [ ! -z "$1" ]
then
   DIR=$1
   cd "$DIR"
else
   DIR=$(dirname "$0")
   echo "Download path: $DIR"
   cd "$DIR"
fi

FILENAME="./analytics-zoo_ssd-mobilenet-300x300_PASCAL_0.1.0.model"
if [ -f "$FILENAME" ]
then
   echo "$FILENAME already exists."
   exit
fi

echo "Downloading pretrained model"
wget https://sourceforge.net/projects/analytics-zoo/files/analytics-zoo-models/object-detection/analytics-zoo_ssd-mobilenet-300x300_PASCAL_0.1.0.model

echo "Finished"


text:
--TEST--
Test array_sum() function : usage variations - associative array
--FILE--
<?php
/* Prototype  : mixed array_sum(array $input)
 * Description: Returns the sum of the array entries
 * Source code: ext/standard/array.c
*/

/*
* Testing array_sum() with associative array as 'input' argument
*/

echo "*** Testing array_sum() : with associative array ***\n";

// array with numeric keys
$input = array(0 => 1, 1 => 10, 2 => 0, 3 => -2, 4 => 23.56);
echo "-- with numeric keys --\n";
var_dump( array_sum($input) );

// array with string keys
$input = array('a' => 20, "b" => 50, 'c' => 0, 'd' => -30, "e" => 100);
echo "-- with string keys --\n";
var_dump( array_sum($input) );
echo "Done"
?>
--EXPECTF--
*** Testing array_sum() : with associative array ***
-- with numeric keys --
float(32.56)
-- with string keys --
int(140)
Done


text:
package org.activiti.core.common.spring.security.test;

import static org.assertj.core.api.Assertions.assertThat;

import org.activiti.core.common.spring.security.SimpleGrantedAuthoritiesResolver;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import java.util.Collection;
import java.util.List;

public class SimpleGrantedAuthoritiesResolverTest {

    private SimpleGrantedAuthoritiesResolver subject = new SimpleGrantedAuthoritiesResolver();

    @Test
    public void testGetAuthorities() {
        // given
        // given
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("GROUP_users",
                                                                                "ROLE_admin");

        Authentication authentication = new UsernamePasswordAuthenticationToken("user",
                                                                                "password",
                                                                                authorities);

        // when
        Collection<? extends GrantedAuthority> result = subject.getAuthorities(authentication);

        // then
        assertThat(result).isNotEmpty()
                          .asList()
                          .containsAll(authorities);
    }

}


text:
using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Gms.Gcm.Iid;
using Android.Gms.Gcm;

// @PACKAGE_NAME@ will inject your own package name into the value
[assembly: UsesPermission (Android.Manifest.Permission.GetAccounts)]

namespace GCMSample
{
    [Activity (Label = "GCMSample", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        const string TAG = "GCMSAMPLE";

        TextView textToken;
        EditText textMessage;
        Button buttonToken;
        Button buttonSend;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            textToken = FindViewById<TextView> (Resource.Id.textToken);
            textMessage = FindViewById<EditText> (Resource.Id.editTextSendMsg);
            buttonToken = FindViewById<Button> (Resource.Id.buttonToken);
            buttonSend = FindViewById<Button> (Resource.Id.buttonSend);

            buttonToken.Click += async delegate {
                MyRegistrationService.Register (this);
            };

            if (MyRegistrationService.GCM_SENDER_ID == "YOUR-SENDER-ID")
                throw new Exception ("You must change MyGcmListenerService.GCM_SENDER_ID const to the value of your own Google Developer Console Project # which has Cloud Messaging For Android API enabled, and an OAUTH and Android Key setup in the Developer Console");
        }

        protected override void OnStart ()
        {
            base.OnStart ();

            MyRegistrationService.TokenRefreshed += TokenUpdated;
        }

        protected override void OnStop ()
        {
            MyRegistrationService.TokenRefreshed -= TokenUpdated;

            base.OnStop ();
        }

        void TokenUpdated (string token)
        {
            Android.Util.Log.Debug (TAG, "Got Token: {0}", token);

            RunOnUiThread (() => textToken.Text = token);
        }

        static int msgId = 0;

        bool SendUpstreamMessage (string msg)
        {
            var gcm = GoogleCloudMessaging.GetInstance (this);

            try {
                var data = new Bundle();
                data.PutString ("my_message", msg);

                var id = msgId++;

                gcm.Send (MyRegistrationService.GCM_SENDER_ID + "@gcm.googleapis.com", id.ToString (), data);

                return true;

            } catch (Exception ex) {
                Android.Util.Log.Error (TAG, "SendUpstreamMessage Failed: {0}", ex);
            }

            return false;
        }
    }

    [Service]
    public class MyRegistrationService : IntentService
    {
        public const string GCM_SENDER_ID = "YOUR-SENDER-ID";

        public static event Action<string> TokenRefreshed;

        public static void Register (Context context)
        {
            context.StartService (new Intent (context, typeof(MyRegistrationService)));
        }

        protected override void OnHandleIntent (Intent intent)
        {
            // Get the new token and send to the server
            var instanceID = InstanceID.GetInstance (Application.Context);
            var token = instanceID.GetToken (GCM_SENDER_ID, GoogleCloudMessaging.InstanceIdScope);

            // Fire the event for any UI subscribed to it
            TokenRefreshed?.Invoke (token);

            Console.WriteLine ("OnTokenRefresh: {0}", token);
        }
    }

    [Service (Exported=false)]
    [IntentFilter (new [] { InstanceID.IntentFilterAction })]
    public class MyInstanceIDListenerService : InstanceIDListenerService
    {
        public override async void OnTokenRefresh ()
        {
            MyRegistrationService.Register (this);
        }
    }

    [Service (Exported=false)]
    [IntentFilter (new [] { GoogleCloudMessaging.IntentFilterActionReceive })]
    public class MyGcmListenerService : GcmListenerService
    {
        const string TAG = "GCMSAMPLE";

        public override void OnDeletedMessages ()
        {
            base.OnDeletedMessages ();

            Android.Util.Log.Debug (TAG, "Messages Deleted");
        }

        public override void OnMessageReceived (string from, Bundle data)
        {
            var message = data.GetString ("message");
            Android.Util.Log.Debug (TAG, "From: " + from);
            Android.Util.Log.Debug (TAG, "Message: " + message);

            /**
             * Production applications would usually process the message here.
             * Eg: - Syncing with server.
             *     - Store message in local database.
             *     - Update UI.
             */

            /**
            * In some cases it may be useful to show a notification indicating to the user
            * that a message was received.
            */
        }

        public override void OnMessageSent (string msgId)
        {
            base.OnMessageSent (msgId);

            Android.Util.Log.Debug (TAG, "Message Sent: {0}", msgId);
        }

        public override void OnSendError (string msgId, string error)
        {
            base.OnSendError (msgId, error);

            Android.Util.Log.Debug (TAG, "Message Failed: {0} - {1}", msgId, error);
        }
    }

}


text:
using namespace lb;

Ray::Ray(const Vector3d &origin, const Vector3d &direction):
    o(origin),
    d(direction)
{
}

/// Implements the 'Efficient Ray-Polygon Intersection' algorithm as described
/// by Didier Badouel in Graphics Gems I, first published in 1990.
bool Ray::intersectsDidierBadouel(const Triangle &triangle) const
{
    double k = dot(triangle.n, d);

    // In case the ray and the triangle are parallel, or the triangle is
    // backwards facing, the ray does not intersect the triangle.
    if (k >= 0)
    {
        return false;
    }

    double t = -(dot(triangle.n, o) + triangle.D) / k;

    // In case the intersection point lies behind the ray's origin, the ray does
    // not intersect the triangle.
    if (t < 0)
    {
        return false;
    }

    // Find the intersection point P.
    Vector3d P = o + t * d;

    // Project the triangle on either the XY, XZ, or YZ plane, such that the
    // projection is as large as possible, and not a flat line (in case the
    // normal of the triangle is parallel to the projection plane). The decision
    // on which plane to project is taken by taking the largest component of the
    // triangle's normal, and using the plane perpendicular to that axis as the
    // projection plane.
    double u0, u1, u2, v0, v1, v2;

    if (triangle.n.x >= triangle.n.y && triangle.n.x >= triangle.n.z)
    {
        // Project on the YZ plane.
        u0 = P.y - triangle.v0.y;
        u1 = triangle.e0.y;
        u2 = triangle.e1.y;

        v0 = P.z - triangle.v0.z;
        v1 = triangle.e0.z;
        v2 = triangle.e1.z;
    }
    else if (triangle.n.y >= triangle.n.z)
    {
        // Project on the XZ plane.
        u0 = P.x - triangle.v0.x;
        u1 = triangle.e0.x;
        u2 = triangle.e1.x;

        v0 = P.z - triangle.v0.z;
        v1 = triangle.e0.z;
        v2 = triangle.e1.z;
    }
    else
    {
        // Project on the XY plane.
        u0 = P.x - triangle.v0.x;
        u1 = triangle.e0.x;
        u2 = triangle.e1.x;

        v0 = P.y - triangle.v0.y;
        v1 = triangle.e0.y;
        v2 = triangle.e1.y;
    }

    double beta = (v0 * u1 - u0 * v1) / (u1 * v2 - u2 * v1);
    if (beta < 0.0 || beta > 1.0)
    {
        return false;
    }

    double alpha = (u0 * v2 - u2 * v0) / (u1 * v2 - u2 * v1);
    return alpha >= 0.0 && alpha + beta <= 1.0;
}

/// Implements a straight up geometrical approach to solve the ray/triangle
/// intersection problem. The intersection point P with the plane the triangle
/// lies in is first determined. Subsequently, the algorithm checks whether P
/// lies within the triangle boundaries.
bool Ray::intersectsGeometrically(const Triangle &triangle) const
{
    double k = dot(triangle.n, d);

    // In case the ray and the triangle are parallel, or the triangle is
    // backwards facing, the ray does not intersect the triangle.
    if (k >= 0)
    {
        return false;
    }

    double t = -(dot(triangle.n, o) + triangle.D) / k;

    // In case the intersection point lies behind the ray's origin, the ray does
    // not intersect the triangle.
    if (t < 0)
    {
        return false;
    }

    // Find the intersection point P.
    Vector3d P = o + t * d;

    // The ray intersects the plane of the triangle. Now determine whether the
    // intersection point lies within the triangle.
    return (dot(triangle.n, cross(triangle.e0, P - triangle.v0)) >= 0 &&
            dot(triangle.n, cross(triangle.v1v2, P - triangle.v1)) >= 0 &&
            dot(triangle.n, cross(triangle.v2v0, P - triangle.v2)) >= 0);
}

/// Implementation of the Moller/Trumbore algorithm, described in their paper
/// 'Fast Minimum-Storage Ray-Triangle Intersection', published in 1997.
bool Ray::intersectsMollerTrumbore(const Triangle &triangle) const
{
    Vector3d P = cross(d, triangle.e1);

    double determinant = dot(P, triangle.e0);
    if (determinant < EPSILON)
    {
        return false;
    }

    Vector3d T = o - triangle.v0;

    // Now calculate the barycentric coordinates u and v.
    double u = dot(P, T);
    if (u < 0.0 || u > determinant)
    {
        return false;
    }

    // In case v lies between 0 and 1, we have an intersection.
    double v = dot(cross(T, triangle.e0), d);
    if (v < 0.0 || v > determinant)
    {
        return false;
    }

    return (determinant - u - v) >= 0.0;
}

std::ostream &lb::operator<<(std::ostream &out, const Ray &r)
{
    return out << "Ray, origin: " << r.o << ", direction: " << r.d << "\n";
}

std::ostream &lb::operator<<(std::ostream &out, const IntersectionMethod &intersectionMethod)
{
    if (intersectionMethod == &lb::Ray::intersectsDidierBadouel)
    {
        out << "Didier-Badouel";
    }
    else if (intersectionMethod == &lb::Ray::intersectsMollerTrumbore)
    {
        out << "Moller-Trumbore";
    }
    else if (intersectionMethod == &lb::Ray::intersectsGeometrically)
    {
        out << "Geometrically";
    }
    else
    {
        out << "Unknown";
    }
}


text:
import os
try:
    from urllib import parse # py3
except:
    import urllib as parse # py2.7
from cantools.web import fetch
from cantools.util import log, read, write, writejson
from cantools import config

zcpath = os.path.join("logs", "json", "geo")

class Geo(object):
	apis = {
		"latlng": {
			"user": "google",
			"host": "maps.googleapis.com",
			"path": "/maps/api/geocode/json?sensor=false&address={0}",
			"sig": "key",
			"property": "results",
			"index": 0
		},
		"where": {
			"user": "google",
			"host": "maps.googleapis.com",
			"path": "/maps/api/geocode/json?sensor=false&address={0}",
			"sig": "key",
			"property": "results",
			"index": 0
		},
		"zip": {
			"geonames": {
				"user": "geonames",
				"host": "ws.geonames.org",
				"path": "/findNearbyPostalCodesJSON?radius=1&lat={0}&lng={1}",
				"sig": "username",
				"property": "postalCodes",
				"index": 0
			},
			"google": {
				"user": "google",
				"host": "maps.googleapis.com",
				"path": "/maps/api/geocode/json?sensor=false&latlng={0},{1}",
				"sig": "key",
				"property": "results",
				"index": 0
			}
		}[config.geo.zip]
	}

	def __init__(self):
		self.cache = read("%s.json"%(zcpath,), isjson=True, default={})
		for addr in self.cache:
			self.cache[addr]["count"] = 0

	def _no_cache(self, addr):
		return not (addr in self.cache and self.cache[addr]["lat"] and self.cache[addr]["lng"])

	def _fetch(self, api, *args): # api is latlng/zip
		path = self.apis[api]["path"].format(*[parse.quote(str(a).replace(" ", "+")) for a in args])
		host = self.apis[api]["host"]
		user = self.apis[api]["user"]
		prop = self.apis[api]["property"]
		keys = config.geo.user[user]
		onum = num = self.apis[api]["index"]
		sig = self.apis[api]["sig"]
		kwargs = { "asjson": True }
		result = []
		while True:
			fullpath = path
			if keys[num]:
				fullpath += "&%s=%s"%(sig, keys[num])
				if user == "google":
					kwargs["protocol"] = "https"
			raw = fetch(host, fullpath, **kwargs)
			result = raw.get(prop, [])
			if len(result):
				break
			log("0-length %s result (got: '%s') - changing user"%(api, raw), important=True)
			num = (num + 1) % len(keys)
			if num == onum:
				log("exhausted key list -- returning [] :'(")
				break
		self.apis[api]["index"] = num
		return result

	def where(self, place):
		results = self._fetch("where", place)
		if not results:
			return "space"
		places = results[0]["address_components"]
		return len(places) > 1 and places[1]["long_name"] or "earth"

	def address2latlng(self, address):
		if self._no_cache(address):
			log("finding lat/lng for %s"%(address,), 3)
			results = self._fetch("latlng", address)
			if not len(results):
				log("no results!!!", 4)
				self.cache[address] = {
					"lat": None,
					"lng": None
				}
			else:
				loc = results[0]['geometry']['location']
				self.cache[address] = {
					"lat": loc["lat"],
					"lng": loc["lng"]
				}
			self.savecache()
		return [self.cache[address]['lat'], self.cache[address]['lng']]

	def latlng2zip(self, lat, lng):
		result = self._fetch("zip", lat, lng)
		log("finding zip for lat %s and lng %s"%(lat, lng), 3)
		if not len(result):
			log("can't find zipcode!!!", important=True)
			return None
		if config.geo.zip == "google":
			return [c["short_name"] for c in result[0]["address_components"] if c["types"][0] == "postal_code"][0]
		return result[0]["postalCode"]

	def addr2zip(self, addr, allowNone=False):
		log("finding zip for '%s'"%(addr,), 3)
		if config.geo.test:
			log("test mode! returning nonsense :)")
			return '12345'
		if self._no_cache(addr):
			self.address2latlng(addr)
		d = self.cache[addr]
		if not d.get("zip", allowNone):
			d["count"] = 1
			d["zip"] = d["lat"] and self.latlng2zip(d["lat"], d["lng"])
			self.savecache()
		else:
			d["count"] += 1
			log("address referenced %s times"%(d["count"],), 4)
		log("found zip: %s"%(d["zip"],), 4)
		return d["zip"]

	def savecache(self, pretty=False):
		log("saving zipcode / latlng (geo) cache (pretty: %s)"%(pretty,), important=True)
		if pretty:
			writejson(self.cache, zcpath)
		else:
			write(self.cache, "%s.json"%(zcpath,), True)

	def distance(self, lat1, lng1, lat2, lng2):
		log("approximating distance between [%s %s] and [%s %s]"%(lat1, lng1, lat2, lng2))
		latd = lat1 - lat2
		lngd = lng1 - lng2
		latsq = latd ** 2
		lngsq = lngd ** 2
		tsq = latsq + lngsq
		hypot = tsq**(1.0/2)
		miles = hypot * 69.11;
		log("lat diff: %s square: %s"%(latd, latsq))
		log("lng diff: %s square: %s"%(lngd, lngsq))
		log("sum of squares: %s hypotenuse: %s"%(tsq, hypot))
		log("about %s miles"%(miles,))
		return miles

geo = Geo()
where = geo.where
address2latlng = geo.address2latlng
latlng2zip = geo.latlng2zip
addr2zip = geo.addr2zip
savecache = geo.savecache
distance = geo.distance


text:
namespace g{
namespace Android{
namespace Base{
namespace Primitives{

// public extern struct jfieldID :2082
// {
uStructType* jfieldID_typeof();

struct jfieldID
{
};
// }

}}}} // ::g::Android::Base::Primitives


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Quadrotor Flips Optimization using CMA-ES | ShortCircuits</title>
    <meta name=viewport content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Quattrocento:400,700|Quattrocento+Sans:400,400i,700|Inconsolata" rel="stylesheet">
    <link rel="stylesheet" href="/static/css/index.min.css"/>
    <link rel="shortcut icon" href="/static/images/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/static/images/favicon.ico" type="image/x-icon">
    <meta name="description" content="Quadrotors have fascinated me for a long time. There has been an enormous amount of research with these small machines leading to a lot of cool experiments and products over the past few years. Machine learning techniques have been used in a lot of research papers to optimize the flight ...">
    <meta name="keywords" content="Python,Quadrotor,CMA-ES">
    <meta name="author" content="Nikhil K">

Projects

Blog

About

         Quadrotor Flips Optimization using CMA-ES

                    August 05, 2016

Quadrotors have fascinated me for a long time. There has been an enormous amount of research with these small machines leading to a lot of cool experiments and products over the past few years. Machine learning techniques have been used in a lot of research papers to optimize the flight. I wanted to learn how you can perform the task using Python and apply machine learning techniques. I started hunting for articles on this topic and among the humongous list, I found that I liked the paper A Simple Learning Strategy for High-Speed Quadrocopter Multi-Flips the most. The article is written by Sergei Lupashin, Angela Schollig, Michael Sherback, Raffaello D'Andrea from group Flying Machine Arena.

Acrobatic maneuvers are tough to perform on quadrotors as they require precise control over the thrust that is applied to the motors. The paper describes how machine learning technique can be used to perform flips along one of the axes at a high rotation rate of 1600 degrees/second and return to the starting position without any human intervention. Let me give a very brief overview the approach used in the paper.

Quadrotors are sophisticated devices that are influenced by a lot of factors. So rather than making use of higher order model, most of the researchers go ahead with a simplistic lower order model as this reduces the complexities introduced by the higher order models without compromising the accuracy of the model. A quadrotor has four motors, and primitively it can be modeled as the collective forces generated by the four motors and gravitational force acting on it. The movement of the quadrotor for this maneuver is controlled using the collective acceleration value applied to the all the motors, this value is then broken down into multiple control parameters based on a PI controller. A control envelope is used to restrict input values generated.

The flip is performed in 5 steps and is defined by five parameters, and simplistically they are the acceleration and period for which the force is applied. These form the values that are optimized to gain better performance. Initially, a rough guess of the initial values of the five control parameters is provided to the optimization algorithm. The roughly estimated parameters are fed to an optimizer that is running an algorithm like CMA-ES to obtain the best set of values. The algorithm makes use of the simple low order quadrotor model to perform the optimization. The optimal parameters obtained from the optimizer are then fed to the quadrotor to carry out the flips in real time.

The entire algorithm is implemented using Python. The quadrotor model makes of numpy array methods and odeint from scipy to perform the integration. CMA-ES is used as the optimization library, and the implementation by deap framework is used. The library can be found on github.

The generated data can be visualized using matplotlib or through blender. You can see the results from an incomplete simulation using both the visualization methods

Matplotlib Result

Matplotlib Based 3d Plot

Blender Animation

Conclusion

I would like to point out that these are my personal opinions and I you have any valid concerns related to the post please let me know. The library is modular and hence feel free to utilize it in any of your ventures.

References and Links

A Simple Learning Strategy for High-Speed Quadrocopter Multi-Flips

Sergei Lupashin, Angela Sch ̈ollig, Michael Sherback, Raffaello D'Andrea

Adaptive Open-Loop Aerobatic Maneuvers for Quadrocopters

Sergei Lupashin, Rafaello D'Andrea

Adaptive fast open-loop maneuvers for quadrocopters

Sergei Lupashin, Rafaello D'Andrea

Tags

                Python
                Quadrotor
                CMA-ES

Please enable JavaScript to view the comments powered by Disqus.


text:
"""
Given two integers representing the numerator and denominator of a fraction,
return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

    Given numerator = 1, denominator = 2, return "0.5".
    Given numerator = 2, denominator = 1, return "2".
    Given numerator = 2, denominator = 3, return "0.(6)".

Hint:

    No scary math, just apply elementary math knowledge. Still remember how to
    perform a long division?

    Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do
    you see a pattern?

    Be wary of edge cases! List out as many test cases as you can think of and
    test your code thoroughly.

Credits:
    Special thanks to @Shangrila for adding this problem and creating all test
    cases.
"""
class Solution(object):
    def fractionToDecimal(self, numerator, denominator):
        """
        :type numerator: int
        :type denominator: int
        :rtype: str
        """
        if denominator == 0:
            return
        if numerator == 0:
            return "0"
        soln = []
        if numerator * denominator < 0:
            neg = True
            soln.append('-')
        else:
            neg = False
        numerator = abs(numerator)
        denominator = abs(denominator)
        if numerator >= denominator:
            quotient, numerator = divmod(numerator, denominator)
            soln.append(str(quotient))
        else:
            soln.append('0')
        if numerator > 0:
            soln.append('.')
            locs = {}
            loc = 0
            while True:
                numerator *= 10
                quotient, remainder = divmod(numerator, denominator)
                if (quotient, remainder) in locs:
                    divided = False
                    break
                if remainder == 0:
                    soln.append(str(quotient))
                    divided = True
                    break
                numerator = remainder
                soln.append(str(quotient))
                locs[(quotient, remainder)] = loc
                loc += 1
        else:
            divided = True
        if not divided:
            if neg:
                soln.insert(locs[(quotient, remainder)] + 3, '(')
            else:
                soln.insert(locs[(quotient, remainder)] + 2, '(')
            soln.append(')')
        return "".join(soln)

assert Solution().fractionToDecimal(2, 1) == "2"
assert Solution().fractionToDecimal(-50, 8) == "-6.25"
assert Solution().fractionToDecimal(1, 2) == "0.5"
assert Solution().fractionToDecimal(2, 3) == "0.(6)"
assert Solution().fractionToDecimal(5, 3) == "1.(6)"
assert Solution().fractionToDecimal(1, 7) == "0.(142857)"
assert Solution().fractionToDecimal(1, 17) == "0.(0588235294117647)"
assert Solution().fractionToDecimal(7, 12) == "0.58(3)"
assert Solution().fractionToDecimal(7, -12) == "-0.58(3)"
assert Solution().fractionToDecimal(4, 333) == "0.(012)"
print("pass")


text:
from os import environ
from twisted.internet.defer import inlineCallbacks, returnValue

from autobahn.wamp.types import RegisterOptions
from autobahn.twisted.util import sleep
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner

class Component(ApplicationSession):
    """
    Application component that produces progressive results.
    """

    @inlineCallbacks
    def onJoin(self, details):
        print("session attached")

        @inlineCallbacks
        def longop(n, details=None):
            if details.progress:
                # caller can (and requested to) consume progressive results
                for i in range(n):
                    details.progress(i)
                    yield sleep(1)
            else:
                # process like a normal call (not producing progressive results)
                yield sleep(1 * n)
            returnValue(n)

        yield self.register(longop, u'com.myapp.longop', RegisterOptions(details_arg='details'))

        print("procedures registered")

if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"),
        u"crossbardemo",

        debug=False,  # optional; log even more details
    )
    runner.run(Component)


text:
package com.novbank.ndp.kernel.rdfsupport;

import org.javatuples.Triplet;

/**
 * Created by hp on 2015/5/14.
 */
public class RDFTriple<S extends RDFResource,P extends RDFProperty,O extends RDFValue>{
    protected Triplet<S,P,O> triplet;
    public RDFTriple(S subj, P pred, O obj) {
        triplet = new Triplet<>(subj, pred, obj);
    }

    public final S getSubject(){
        return triplet.getValue0();
    }

    public final P getPredicate(){
        return triplet.getValue1();
    }

    public final O getObject(){
        return triplet.getValue2();
    }
}


text:
//
//  MPGoogleAdMobInterstitialCustomEvent.h
//  MoPub
//
//  Copyright (c) 2012 MoPub, Inc. All rights reserved.
//

#import "MPInterstitialCustomEvent.h"
#import "GADInterstitial.h"

/*
 * Certified with version 6.9.3 of the Google AdMob Ads SDK.
 */

@interface MPGoogleAdMobInterstitialCustomEvent : MPInterstitialCustomEvent <GADInterstitialDelegate>

@end


text:
using System;
using System.Drawing;
using VectorImageEdit.Modules.BasicShapes.Geometries;

namespace VectorImageEdit.Modules.BasicShapes
{
    [Serializable]
    public class BezierCurve : ShapeBase
    {
        public BezierCurve(Point p0, Point p1, Point p2, Point p3, ShapeStyle style)
            : base(new Rectangle(
                Math.Min(Math.Min(Math.Min(p0.X, p1.X), p2.X), p3.X),
                Math.Min(Math.Min(Math.Min(p0.Y, p1.Y), p2.Y), p3.Y),
                Math.Max(Math.Max(Math.Max(p0.X, p1.X), p2.X), p3.X) - Math.Min(Math.Min(Math.Min(p0.X, p1.X), p2.X), p3.X),
                Math.Max(Math.Max(Math.Max(p0.Y, p1.Y), p2.Y), p3.Y) - Math.Min(Math.Min(Math.Min(p0.Y, p1.Y), p2.Y), p3.Y)),
                0,
                style,
                "Layer - BezierCurve")
        {
            ControlPoints = new[]
            {
                new GeometryPoint(p0, GeometryPointType.Movable),
                new GeometryPoint(p1, GeometryPointType.Movable),
                new GeometryPoint(p2, GeometryPointType.Movable),
                new GeometryPoint(p3, GeometryPointType.Movable)
            };

            controlPointLinks = new GeometryItem[3];
            controlPointLinks[0].Points[0] = ControlPoints[0];
            controlPointLinks[0].Points[1] = ControlPoints[1];
            controlPointLinks[1].Points[0] = ControlPoints[1];
            controlPointLinks[1].Points[1] = ControlPoints[2];
            controlPointLinks[2].Points[0] = ControlPoints[2];
            controlPointLinks[2].Points[1] = ControlPoints[3];

            EditablegeometryCue.AddRange(ControlPoints);
            EditablegeometryCue.AddRange(controlPointLinks);
        }

        /// <summary>
        /// Gets the editable geometry points that define this Bezier curve.
        /// Note: the shape region contains all these points.
        /// </summary>
        public GeometryPoint[] ControlPoints { get; private set; }

        private GeometryItem[] controlPointLinks;

        public override void DrawGraphics(Graphics destination)
        {
            DrawGraphics();
            using (var pen = Style.CreatePen())
            {
                destination.DrawBezier(pen, ControlPoints[0], ControlPoints[1], ControlPoints[2], ControlPoints[3]);
            }

            EditablegeometryCue.DrawGeometry(destination);
        }

        public override void ConstructFrom(Rectangle region)
        {
            throw new NotSupportedException();
        }
    }
}


text:
@interface MoreViewController ()

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIViewController *lastVC;
@property (nonatomic, strong) UINavigationController *lastNavVC;

@end

@implementation MoreViewController

- (id)init
{
    self = [super initWithNibName:@"MoreViewController" bundle:nil];

    if (self != nil) {
        self.title = @"More";
    }

    return self;
}

#pragma mark - TabBarControllerDelegate methods

- (TabBarItemView *)tabBarItemView
{
    TabBarItemView *tabBarItem = [TabBarController defaultTabBarItemView];
    tabBarItem.item.title = @"More";
    tabBarItem.item.image = [UIImage imageNamed:@"dot-more-7"];

    return tabBarItem;
}

#pragma mark - UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.viewControllers count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }

    TabBarController *tabBarController = (TabBarController *)self.tabBarController;
    TabBarItemView *tabBarItemView = [tabBarController tabBarItemViewForViewController:self.viewControllers[ indexPath.row ]];

    cell.textLabel.text = tabBarItemView.item.title;
    cell.imageView.image = tabBarItemView.item.image;

    cell.exclusiveTouch = YES;

    return cell;
}

#pragma mark - UITableViewDelegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIViewController *viewController = self.viewControllers[ indexPath.row ];

    [self.navigationController pushViewController:viewController animated:YES];
}

@end


text:
package org.apache.camel.component.bean;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spi.Registry;
import org.junit.Test;

public class MethodCallRefOrBeanPrefixTest extends ContextTestSupport {

    @Override
    protected Registry createRegistry() throws Exception {
        Registry jndi = super.createRegistry();
        jndi.bind("foo", new MyFooBean());
        return jndi;
    }

    @Test
    public void testRefOrBeanPrefix() throws Exception {
        getMockEndpoint("mock:a").expectedBodiesReceived("Hello A");
        getMockEndpoint("mock:b").expectedBodiesReceived("Hello B");

        template.sendBody("direct:a", "A");
        template.sendBody("direct:b", "B");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:a").transform().method("ref:foo").to("mock:a");

                from("direct:b").transform().method("bean:foo").to("mock:b");
            }
        };
    }
}