text:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
CheckSymbolExists
-----------------

Provides a macro to check if a symbol exists as a function, variable,
or macro in ``C``.

.. command:: check_symbol_exists

  .. code-block:: cmake

    check_symbol_exists(<symbol> <files> <variable>)

  Check that the ``<symbol>`` is available after including given header
  ``<files>`` and store the result in a ``<variable>``.  Specify the list
  of files in one argument as a semicolon-separated list.
  ``<variable>`` will be created as an internal cache variable.

If the header files define the symbol as a macro it is considered
available and assumed to work.  If the header files declare the symbol
as a function or variable then the symbol must also be available for
linking (so intrinsics may not be detected).
If the symbol is a type, enum value, or intrinsic it will not be recognized
(consider using :module:`CheckTypeSize` or :module:`CheckCSourceCompiles`).
If the check needs to be done in C++, consider using
:module:`CheckCXXSymbolExists` instead.

The following variables may be set before calling this macro to modify
the way the check is run:

``CMAKE_REQUIRED_FLAGS``
  string of compile command line flags.
``CMAKE_REQUIRED_DEFINITIONS``
  a :ref:`;-list <CMake Language Lists>` of macros to define (-DFOO=bar).
``CMAKE_REQUIRED_INCLUDES``
  a :ref:`;-list <CMake Language Lists>` of header search paths to pass to
  the compiler.
``CMAKE_REQUIRED_LINK_OPTIONS``
  a :ref:`;-list <CMake Language Lists>` of options to add to the link command.
``CMAKE_REQUIRED_LIBRARIES``
  a :ref:`;-list <CMake Language Lists>` of libraries to add to the link
  command. See policy :policy:`CMP0075`.
``CMAKE_REQUIRED_QUIET``
  execute quietly without messages.

For example:

.. code-block:: cmake

  include(CheckSymbolExists)

  # Check for macro SEEK_SET
  check_symbol_exists(SEEK_SET "stdio.h" HAVE_SEEK_SET)
  # Check for function fopen
  check_symbol_exists(fopen "stdio.h" HAVE_FOPEN)
#]=======================================================================]

if(__CheckSymbolExists_cmake__)
  return()
endif()
set(__CheckSymbolExists_cmake__ TRUE)

cmake_policy(PUSH)
cmake_policy(SET CMP0054 NEW) # if() quoted variables not dereferenced

macro(CHECK_SYMBOL_EXISTS SYMBOL FILES VARIABLE)
  if(CMAKE_C_COMPILER_LOADED)
    __CHECK_SYMBOL_EXISTS_IMPL("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.c" "${SYMBOL}" "${FILES}" "${VARIABLE}" )
  elseif(CMAKE_CXX_COMPILER_LOADED)
    __CHECK_SYMBOL_EXISTS_IMPL("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.cxx" "${SYMBOL}" "${FILES}" "${VARIABLE}" )
  else()
    message(FATAL_ERROR "CHECK_SYMBOL_EXISTS needs either C or CXX language enabled")
  endif()
endmacro()

macro(__CHECK_SYMBOL_EXISTS_IMPL SOURCEFILE SYMBOL FILES VARIABLE)
  if(NOT DEFINED "${VARIABLE}" OR "x${${VARIABLE}}" STREQUAL "x${VARIABLE}")
    set(CMAKE_CONFIGURABLE_FILE_CONTENT "/* */\n")
    set(MACRO_CHECK_SYMBOL_EXISTS_FLAGS ${CMAKE_REQUIRED_FLAGS})
    if(CMAKE_REQUIRED_LINK_OPTIONS)
      set(CHECK_SYMBOL_EXISTS_LINK_OPTIONS
        LINK_OPTIONS ${CMAKE_REQUIRED_LINK_OPTIONS})
    else()
      set(CHECK_SYMBOL_EXISTS_LINK_OPTIONS)
    endif()
    if(CMAKE_REQUIRED_LIBRARIES)
      set(CHECK_SYMBOL_EXISTS_LIBS
        LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES})
    else()
      set(CHECK_SYMBOL_EXISTS_LIBS)
    endif()
    if(CMAKE_REQUIRED_INCLUDES)
      set(CMAKE_SYMBOL_EXISTS_INCLUDES
        "-DINCLUDE_DIRECTORIES:STRING=${CMAKE_REQUIRED_INCLUDES}")
    else()
      set(CMAKE_SYMBOL_EXISTS_INCLUDES)
    endif()
    foreach(FILE ${FILES})
      string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT
        "#include <${FILE}>\n")
    endforeach()
    string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT "
int main(int argc, char** argv)
{
  (void)argv;")
    set(_CSE_CHECK_NON_MACRO "return ((int*)(&${SYMBOL}))[argc];")
    if("${SYMBOL}" MATCHES "^[a-zA-Z_][a-zA-Z0-9_]*$")
      # The SYMBOL has a legal macro name.  Test whether it exists as a macro.
      string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT "
#ifndef ${SYMBOL}
  ${_CSE_CHECK_NON_MACRO}
#else
  (void)argc;
  return 0;
#endif")
    else()
      # The SYMBOL cannot be a macro (e.g., a template function).
      string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT "
  ${_CSE_CHECK_NON_MACRO}")
    endif()
    string(APPEND CMAKE_CONFIGURABLE_FILE_CONTENT "
}")
    unset(_CSE_CHECK_NON_MACRO)

    configure_file("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
      "${SOURCEFILE}" @ONLY)

    if(NOT CMAKE_REQUIRED_QUIET)
      message(CHECK_START "Looking for ${SYMBOL}")
    endif()
    try_compile(${VARIABLE}
      ${CMAKE_BINARY_DIR}
      "${SOURCEFILE}"
      COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS}
      ${CHECK_SYMBOL_EXISTS_LINK_OPTIONS}
      ${CHECK_SYMBOL_EXISTS_LIBS}
      CMAKE_FLAGS
      -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_SYMBOL_EXISTS_FLAGS}
      "${CMAKE_SYMBOL_EXISTS_INCLUDES}"
      OUTPUT_VARIABLE OUTPUT)
    if(${VARIABLE})
      if(NOT CMAKE_REQUIRED_QUIET)
        message(CHECK_PASS "found")
      endif()
      set(${VARIABLE} 1 CACHE INTERNAL "Have symbol ${SYMBOL}")
      file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
        "Determining if the ${SYMBOL} "
        "exist passed with the following output:\n"
        "${OUTPUT}\nFile ${SOURCEFILE}:\n"
        "${CMAKE_CONFIGURABLE_FILE_CONTENT}\n")
    else()
      if(NOT CMAKE_REQUIRED_QUIET)
        message(CHECK_FAIL "not found")
      endif()
      set(${VARIABLE} "" CACHE INTERNAL "Have symbol ${SYMBOL}")
      file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
        "Determining if the ${SYMBOL} "
        "exist failed with the following output:\n"
        "${OUTPUT}\nFile ${SOURCEFILE}:\n"
        "${CMAKE_CONFIGURABLE_FILE_CONTENT}\n")
    endif()
    unset(CMAKE_CONFIGURABLE_FILE_CONTENT)
  endif()
endmacro()

cmake_policy(POP)

redpajama_set_name: RedPajamaGithub


text:
/*
 *  Definition for Async HDLC
 */
#define HDLC_SYN 0x7e		/* SYNC character */
#define HDLC_ESC 0x7d		/* Escape character */
#define HDLC_XOR 0x20		/* Modifier value */

#define	HDLC_ADDR 0xff
#define	HDLC_UI	  0x03
/*
 *  Definition for HDLC Frame Check Sequence
 */
#define INITFCS 0xffff		/* Initial value for FCS computation */
#define GOODFCS 0xf0b8		/* Good FCS value */

#define	DEF_MRU		1500
#define	MAX_MRU		2048
#define	MIN_MRU		296

#define	DEF_MTU		0	/* whatever peer says */
#define	MAX_MTU		2048
#define	MIN_MTU		296

struct physical;
struct link;
struct lcp;
struct bundle;
struct mbuf;
struct cmdargs;

struct hdlc {
  struct pppTimer ReportTimer;

  struct {
    int badfcs;
    int badaddr;
    int badcommand;
    int unknownproto;
  } laststats, stats;

  struct {
    struct lcp *owner;			/* parent LCP */
    struct pppTimer timer;		/* When to send */
    int method;				/* bit-mask for LQM_* from lqr.h */

    u_int32_t ifOutUniPackets;		/* Packets sent by me */
    u_int32_t ifOutOctets;		/* Octets sent by me */
    u_int32_t ifInUniPackets;		/* Packets received from peer */
    u_int32_t ifInDiscards;		/* Discards */
    u_int32_t ifInErrors;		/* Errors */
    u_int32_t ifInOctets;		/* Octets received from peer (unused) */

    struct {
      u_int32_t InGoodOctets;		/* Good octets received from peer */
      u_int32_t OutLQRs;		/* LQRs sent by me */
      u_int32_t InLQRs;			/* LQRs received from peer */

      struct lqrsavedata Save;		/* Our last LQR */
      struct lqrsavedata prevSave;	/* Our last-but-one LQR (analysis) */

      struct lqrdata peer;		/* Last LQR from peer */
      int peer_timeout;			/* peers max lqr timeout */
      int resent;			/* Resent last packet `resent' times */
    } lqr;

    struct {
      u_int32_t seq_sent;		/* last echo sent */
      u_int32_t seq_recv;		/* last echo received */
    } echo;
  } lqm;
};

extern void hdlc_Init(struct hdlc *, struct lcp *);
extern void hdlc_StartTimer(struct hdlc *);
extern void hdlc_StopTimer(struct hdlc *);
extern int hdlc_ReportStatus(struct cmdargs const *);
extern const char *hdlc_Protocol2Nam(u_short);
extern void hdlc_DecodePacket(struct bundle *, u_short, struct mbuf *,
                              struct link *);

extern u_short hdlc_Fcs(u_char *, size_t);
extern int hdlc_Detect(u_char const **, unsigned, int);
#define hdlc_WrapperOctets() (2)

extern struct layer hdlclayer;


text:
define(['ojs/ojcore', 'knockout', 'jquery', 'appController', 'ojs/ojrouter', 'ojs/ojinputtext', 'ojs/ojbutton', 'ojs/ojcheckboxset'], function(oj, ko, $, app) {
	function SigninViewModel() {
		var self = this;

		var storage = window.localStorage;

		self.userName = ko.observable(storage.getItem('username'));
		self.password = ko.observable(storage.getItem('password'));

		self.rememberUserName = ko.observable(['remember']);
		self.notification = ko.observable();

		self.signIn = function() {
			//app.appUtilities.startSpinner();
			/*mbe.authenticate(self.userName(), self.password(), function (code, data) {
				mbe.getCurrentUser().then(function(user) {
					if (window.cordova.platformId != 'browser') app.setupNotifications();

					if (self.rememberUserName()[0] == 'remember') {
						storage.setItem('username', self.userName());
						storage.setItem('password', self.password());
					} else {
						storage.removeItem('username');
						storage.removeItem('password');
					}
					app.user = user;
					//app.appUtilities.stopSpinner();
					oj.Router.rootInstance.go('dashboard');
				});
			}, function(error) {
				console.log('error', error);
				//app.appUtilities.stopSpinner();
			});*/
			if (self.rememberUserName()[0] == 'remember') {
				storage.setItem('username', self.userName());
				storage.setItem('password', self.password());
			} else {
				storage.removeItem('username');
				storage.removeItem('password');
			}
			app.user = {
				username : self.userName()
			}
			oj.Router.rootInstance.go('bus');

		};

	}
	return SigninViewModel;
});


text:
LCM Server: an LCM interface to Caesar.jl
=#

using Base.Dates
using Caesar
using Unmarshal
using CaesarLCMTypes
using TransformUtils, Rotations, CoordinateTransformations
using Distributions
using LCMCore
using LibBSON

using RobotTestDatasets

include(joinpath(dirname(@__FILE__), "synchronySDKIntegration.jl"))

"""
Store robot parameters in the centralized database system.
"""
function setRobotParameters!(sslaml::SyncrSLAM)
  rovconf = Dict{String, String}() # TODO relax to Dict{String, Any}
  rovconf["robot"] = "hovering-rov"
  rovconf["bTc"] = "[0.0;0.0;0.0; 1.0; 0.0; 0.0; 0.0]"
  rovconf["bTc_format"] = "xyzqwqxqyqz"
  # currently unused, but upcoming
  rovconf["pointcloud_description_name"] = "BSONpointcloud"
  rovconf["pointcloud_color_description_name"] = "BSONcolors"

  # Actually modify the databases
  Syncr.updateRobotConfig(sslaml.syncrconf, sslaml.robotId, rovconf)

  nothing
end

# Include the LCM handlers...
include(joinpath(dirname(@__FILE__), "lcmHandlers.jl"))

# this function handles lcm msgs
function listener!(lcm_node::Union{LCMCore.LCM, LCMCore.LCMLog})
    # handle traffic
        # TODO: handle termination
    while true
        if !handle(lcm_node)
            break
        end
    end
end

# 0. Constants
println("[Caesar.jl] defining constants.")
robotId = "HROV"
sessionId = "LCM_27"
sessionId = strip(sessionId)

# create a SLAM container object
slam_client = SyncrSLAM(robotId, sessionId, nothing)

# initialize a new session ready for SLAM using the built in SynchronySDK
println("[Caesar.jl] Setting up remote solver")
initialize!(slam_client)

# Set up the robot
setRobotParameters!(slam_client)
robotConfig = Syncr.getRobotConfig(slam_client.syncrconf, slam_client.robotId)

# TODO - should have a function that allows first pose and prior to be set by user.

# create new handlers to pass in additional data
lcm_pose_handler = (channel, message_data) -> handle_poses!(slam_client, message_data )
lcm_odom_handler = (channel, message_data) -> handle_partials!(slam_client, message_data )
lcm_prior_handler = (channel, message_data) -> handle_priors!(slam_client, message_data )
lcm_cloud_handler = (channel, message_data) -> handle_clouds!(slam_client, message_data )
lcm_loop_handler = (channel, message_data) -> handle_loops!(slam_client, message_data )

# create LCM object and subscribe to messages on the following channels
logfile = robotdata("rovlcm_singlesession_01")
lcm_node = LCMLog(logfile) # for direct log file access

# poses
subscribe(lcm_node, "CAESAR_POSES", lcm_pose_handler, pose_node_t)

# factors
subscribe(lcm_node, "CAESAR_PARTIAL_XYH", lcm_odom_handler)
subscribe(lcm_node, "CAESAR_PARTIAL_ZPR", lcm_prior_handler, prior_zpr_t)
# loop closures come in via p3p3nh factors
subscribe(lcm_node, "CAESAR_PARTIAL_XYH_NH", lcm_loop_handler, pose_pose_xyh_nh_t)

# sensor data
subscribe(lcm_node, "CAESAR_POINT_CLOUDS", lcm_cloud_handler, point_cloud_t)

println("[Caesar.jl] Running LCM listener")
listener!(lcm_node)

println(" --- Done! Now we can run the solver on this dataset!")

# Todo - call Sychrony to start the solver


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using Twingly.Gearman.Configuration;
using Twingly.Gearman.Exceptions;

namespace Twingly.Gearman
{
    public abstract class GearmanConnectionManager : IDisposable
    {
        private const int _DEFAULT_PORT = 4730;

        private readonly IList<IGearmanConnection> _connections;
        private IGearmanConnectionFactory _connectionFactory;

        public IGearmanConnectionFactory ConnectionFactory
        {
            get
            {
                return _connectionFactory;
            }

            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");

                _connectionFactory = value;
            }
        }

        protected GearmanConnectionManager()
        {
            _connections = new List<IGearmanConnection>();
            _connectionFactory = new GearmanConnectionFactory();
        }

        protected GearmanConnectionManager(string clusterName)
            : this()
        {
            if (clusterName == null)
                throw new ArgumentNullException("clusterName");

            var section = ConfigurationManager.GetSection("gearman") as GearmanConfigurationSection;
            if (section == null)
                throw new ConfigurationErrorsException("Section gearman is not found.");

            ParseConfiguration(section.Clusters[clusterName]);
        }

        protected GearmanConnectionManager(ClusterConfigurationElement clusterConfiguration)
            : this()
        {
            if (clusterConfiguration == null)
                throw new ArgumentNullException("clusterConfiguration");

            ParseConfiguration(clusterConfiguration);
        }

        public void Dispose()
        {
            // http://codecrafter.blogspot.se/2010/01/better-idisposable-pattern.html
            CleanUpManagedResources();
            GC.SuppressFinalize(this);
        }

        protected virtual void CleanUpManagedResources()
        {
            DisconnectAll();
        }

        private void ParseConfiguration(ClusterConfigurationElement cluster)
        {
            foreach (ServerConfigurationElement server in cluster.Servers)
            {
                AddServer(server.Host, server.Port);
            }
        }

        public void AddServer(string host)
        {
            AddServer(host, _DEFAULT_PORT);
        }

        public void AddServer(string host, int port)
        {
            AddConnection(ConnectionFactory.CreateConnection(host, port));
        }

        public void DisconnectAll()
        {
            foreach (var connection in _connections)
            {
                if (connection != null)
                {
                    connection.Disconnect();
                }
            }
        }

        private void AddConnection(IGearmanConnection connection)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            _connections.Add(connection);
        }

        protected IEnumerable<IGearmanConnection> GetAliveConnections()
        {
            var connections = _connections.Shuffle(new Random()).ToList();
            var isAllDead = _connections.Where(conn => conn.IsDead()).Count() == _connections.Count;
            var aliveConnections = new List<IGearmanConnection>();

            foreach (var connection in connections)
            {
                // Try to reconnect if they're not connected and not dead, or if all servers are dead, we will try to reconnect them anyway.
                if (!connection.IsConnected() && (!connection.IsDead() || isAllDead))
                {
                    try
                    {
                        connection.Connect();
                        OnConnectionConnected(connection);

                        // quick idea: Make GearmanConnection a base class and sub class it differently for the
                        // client and the worker, where the worker always registers all functions when connecting?
                        // Could that work?
                    }
                    catch (GearmanConnectionException)
                    {
                        // Is it enough to catch GearmanConnectionException?
                        connection.MarkAsDead();
                        continue;
                    }
                }

                if (connection.IsConnected())
                {
                    aliveConnections.Add(connection);
                }
            }

            return aliveConnections;
        }

        protected virtual void OnConnectionConnected(IGearmanConnection connection)
        {
        }
    }
}


text:
namespace __asan {

typedef __asan_global Global;

struct ListOfGlobals {
  const Global *g;
  ListOfGlobals *next;
};

static AsanLock mu_for_globals(LINKER_INITIALIZED);
static LowLevelAllocator allocator_for_globals;
static ListOfGlobals *list_of_all_globals;
static ListOfGlobals *list_of_dynamic_init_globals;

void PoisonRedZones(const Global &g)  {
  uptr shadow_rz_size = kGlobalAndStackRedzone >> SHADOW_SCALE;
  CHECK(shadow_rz_size == 1 || shadow_rz_size == 2 || shadow_rz_size == 4);
  // full right redzone
  uptr g_aligned_size = kGlobalAndStackRedzone *
      ((g.size + kGlobalAndStackRedzone - 1) / kGlobalAndStackRedzone);
  PoisonShadow(g.beg + g_aligned_size,
               kGlobalAndStackRedzone, kAsanGlobalRedzoneMagic);
  if ((g.size % kGlobalAndStackRedzone) != 0) {
    // partial right redzone
    u64 g_aligned_down_size = kGlobalAndStackRedzone *
        (g.size / kGlobalAndStackRedzone);
    CHECK(g_aligned_down_size == g_aligned_size - kGlobalAndStackRedzone);
    PoisonShadowPartialRightRedzone(g.beg + g_aligned_down_size,
                                    g.size % kGlobalAndStackRedzone,
                                    kGlobalAndStackRedzone,
                                    kAsanGlobalRedzoneMagic);
  }
}

static uptr GetAlignedSize(uptr size) {
  return ((size + kGlobalAndStackRedzone - 1) / kGlobalAndStackRedzone)
      * kGlobalAndStackRedzone;
}

bool DescribeAddressIfGlobal(uptr addr) {
  if (!flags()->report_globals) return false;
  ScopedLock lock(&mu_for_globals);
  bool res = false;
  for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
    const Global &g = *l->g;
    if (flags()->report_globals >= 2)
      Report("Search Global: beg=%p size=%zu name=%s\n",
             (void*)g.beg, g.size, (char*)g.name);
    res |= DescribeAddressRelativeToGlobal(addr, g);
  }
  return res;
}

// Register a global variable.
// This function may be called more than once for every global
// so we store the globals in a map.
static void RegisterGlobal(const Global *g) {
  CHECK(asan_inited);
  if (flags()->report_globals >= 2)
    Report("Added Global: beg=%p size=%zu/%zu name=%s dyn.init=%zu\n",
           (void*)g->beg, g->size, g->size_with_redzone, g->name,
           g->has_dynamic_init);
  CHECK(flags()->report_globals);
  CHECK(AddrIsInMem(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  PoisonRedZones(*g);
  ListOfGlobals *l =
      (ListOfGlobals*)allocator_for_globals.Allocate(sizeof(ListOfGlobals));
  l->g = g;
  l->next = list_of_all_globals;
  list_of_all_globals = l;
  if (g->has_dynamic_init) {
    l = (ListOfGlobals*)allocator_for_globals.Allocate(sizeof(ListOfGlobals));
    l->g = g;
    l->next = list_of_dynamic_init_globals;
    list_of_dynamic_init_globals = l;
  }
}

static void UnregisterGlobal(const Global *g) {
  CHECK(asan_inited);
  CHECK(flags()->report_globals);
  CHECK(AddrIsInMem(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  PoisonShadow(g->beg, g->size_with_redzone, 0);
  // We unpoison the shadow memory for the global but we do not remove it from
  // the list because that would require O(n^2) time with the current list
  // implementation. It might not be worth doing anyway.
}

// Poison all shadow memory for a single global.
static void PoisonGlobalAndRedzones(const Global *g) {
  CHECK(asan_inited);
  CHECK(flags()->check_initialization_order);
  CHECK(AddrIsInMem(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  if (flags()->report_globals >= 3)
    Printf("DynInitPoison  : %s\n", g->name);
  PoisonShadow(g->beg, g->size_with_redzone, kAsanInitializationOrderMagic);
}

static void UnpoisonGlobal(const Global *g) {
  CHECK(asan_inited);
  CHECK(flags()->check_initialization_order);
  CHECK(AddrIsInMem(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->beg));
  CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
  if (flags()->report_globals >= 3)
    Printf("DynInitUnpoison: %s\n", g->name);
  PoisonShadow(g->beg, g->size_with_redzone, 0);
  PoisonRedZones(*g);
}

}  // namespace __asan

// ---------------------- Interface ---------------- {{{1
using namespace __asan;  // NOLINT

// Register one global with a default redzone.
void __asan_register_global(uptr addr, uptr size,
                            const char *name) {
  if (!flags()->report_globals) return;
  ScopedLock lock(&mu_for_globals);
  Global *g = (Global *)allocator_for_globals.Allocate(sizeof(Global));
  g->beg = addr;
  g->size = size;
  g->size_with_redzone = GetAlignedSize(size) + kGlobalAndStackRedzone;
  g->name = name;
  RegisterGlobal(g);
}

// Register an array of globals.
void __asan_register_globals(__asan_global *globals, uptr n) {
  if (!flags()->report_globals) return;
  ScopedLock lock(&mu_for_globals);
  for (uptr i = 0; i < n; i++) {
    RegisterGlobal(&globals[i]);
  }
}

// Unregister an array of globals.
// We must do this when a shared objects gets dlclosed.
void __asan_unregister_globals(__asan_global *globals, uptr n) {
  if (!flags()->report_globals) return;
  ScopedLock lock(&mu_for_globals);
  for (uptr i = 0; i < n; i++) {
    UnregisterGlobal(&globals[i]);
  }
}

// This method runs immediately prior to dynamic initialization in each TU,
// when all dynamically initialized globals are unpoisoned.  This method
// poisons all global variables not defined in this TU, so that a dynamic
// initializer can only touch global variables in the same TU.
void __asan_before_dynamic_init(uptr first_addr, uptr last_addr) {
  if (!flags()->check_initialization_order) return;
  CHECK(list_of_dynamic_init_globals);
  ScopedLock lock(&mu_for_globals);
  bool from_current_tu = false;
  // The list looks like:
  // a => ... => b => last_addr => ... => first_addr => c => ...
  // The globals of the current TU reside between last_addr and first_addr.
  for (ListOfGlobals *l = list_of_dynamic_init_globals; l; l = l->next) {
    if (l->g->beg == last_addr)
      from_current_tu = true;
    if (!from_current_tu)
      PoisonGlobalAndRedzones(l->g);
    if (l->g->beg == first_addr)
      from_current_tu = false;
  }
  CHECK(!from_current_tu);
}

// This method runs immediately after dynamic initialization in each TU, when
// all dynamically initialized globals except for those defined in the current
// TU are poisoned.  It simply unpoisons all dynamically initialized globals.
void __asan_after_dynamic_init() {
  if (!flags()->check_initialization_order) return;
  ScopedLock lock(&mu_for_globals);
  for (ListOfGlobals *l = list_of_dynamic_init_globals; l; l = l->next)
    UnpoisonGlobal(l->g);
}


text:
package com.valuelogic.kubernetessample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class KubernetesSampleApplication {

	public static void main(String[] args) {
		SpringApplication.run(KubernetesSampleApplication.class, args);
	}

}


text:
package com.yoiojava.model;

import com.yoiojava.persistence.Database;
import com.yoiojava.persistence.DatabaseFactory;

/**
 * @author Yoio<Yoio@3cto.net>
 */
public class BaseDao {
	private Database db = DatabaseFactory.getDatabase();

	public Database setTableName(String tablename) {
		return db.setTableName(tablename);
	}

	protected Database getDatabase() {
		return db;
	}
}


text:
package com.example.cloudsql;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

@SuppressFBWarnings(
    value = {"SE_NO_SERIALVERSIONID", "WEM_WEAK_EXCEPTION_MESSAGING"},
    justification = "Not needed for IndexServlet, Exception adds context")
@WebServlet(name = "Index", value = "")
public class IndexServlet extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(IndexServlet.class.getName());

  TemplateData getTemplateData(DataSource pool) throws ServletException {
    try {
      return TemplateData.getTemplateData(pool);
    } catch (SQLException ex) {
      throw new ServletException(ex);
    }
  }

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    // Extract the pool from the Servlet Context, reusing the one that was created
    // in the ContextListener when the application was started
    DataSource pool = (DataSource) req.getServletContext().getAttribute("my-pool");

    TemplateData templateData = getTemplateData(pool);

    // Add variables and render the page
    req.setAttribute("tabCount", templateData.tabCount);
    req.setAttribute("spaceCount", templateData.spaceCount);
    req.setAttribute("recentVotes", templateData.recentVotes);
    req.getRequestDispatcher("/index.jsp").forward(req, resp);
  }

  @SuppressFBWarnings(
      value = {"SERVLET_PARAMETER", "XSS_SERVLET"},
      justification = "Input is validated and sanitized.")
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Get the team from the request and record the time of the vote.
    String team = Utils.validateTeam(req.getParameter("team"));
    Timestamp now = new Timestamp(new Date().getTime());
    if (team == null) {
      resp.setStatus(400);
      resp.getWriter().append("Invalid team specified.");
      return;
    }

    // Reuse the pool that was created in the ContextListener when the Servlet started.
    DataSource pool = (DataSource) req.getServletContext().getAttribute("my-pool");
    // [START cloud_sql_mysql_servlet_connection]
    // Using a try-with-resources statement ensures that the connection is always released back
    // into the pool at the end of the statement (even if an error occurs)
    try (Connection conn = pool.getConnection()) {

      // PreparedStatements can be more efficient and project against injections.
      String stmt = "INSERT INTO votes (time_cast, candidate) VALUES (?, ?);";
      try (PreparedStatement voteStmt = conn.prepareStatement(stmt);) {
        voteStmt.setTimestamp(1, now);
        voteStmt.setString(2, team);

        // Finally, execute the statement. If it fails, an error will be thrown.
        voteStmt.execute();
      }
    } catch (SQLException ex) {
      // If something goes wrong, handle the error in this section. This might involve retrying or
      // adjusting parameters depending on the situation.
      // [START_EXCLUDE]
      LOGGER.log(Level.WARNING, "Error while attempting to submit vote.", ex);
      resp.setStatus(500);
      resp.getWriter()
          .write(
              "Unable to successfully cast vote! Please check the application "
                  + "logs for more details.");
      // [END_EXCLUDE]
    }
    // [END cloud_sql_mysql_servlet_connection]

    resp.setStatus(200);
    resp.getWriter().printf("Vote successfully cast for '%s' at time %s!%n", team, now);
  }
}


text:
<?php

namespace Novosga\Model;

/**
 * @Entity
 * @Table(name="cargos_mod_perm")
 */
class Permissao extends Model implements \JsonSerializable
{
    /**
     * @Id
     * @ManyToOne(targetEntity="Modulo")
     * @JoinColumn(name="modulo_id", referencedColumnName="id")
     */
    protected $modulo;

    /**
     * @Id
     * @ManyToOne(targetEntity="Cargo")
     * @JoinColumn(name="cargo_id", referencedColumnName="id")
     */
    protected $cargo;

    /**
     * @Column(type="integer", name="permissao", nullable=false)
     */
    protected $permissao;

    public function __construct()
    {
    }

    /**
     * Define o modulo ao qual a permissão se refere.
     *
     * @param Modulo $modulo
     */
    public function setModulo(Modulo $modulo)
    {
        $this->modulo = $modulo;
    }

    /**
     * Retorna o modulo ao qual esta permissão se refere.
     *
     * @return Modulo
     */
    public function getModulo()
    {
        return $this->modulo;
    }

    public function getCargo()
    {
        return $this->cargo;
    }

    public function setCargo($cargo)
    {
        $this->cargo = $cargo;
    }

    public function getPermissao()
    {
        return $this->permissao;
    }

    public function setPermissao($permissao)
    {
        $this->permissao = $permissao;
    }

    public function jsonSerialize()
    {
        return [
            'cargo'     => $this->getCargo(),
            'modulo'    => $this->getModulo(),
            'permissao' => $this->getPermissao(),
        ];
    }
}


text:
package pl.java.scalatech.annotation;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target(value=FIELD)
@Retention(RUNTIME)
@Documented
public @interface AmountFormat {

}


text:
"""
Copyright 2016-present Tony Peng

Load a trained feed-forward model to stylize an image.
"""

import nets
import numpy as np
import tensorflow as tf
import utils
import time

MODEL_PATH = 'models/trained/WhiteLine'
CONTENT_IMAGE_PATH = 'runs/WhiteLine/WorldTradeCenter.jpg'
OUTPUT_IMAGE_PATH = 'runs/WhiteLine/WorldTradeCenterStyled.jpg'

content_image = utils.read_image(CONTENT_IMAGE_PATH)

with tf.Session() as sess:
    x = tf.placeholder(tf.float32, shape=(1, ) + content_image.shape)
    stylzr = nets.stylzr(x)

    # load the model
    model = tf.train.latest_checkpoint(MODEL_PATH)
    saver = tf.train.Saver()
    saver.restore(sess, model)

    # evaluate!
    start_time = time.time()
    styled_image = stylzr.eval(feed_dict={x: np.array([content_image])})
    print("eval: "+str(time.time() - start_time)+"s")
    styled_image = styled_image.reshape(styled_image.shape[1:])
    utils.write_image(styled_image, OUTPUT_IMAGE_PATH)


text:
package org.dcm4cheri.auditlog;

import org.dcm4che.auditlog.InstancesAction;

/**
 * <description>
 *
 * @see <related>
 * @author  gunter zeilinger
 * @version $Revision: 3922 $ $Date: 2005-10-06 00:26:16 +0800 (周四, 06 10月 2005) $
 * @since August 27, 2002
 *
 *
Revisions:
 *
 *
yyyymmdd author:
 *

 *
 explicit fix description (no line numbers but methods) go
 *            beyond the cvs commit message
 *

 */
class StudyDeleted implements IHEYr4.Message {

    // Constants -----------------------------------------------------

    // Variables -----------------------------------------------------
    private InstancesAction instancesAction;

    private final String desc;

    // Constructors --------------------------------------------------
    public StudyDeleted(InstancesAction instancesAction, String desc) {
        this.instancesAction = instancesAction;
        this.desc = desc;
    }

    // Methods -------------------------------------------------------
    public void writeTo(StringBuffer sb) {
        sb.append("<StudyDeleted>");
        instancesAction.writeTo(sb);
        if (desc != null)
            sb.append("<Description><![CDATA[").append(desc)
            	.append("]]></Description>");
        sb.append("</StudyDeleted>");
    }

}


text:
/*------------------------------------------------------------------------
	- HTML Table Filter Generator
	- Fixed headers feature v1.0 - Deprecated!
	- By Max Guglielmi (tablefilter.free.fr)
	- Licensed under the MIT License
-------------------------------------------------------------------------*/

TF.prototype.SetFixedHeaders = function()
/*====================================================
	- CSS solution making headers fixed
=====================================================*/
{
	if((!this.hasGrid && !this.isFirstLoad) || !this.fixedHeaders) return;
	if(this.contDiv) return;
	var thead = tf_Tag(this.tbl,'thead');
	if( thead.length==0 ) return;
	var tbody = tf_Tag(this.tbl,'tbody');
	if( tbody[0].clientHeight!=0 )
	{//firefox returns tbody height
		//previous values
		this.prevTBodyH = tbody[0].clientHeight;
		this.prevTBodyOverflow = tbody[0].style.overflow;
		this.prevTBodyOverflowX = tbody[0].style.overflowX;

		tbody[0].style.height = this.tBodyH+'px';
		tbody[0].style.overflow = 'auto';
		tbody[0].style.overflowX = 'hidden';
	} else { //IE returns 0
		// cont div is added to emulate fixed headers behaviour
		var contDiv = tf_CreateElm( 'div',['id',this.prfxContentDiv+this.id] );
		contDiv.className = this.contDivCssClass;
		this.tbl.parentNode.insertBefore(contDiv, this.tbl);
		contDiv.appendChild(this.tbl);
		this.contDiv = tf_Id(this.prfxContentDiv+this.id);
		//prevents headers moving during window scroll (IE)
		this.contDiv.style.position = 'relative';

		var theadH = 0;
		var theadTr = tf_Tag(thead[0],'tr');
		for(var i=0; i<theadTr.length; i++)
		{//css below emulates fixed headers on IE<=6
			theadTr[i].style.cssText += 'position:relative; ' +
										'top:expression(offsetParent.scrollTop);';
			theadH += parseInt(theadTr[i].clientHeight);
		}

		this.contDiv.style.height = (this.tBodyH+theadH)+'px';

		var tfoot = tf_Tag(this.tbl,'tfoot');
		if( tfoot.length==0 ) return;

		var tfootTr = tf_Tag(tfoot[0],'tr');

		for(var j=0; j<tfootTr.length; j++)//css below emulates fixed footer on IE<=6
			tfootTr[j].style.cssText += 'position:relative; overflow-x: hidden; ' +
										'top: expression(parentNode.parentNode.offsetHeight >= ' +
										'offsetParent.offsetHeight ? 0 - parentNode.parentNode.offsetHeight + '+
										'offsetParent.offsetHeight + offsetParent.scrollTop : 0);';
	}
}

TF.prototype.RemoveFixedHeaders = function()
/*====================================================
	- Removes fixed headers
=====================================================*/
{
	if(!this.hasGrid || !this.fixedHeaders ) return;
	if( this.contDiv )//IE additional div
	{
		this.contDiv.parentNode.insertBefore(this.tbl, this.contDiv);
		this.contDiv.parentNode.removeChild( this.contDiv );
		this.contDiv = null;
		var thead = tf_Tag(this.tbl,'thead');
		if( thead.length==0 ) return;
		var theadTr = tf_Tag(thead[0],'tr');
		if( theadTr.length==0 ) return;
		for(var i=0; i<theadTr.length; i++)
			theadTr[i].style.cssText = '';
		var tfoot = tf_Tag(this.tbl,'tfoot');
		if( tfoot.length==0 ) return;
		var tfootTr = tf_Tag(tfoot[0],'tr');
		for(var j=0; j<tfootTr.length; j++)
		{
			tfootTr[j].style.position = 'relative';
			tfootTr[j].style.top = '';
			tfootTr[j].style.overeflowX = '';
		}
	} else {
		var tbody = tf_Tag(this.tbl,'tbody');
		if( tbody.length==0 ) return;
		tbody[0].style.height = this.prevTBodyH+'px';
		tbody[0].style.overflow = this.prevTBodyOverflow;
		tbody[0].style.overflowX = this.prevTBodyOverflowX;
	}
}


text:
/*
 * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.nio.file;

import java.util.Iterator;
import java.io.Closeable;
import java.io.IOException;

/**
 * An object to iterate over the entries in a directory. A directory stream
 * allows for the convenient use of the for-each construct to iterate over a
 * directory.
 *
 *
  While {@code DirectoryStream} extends {@code Iterable}, it is not a
 * general-purpose {@code Iterable} as it supports only a single {@code
 * Iterator}; invoking the {@link #iterator iterator} method to obtain a second
 * or subsequent iterator throws {@code IllegalStateException}.
 *
 *
 An important property of the directory stream's {@code Iterator} is that
 * its {@link Iterator#hasNext() hasNext} method is guaranteed to read-ahead by
 * at least one element. If {@code hasNext} method returns {@code true}, and is
 * followed by a call to the {@code next} method, it is guaranteed that the
 * {@code next} method will not throw an exception due to an I/O error, or
 * because the stream has been {@link #close closed}. The {@code Iterator} does
 * not support the {@link Iterator#remove remove} operation.
 *
 *
 A {@code DirectoryStream} is opened upon creation and is closed by
 * invoking the {@code close} method. Closing a directory stream releases any
 * resources associated with the stream. Failure to close the stream may result
 * in a resource leak. The try-with-resources statement provides a useful
 * construct to ensure that the stream is closed:
 *

 *   Path dir = ...
 *   try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
 *       for (Path entry: stream) {
 *           ...
 *       }
 *   }
 *

 *
 *
 Once a directory stream is closed, then further access to the directory,
 * using the {@code Iterator}, behaves as if the end of stream has been reached.
 * Due to read-ahead, the {@code Iterator} may return one or more elements
 * after the directory stream has been closed. Once these buffered elements
 * have been read, then subsequent calls to the {@code hasNext} method returns
 * {@code false}, and subsequent calls to the {@code next} method will throw
 * {@code NoSuchElementException}.
 *
 *
 A directory stream is not required to be asynchronously closeable.
 * If a thread is blocked on the directory stream's iterator reading from the
 * directory, and another thread invokes the {@code close} method, then the
 * second thread may block until the read operation is complete.
 *
 *
 If an I/O error is encountered when accessing the directory then it
 * causes the {@code Iterator}'s {@code hasNext} or {@code next} methods to
 * throw {@link DirectoryIteratorException} with the {@link IOException} as the
 * cause. As stated above, the {@code hasNext} method is guaranteed to
 * read-ahead by at least one element. This means that if {@code hasNext} method
 * returns {@code true}, and is followed by a call to the {@code next} method,
 * then it is guaranteed that the {@code next} method will not fail with a
 * {@code DirectoryIteratorException}.
 *
 *
 The elements returned by the iterator are in no specific order. Some file
 * systems maintain special links to the directory itself and the directory's
 * parent directory. Entries representing these links are not returned by the
 * iterator.
 *
 *
 The iterator is weakly consistent. It is thread safe but does not
 * freeze the directory while iterating, so it may (or may not) reflect updates
 * to the directory that occur after the {@code DirectoryStream} is created.
 *
 *
 Usage Examples:
 * Suppose we want a list of the source files in a directory. This example uses
 * both the for-each and try-with-resources constructs.
 *

 *   List<Path> listSourceFiles(Path dir) throws IOException {
 *       List<Path> result = new ArrayList<>();
 *       try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) {
 *           for (Path entry: stream) {
 *               result.add(entry);
 *           }
 *       } catch (DirectoryIteratorException ex) {
 *           // I/O error encounted during the iteration, the cause is an IOException
 *           throw ex.getCause();
 *       }
 *       return result;
 *   }
 *

 * @param   <T>     The type of element returned by the iterator
 *
 * @since 1.7
 *
 * @see Files#newDirectoryStream(Path)
 */

public interface DirectoryStream<T>
    extends Closeable, Iterable<T> {
    /**
     * An interface that is implemented by objects that decide if a directory
     * entry should be accepted or filtered. A {@code Filter} is passed as the
     * parameter to the {@link Files#newDirectoryStream(Path,DirectoryStream.Filter)}
     * method when opening a directory to iterate over the entries in the
     * directory.
     *
     * @param   <T>     the type of the directory entry
     *
     * @since 1.7
     */
    @FunctionalInterface
    public static interface Filter<T> {
        /**
         * Decides if the given directory entry should be accepted or filtered.
         *
         * @param   entry
         *          the directory entry to be tested
         *
         * @return  {@code true} if the directory entry should be accepted
         *
         * @throws  IOException
         *          If an I/O error occurs
         */
        boolean accept(T entry) throws IOException;
    }

    /**
     * Returns the iterator associated with this {@code DirectoryStream}.
     *
     * @return  the iterator associated with this {@code DirectoryStream}
     *
     * @throws  IllegalStateException
     *          if this directory stream is closed or the iterator has already
     *          been returned
     */
    @Override
    Iterator<T> iterator();
}


text:
package com.github.bogdanlivadariu.screenshotwatcher.models.config;

public class ScreenshotWatcherConfigurationModel {

    private String hostAddress;

    private int portPreference;

    private String mongoDBHost;

    private int mongoDBPort;

    private String mongoDBUserName;

    private String mongoDBPassword;

    private String mongoDB;

    public String getHostAddress() {
        return hostAddress;
    }

    public int getPortPreference() {
        return portPreference;
    }

    public String getMongoDBHost() {
        return mongoDBHost;
    }

    public int getMongoDBPort() {
        return mongoDBPort;
    }

    public String getMongoDBUserName() {
        return mongoDBUserName;
    }

    public String getMongoDBPassword() {
        return mongoDBPassword;
    }

    public String getMongoDB() {
        return mongoDB;
    }

}


text:
package com.vsked.test;

public class GlobalSet {

	// appid, secretid secretkey请到http://open.youtu.qq.com/获取
	// 请正确填写把下面的APP_ID、SECRET_ID和SECRET_KEY
	public static final String APP_ID = "10008975";
	public static final String SECRET_ID = "AKID1vdBXigT3ThmfMn8DYjiW8YpurDPqCnC";
	public static final String SECRET_KEY = "KSRIxSmxwjKiy2tZ5RbZKyVt782kFYfZ";
	public static final String USER_ID = "hyfdcompany";
}


text:
package org.fusesource.fabric.stream.log;

import org.apache.camel.*;
import org.apache.camel.impl.DefaultComponent;
import org.apache.camel.impl.DefaultConsumer;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.impl.DefaultMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *

 *

 *
 * @author Hiram Chirino
 */
public class InputBatcher extends DefaultComponent {

    private static final transient Logger LOG = LoggerFactory.getLogger(InputBatcherConsumer.class);

    public int batchSize = 1024*256;
    public long batchTimeout = 1000;
    public InputStream is = System.in;

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        return new InputBatcherEndpoint(uri, this);
    }

    class InputBatcherEndpoint extends DefaultEndpoint {

        InputBatcherEndpoint(String endpointUri, Component component) {
            super(endpointUri, component);
        }

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

        @Override
        public Producer createProducer() throws Exception {
            throw new UnsupportedOperationException("Producer not supported!");
        }

        @Override
        public Consumer createConsumer(Processor processor) throws Exception {
            return new InputBatcherConsumer(this, processor);
        }

    }

    static final Object EOF = new Object();

    class InputBatcherConsumer extends DefaultConsumer {

        final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1024);

        final ExecutorService inputReader = Executors.newSingleThreadExecutor();
        final ExecutorService batchReader = Executors.newSingleThreadExecutor();
        private AsyncProcessor processor;

        InputBatcherConsumer(Endpoint endpoint, Processor processor) {
            super(endpoint, processor);
        }

        @Override
        protected void doStart() throws Exception {
            super.doStart();

            //
            // Start a thread which reads stdin and passes the data in big byte[] chunks
            // aligned at \n boundaries to an ArrayBlockingQueue
            //
            inputReader.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        byte batch[] = new byte[4*1024];
                        int pos = 0;
                        while(isRunAllowed()) {
                            // do not poll if we are suspended
                            if (isSuspending() || isSuspended()) {
                                LOG.trace("Consumer is suspended so skip polling");
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    LOG.debug("Sleep interrupted, are we stopping? {}", isStopping() || isStopped());
                                }
                                continue;
                            }

                            int count = is.read(batch, pos, batch.length - pos);
                            if( count < 0  ) {
                                if( pos > 0 ) {
                                    byte[] data = new byte[pos];
                                    System.arraycopy(batch, 0, data, 0, pos);
                                    queue.put(data);
                                }
                                queue.put(EOF);
                                return;
                            } else {
                                pos += count;
                                int at = lastnlposition(batch, pos);
                                if( at >= 0 ) {
                                    int len = at+1;
                                    byte[] data = new byte[len];
                                    System.arraycopy(batch, 0, data, 0, len);
                                    int remaining = pos-len;
                                    System.arraycopy(batch, len, batch, 0,  remaining);
                                    pos = remaining;
//                                    System.err.println("Queued "+len+" bytes");
                                    queue.put(data);
                                } else if (pos == batch.length) {
                                    // no nl found in the 4k read so far.. pass it along.
                                    // only other alternative is to drop it and that's not so good.
//                                    System.err.println("queuing "+pos+" data, but no nl was in it");
                                    queue.put(batch);
                                    batch = new byte[4*1024];
                                    pos = 0;
                                } else {
//                                    System.err.println("at "+pos+" but no nl yet");
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            // In another thread
            batchReader.execute(new Runnable() {
                @Override
                public void run() {
                    boolean atEOF = false;
                    // loop while we are allowed, or if we are stopping loop until the queue is empty
                    while (isRunAllowed() && !atEOF) {
                        // do not poll if we are suspended
                        if (isSuspending() || isSuspended()) {
                            LOG.trace("Consumer is suspended so skip polling");
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                LOG.debug("Sleep interrupted, are we stopping? {}", isStopping() || isStopped());
                            }
                            continue;
                        }

                        ByteArrayOutputStream batch = new ByteArrayOutputStream((int) (batchSize*1.5));
                        try {
                            Object obj = queue.poll(1000, TimeUnit.MILLISECONDS);
                            if (obj != null) {

                                // we are done.
                                if(obj == EOF) {
                                    atEOF = true;
                                    continue;
                                }

                                //starting a new batch..
                                long start = System.currentTimeMillis();
                                long timeout = start + batchTimeout;
                                try {

//                                    System.err.println("batch start, size: "+batch.size());
                                    batch.write((byte[]) obj);

                                    // Fill in the rest of the batch up to the batch size or the batch timeout.
                                    while(batch.size() < batchSize && !atEOF) {
                                        obj = queue.poll();
                                        if( obj!=null ) {
                                            if(obj == EOF) {
                                                atEOF = true;
                                            } else {
//                                                System.err.println("batch add, size: "+batch.size());
                                                batch.write((byte[]) obj);
                                            }
                                        } else {
                                            // gonna have to poll with a timeout..
                                            long remaining = timeout - System.currentTimeMillis();
                                            if( remaining > 0 ) {
//                                                System.err.println("batch waiting "+remaining);
                                                obj = queue.poll(remaining, TimeUnit.MILLISECONDS);
                                                if( obj!=null ) {
                                                    if(obj == EOF) {
                                                        atEOF = true;
                                                    } else {
                                                        batch.write((byte[]) obj);
                                                    }
                                                    continue;
                                                }
                                                // else timeout..
                                            }
                                            // timeout.
//                                            System.err.println("batch poll timeout");
                                            break;
                                        }
                                    }

                                    if(batch.size() > 0 ) {

                                        byte[] body = batch.toByteArray();
                                        batch.reset();

                                        Exchange exchange = getEndpoint().createExchange();
                                        Message msg = new DefaultMessage();
                                        msg.setBody(body);
                                        exchange.setIn(msg);

                                        try {
//                                            System.err.println("sending: "+body.length);
                                            getProcessor().process(exchange);
//                                            System.err.println("sent");

                                            if (exchange.getException() != null) {
                                                getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
                                            }
                                        } catch (Exception e) {
                                            getExceptionHandler().handleException("Error processing exchange", exchange, e);
                                        }
                                    }

                                } catch (Exception e) {
                                    LOG.info("Error processing exchange.", e);
                                }
                            }
                        } catch (InterruptedException e) {
                            LOG.debug("Sleep interrupted, are we stopping? {}", isStopping() || isStopped());
                            continue;
                        }
                    }

                    if( atEOF && isRunAllowed() ) {

                        // Send an exchange to signal the end of the stream.
                        Exchange exchange = getEndpoint().createExchange();
                        Message msg = new DefaultMessage();
                        msg.setHeader("EOF", "true");
                        msg.setBody(new byte[0]);
                        exchange.setIn(msg);

                        try {
//                            System.err.println("Sending EOF signal");
                            getProcessor().process(exchange);
                            if (exchange.getException() != null) {
                                getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
                            }
                        } catch (Exception e) {
                            getExceptionHandler().handleException("Error processing exchange", exchange, e);
                        }

                        // we are done processing... lets exit cleanly.
//                        System.err.println("EOF reached shutting down.");
                        System.exit(0);
                    }
                }
            });
        }

        @Override
        protected void doStop() throws Exception {
            inputReader.shutdown();
            batchReader.shutdown();
            super.doStop();
        }

    }

    private static int lastnlposition(byte[] data, int len) {
        // have we received an entire log line yet?
        int at = -1;
        for(int i=len-1; i >= 0; i--) {
            if(data[i] == '\n') {
                at = i;
                break;
            }
        }
        return at;
    }

    public int getBatchSize() {
        return batchSize;
    }

    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    public long getBatchTimeout() {
        return batchTimeout;
    }

    public void setBatchTimeout(long batchTimeout) {
        this.batchTimeout = batchTimeout;
    }

    public InputStream getIs() {
        return is;
    }

    public void setIs(InputStream is) {
        this.is = is;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2020 The Android Open Source Project

  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.
   -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="red_style_name" msgid="3422019812492418917">"Rød farvestil"</string>
    <string name="green_style_name" msgid="1807715891527319248">"Grøn farvestil"</string>
    <string name="colors_style_setting" msgid="7410336396317170889">"Farver"</string>
    <string name="colors_style_setting_description" msgid="4961811355700378894">"Urskivens farvetema"</string>
    <string name="colors_style_red" msgid="1284998271677973320">"Rød"</string>
    <string name="colors_style_green" msgid="1327609154689015139">"Grøn"</string>
    <string name="colors_style_blue" msgid="8619157586474982343">"Blå"</string>
    <string name="watchface_pips_setting" msgid="486515623723087644">"Timemarkører"</string>
    <string name="watchface_pips_setting_description" msgid="651887190185401130">"Om der skal tegnes"</string>
    <string name="watchface_hand_length_setting" msgid="7998526424509601034">"Længde på viserne"</string>
    <string name="watchface_hand_length_setting_description" msgid="9060532706860425059">"Målestok for visere"</string>
    <string name="watchface_complications_setting" msgid="7605635862096204587">"Widgets"</string>
    <string name="watchface_complications_setting_description" msgid="3565604049641117847">"Antal og lokation"</string>
    <string name="watchface_complications_setting_both" msgid="1869848592349112126">"Begge"</string>
    <string name="watchface_complications_setting_none" msgid="722694346696596744">"Ingen"</string>
    <string name="watchface_complications_setting_left" msgid="1623162625339223972">"Venstre"</string>
    <string name="watchface_complications_setting_right" msgid="3310633126129770902">"Højre"</string>
</resources>


text:
libav_package
=============

lib av tools


text:
using System;

namespace MatterHackers.Agg.UI
{
	public static class Clipboard
	{
		private static ISystemClipboard clipboard { get; set; }

		public static bool IsInitialized
		{
			get { return clipboard != null; }
		}

		public static String GetText()
		{
			return clipboard.GetText();
		}

		public static void SetText(string text)
		{
			if (text != null && text != "")
			{
				clipboard.SetText(text);
			}
		}

		public static bool ContainsText()
		{
			return clipboard.ContainsText();
		}

		public static void SetSystemClipboard(ISystemClipboard clipBoard)
		{
			clipboard = clipBoard;
		}
	}
}


text:
package AST;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.io.File;
import java.util.*;
import beaver.*;
import java.util.ArrayList;
import java.util.zip.*;
import java.io.*;
import java.util.Stack;
import java.util.regex.Pattern;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.xml.transform.TransformerException;
import javax.xml.parsers.ParserConfigurationException;
import java.util.Collection;

/**
 * @ast node
 * @declaredat java.ast:110
 */
public abstract class AssignMultiplicativeExpr extends AssignExpr implements Cloneable {
  /**
   * @apilvl low-level
   */
  public void flushCache() {
    super.flushCache();
  }
  /**
   * @apilvl internal
   */
  public void flushCollectionCache() {
    super.flushCollectionCache();
  }
  /**
   * @apilvl internal
   */
  @SuppressWarnings({"unchecked", "cast"})
  public AssignMultiplicativeExpr clone() throws CloneNotSupportedException {
    AssignMultiplicativeExpr node = (AssignMultiplicativeExpr)super.clone();
    node.in$Circle(false);
    node.is$Final(false);
    return node;
  }
  /**
   * @ast method
   * @aspect TypeCheck
   * @declaredat D:\zhh\JastAddJ\Java1.4Frontend\TypeCheck.jrag:64
   */
  public void typeCheck() {
    if(sourceType().isBoolean()||getDest().type().isBoolean())
      error("Multiplicative operators do not operate on boolean types");
    super.typeCheck();
  }
  /**
   * @ast method
   * @declaredat java.ast:1
   */
  public AssignMultiplicativeExpr() {
    super();

  }
  /**
   * @ast method
   * @declaredat java.ast:7
   */
  public AssignMultiplicativeExpr(Expr p0, Expr p1) {
    setChild(p0, 0);
    setChild(p1, 1);
  }
  /**
   * @apilvl low-level
   * @ast method
   * @declaredat java.ast:14
   */
  protected int numChildren() {
    return 2;
  }
  /**
   * @apilvl internal
   * @ast method
   * @declaredat java.ast:20
   */
  public boolean mayHaveRewrite() {
    return false;
  }
  /**
   * Setter for Dest
   * @apilvl high-level
   * @ast method
   * @declaredat java.ast:5
   */
  public void setDest(Expr node) {
    setChild(node, 0);
  }
  /**
   * Getter for Dest
   * @apilvl high-level
   * @ast method
   * @declaredat java.ast:12
   */
  public Expr getDest() {
    return (Expr)getChild(0);
  }
  /**
   * @apilvl low-level
   * @ast method
   * @declaredat java.ast:18
   */
  public Expr getDestNoTransform() {
    return (Expr)getChildNoTransform(0);
  }
  /**
   * Setter for Source
   * @apilvl high-level
   * @ast method
   * @declaredat java.ast:5
   */
  public void setSource(Expr node) {
    setChild(node, 1);
  }
  /**
   * Getter for Source
   * @apilvl high-level
   * @ast method
   * @declaredat java.ast:12
   */
  public Expr getSource() {
    return (Expr)getChild(1);
  }
  /**
   * @apilvl low-level
   * @ast method
   * @declaredat java.ast:18
   */
  public Expr getSourceNoTransform() {
    return (Expr)getChildNoTransform(1);
  }
  /**
   * @apilvl internal
   */
  public ASTNode rewriteTo() {
    return super.rewriteTo();
  }
}


text:
package com.globant.labs.mood.service.mail.template.handlebars;

import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Template;
import com.globant.labs.mood.exception.TechnicalException;
import com.globant.labs.mood.model.mail.MailMessageTemplate;

import java.io.IOException;

/**
 * @author mauro.monti (monti.mauro@gmail.com)
 */
public class HBMMailMessageTemplate implements MailMessageTemplate {

    private Template template;

    public HBMMailMessageTemplate(final Template template) {
        this.template = template;
    }

    @Override
    public String eval(final Object context) {
        final Context hbmContext = Context.newContext(context);
        try {
            return this.template.apply(hbmContext);
        } catch (IOException e) {
            throw new TechnicalException("applying context to template.", e);
        }
    }
}


text:
#ifndef SIGNALSYNCHRONIZER_H
#define SIGNALSYNCHRONIZER_H

#include <QObject>

class SignalSynchronizer : public QObject
{
  Q_OBJECT
public:
  template <typename Iterator, typename Signal>
  SignalSynchronizer(Iterator begin,
                     Iterator end,
                     Signal signal,
                     QObject* parent = nullptr) :
    QObject(parent)
  {
    for (; begin != end; ++begin)
    {
      ++m_counter;
      QObject::connect(
          *begin, signal, this, &SignalSynchronizer::decrementCounter);
    }
  }

  Q_SIGNAL void ready(QPrivateSignal);

private:
  Q_SLOT void decrementCounter();
  unsigned int m_counter{0};
};

#endif // SIGNALSYNCHRONIZER_H