text:
"""Operations to work with the SDK chroot."""

from __future__ import print_function

import os
import uuid

from chromite.lib import constants
from chromite.lib import cros_build_lib
from chromite.lib import cros_logging as logging
from chromite.lib import cros_sdk_lib

class CreateArguments(object):
  """Value object to handle the chroot creation arguments."""

  def __init__(self, replace=False, bootstrap=False, use_image=True,
               chroot_path=None, cache_dir=None):
    """Create arguments init.

    Args:
      replace (bool): Whether an existing chroot should be deleted.
      bootstrap (bool): Whether to build the SDK from source.
      use_image (bool): Whether to mount the chroot on a loopback image or
        create it directly in a directory.
      chroot_path: Path to where the chroot should be reside.
      cache_dir: Alternative directory to use as a cache for the chroot.
    """
    self.replace = replace
    self.bootstrap = bootstrap
    self.use_image = use_image
    self.chroot_path = chroot_path
    self.cache_dir = cache_dir

  def GetArgList(self):
    """Get the list of the corresponding command line arguments.

    Returns:
      list - The list of the corresponding command line arguments.
    """
    args = []

    if self.replace:
      args.append('--replace')
    else:
      args.append('--create')

    if self.bootstrap:
      args.append('--bootstrap')

    if not self.use_image:
      args.append('--nouse-image')

    if self.cache_dir:
      args.extend(['--cache-dir', self.cache_dir])

    if self.chroot_path:
      args.extend(['--chroot', self.chroot_path])

    return args

class UpdateArguments(object):
  """Value object to handle the update arguments."""

  def __init__(self,
               build_source=False,
               toolchain_targets=None,
               toolchain_changed=False):
    """Update arguments init.

    Args:
      build_source (bool): Whether to build the source or use prebuilts.
      toolchain_targets (list): The list of build targets whose toolchains
        should be updated.
      toolchain_changed (bool): Whether a toolchain change has occurred. Implies
        build_source.
    """
    self.build_source = build_source or toolchain_changed
    self.toolchain_targets = toolchain_targets

  def GetArgList(self):
    """Get the list of the corresponding command line arguments.

    Returns:
      list - The list of the corresponding command line arguments.
    """
    args = []

    if self.build_source:
      args.append('--nousepkg')
    elif self.toolchain_targets:
      args.extend(['--toolchain_boards', ','.join(self.toolchain_targets)])

    return args

def Clean(chroot, images=False, sysroots=False, tmp=False):
  """Clean the chroot.

  See:
    cros clean -h

  Args:
    chroot: The chroot to clean.
    images (bool): Remove all built images.
    sysroots (bool): Remove all of the sysroots.
    tmp (bool): Clean the tmp/ directory.
  """
  if not images and not sysroots and not tmp:
    return

  cmd = ['cros', 'clean']
  if chroot:
    cmd.extend(['--sdk-path', chroot.path])
  if images:
    cmd.append('--images')
  if sysroots:
    cmd.append('--sysroots')
  if tmp:
    cmd.append('--chroot-tmp')

  cros_build_lib.run(cmd)

def Create(arguments):
  """Create or replace the chroot.

  Args:
    arguments (CreateArguments): The various arguments to create a chroot.

  Returns:
    int - The version of the resulting chroot.
  """
  cros_build_lib.AssertOutsideChroot()

  cmd = [os.path.join(constants.CHROMITE_BIN_DIR, 'cros_sdk')]
  cmd.extend(arguments.GetArgList())

  cros_build_lib.run(cmd)

  version = GetChrootVersion(arguments.chroot_path)
  if not arguments.replace:
    # Force replace scenarios. Only needed when we're not already replacing it.
    if not version:
      # Force replace when we can't get a version for a chroot that exists,
      # since something must have gone wrong.
      logging.notice('Replacing broken chroot.')
      arguments.replace = True
      return Create(arguments)
    elif not cros_sdk_lib.IsChrootVersionValid(arguments.chroot_path):
      # Force replace when the version is not valid, i.e. ahead of the chroot
      # version hooks.
      logging.notice('Replacing chroot ahead of current checkout.')
      arguments.replace = True
      return Create(arguments)
    elif not cros_sdk_lib.IsChrootDirValid(arguments.chroot_path):
      # Force replace when the permissions or owner are not correct.
      logging.notice('Replacing chroot with invalid permissions.')
      arguments.replace = True
      return Create(arguments)

  return GetChrootVersion(arguments.chroot_path)

def Delete(chroot=None):
  """Delete the chroot.

  Args:
    chroot (chroot_lib.Chroot): The chroot being deleted, or None for the
      default chroot.
  """
  # Manually remove the sysroots to reduce the time taken to delete the chroot.
  logging.info('Removing sysroots.')
  Clean(chroot, sysroots=True)

  # Delete the chroot itself.
  logging.info('Removing the SDK.')
  cmd = [os.path.join(constants.CHROMITE_BIN_DIR, 'cros_sdk'), '--delete']
  if chroot:
    cmd.extend(['--chroot', chroot.path])

  cros_build_lib.run(cmd)

  # Remove any images that were built.
  logging.info('Removing images.')
  Clean(chroot, images=True)

def Unmount(chroot=None):
  """Unmount the chroot.

  Args:
    chroot (chroot_lib.Chroot): The chroot being unmounted, or None for the
      default chroot.
  """
  logging.info('Unmounting the chroot.')
  cmd = [os.path.join(constants.CHROMITE_BIN_DIR, 'cros_sdk'), '--unmount']
  if chroot:
    cmd.extend(['--chroot', chroot.path])

  cros_build_lib.run(cmd)

def GetChrootVersion(chroot_path=None):
  """Get the chroot version.

  Args:
    chroot_path (str|None): The chroot path.

  Returns:
    int|None - The version of the chroot if the chroot is valid, else None.
  """
  if chroot_path:
    path = chroot_path
  elif cros_build_lib.IsInsideChroot():
    path = None
  else:
    path = constants.DEFAULT_CHROOT_PATH

  return cros_sdk_lib.GetChrootVersion(path)

def Update(arguments):
  """Update the chroot.

  Args:
    arguments (UpdateArguments): The various arguments for updating a chroot.

  Returns:
    int - The version of the chroot after the update.
  """
  # TODO: This should be able to be run either in or out of the chroot.
  cros_build_lib.AssertInsideChroot()

  cmd = [os.path.join(constants.CROSUTILS_DIR, 'update_chroot')]
  cmd.extend(arguments.GetArgList())

  # The sdk update uses splitdebug instead of separatedebug. Make sure
  # separatedebug is disabled and enable splitdebug.
  existing = os.environ.get('FEATURES', '')
  features = ' '.join((existing, '-separatedebug splitdebug')).strip()
  extra_env = {'FEATURES': features}

  cros_build_lib.run(cmd, extra_env=extra_env)

  return GetChrootVersion()

def CreateSnapshot(chroot=None, replace_if_needed=False):
  """Create a logical volume snapshot of a chroot.

  Args:
    chroot (chroot_lib.Chroot): The chroot to perform the operation on.
    replace_if_needed (bool): If true, will replace the existing chroot with
      a new one capable of being mounted as a loopback image if needed.

  Returns:
    str - The name of the snapshot created.
  """
  _EnsureSnapshottableState(chroot, replace=replace_if_needed)

  snapshot_token = str(uuid.uuid4())
  logging.info('Creating SDK snapshot with token ID: %s', snapshot_token)

  cmd = [
      os.path.join(constants.CHROMITE_BIN_DIR, 'cros_sdk'),
      '--snapshot-create',
      snapshot_token,
  ]
  if chroot:
    cmd.extend(['--chroot', chroot.path])

  cros_build_lib.run(cmd)

  return snapshot_token

def RestoreSnapshot(snapshot_token, chroot=None):
  """Restore a logical volume snapshot of a chroot.

  Args:
    snapshot_token (str): The name of the snapshot to restore. Typically an
      opaque generated name returned from `CreateSnapshot`.
    chroot (chroot_lib.Chroot): The chroot to perform the operation on.
  """
  # Unmount to clean up stale processes that may still be in the chroot, in
  # order to prevent 'device busy' errors from umount.
  Unmount(chroot)
  logging.info('Restoring SDK snapshot with ID: %s', snapshot_token)
  cmd = [
      os.path.join(constants.CHROMITE_BIN_DIR, 'cros_sdk'),
      '--snapshot-restore',
      snapshot_token,
  ]
  if chroot:
    cmd.extend(['--chroot', chroot.path])

  # '--snapshot-restore' will automatically remount the image after restoring.
  cros_build_lib.run(cmd)

def _EnsureSnapshottableState(chroot=None, replace=False):
  """Ensures that a chroot is in a capable state to create an LVM snapshot.

  Args:
    chroot (chroot_lib.Chroot): The chroot to perform the operation on.
    replace (bool): If true, will replace the existing chroot with a new one
      capable of being mounted as a loopback image if needed.
  """
  cmd = [
      os.path.join(constants.CHROMITE_BIN_DIR, 'cros_sdk'),
      '--snapshot-list',
  ]
  if chroot:
    cmd.extend(['--chroot', chroot.path])

  cache_dir = chroot.cache_dir if chroot else None
  chroot_path = chroot.path if chroot else None

  res = cros_build_lib.run(cmd, check=False, encoding='utf-8',
                           capture_output=True)

  if res.returncode == 0:
    return
  elif 'Unable to find VG' in res.stderr and replace:
    logging.warning('SDK was created with nouse-image which does not support '
                    'snapshots. Recreating SDK to support snapshots.')

    args = CreateArguments(
        replace=True,
        bootstrap=False,
        use_image=True,
        cache_dir=cache_dir,
        chroot_path=chroot_path)

    Create(args)
    return
  else:
    res.check_returncode()


text:
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;

[assembly: PreApplicationStartMethod(typeof(Heliar.ComponentModel.Composition.Web.Mvc.RequestScopedCompositionModule), "Register")]
namespace Heliar.ComponentModel.Composition.Web.Mvc
{
	/// <summary>
	/// HttpModule to assist with the disposal of MEF based per request scoped dependencies with MVC.
	/// </summary>
	public class RequestScopedCompositionModule : IHttpModule
	{
		/// <summary>
		/// Tracks whether the module has been initialized
		/// </summary>
		private static bool isInitialized;

		/// <summary>
		/// Registers the HttpModule.
		/// </summary>
		public static void Register()
		{
			if (!isInitialized)
			{
				isInitialized = true;
				DynamicModuleUtility.RegisterModule(typeof(RequestScopedCompositionModule));
			}
		}

		/// <summary>
		/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule" />.
		/// </summary>
		public void Dispose() { }

		/// <summary>
		/// Initializes a module and prepares it to handle requests. Wires an event handler to HttpApplication.EndRequest for disposal of
		/// the current request's CompositionContainer.
		/// </summary>
		/// <param name="context">An <see cref="T:System.Web.HttpApplication" /> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
		public void Init(HttpApplication context)
		{
			context.EndRequest += CompositionScopeDisposer.DisposeCompositionScope;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
// This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// http://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

using System.Reflection;
using Autofac.Util;

namespace Autofac.Core
{
    /// <summary>
    /// A property identified by name. When applied to a reflection-based
    /// component, the name will be matched against property names.
    /// </summary>
    public class NamedPropertyParameter : ConstantParameter
    {
        /// <summary>
        /// The name of the property.
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// Create a <see cref="NamedPropertyParameter"/> with the specified constant value.
        /// </summary>
        /// <param name="name">The name of the property.</param>
        /// <param name="value">The property value.</param>
        public NamedPropertyParameter(string name, object value)
            : base(value, pi => {
                PropertyInfo prop;
                return pi.TryGetDeclaringProperty(out prop) &&
                    prop.Name == name;
            })
        {
            Name = Enforce.ArgumentNotNullOrEmpty(name, "name");
        }
    }
}


text:
package com.irccloud.android;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.TypedValue;

public class ColorScheme {
    private static ColorScheme instance = new ColorScheme();

    public static ColorScheme getInstance() {
        return instance;
    }

    public static String getUserTheme() {
        String theme = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getString("theme", ColorScheme.defaultTheme());
        if(theme.equals("auto"))
            return getSystemDarkMode() ? "midnight" : "dawn";
        return theme;
    }

    public static int getIRCColor(int color, boolean background) {
        String s = ColorFormatter.COLOR_MAP[color];

        if(getInstance().isDarkTheme && !background) {
            if(ColorFormatter.DARK_FG_SUBSTITUTIONS.containsKey(s))
                s = ColorFormatter.DARK_FG_SUBSTITUTIONS.get(s);
        }

        return 0xff000000 + Integer.parseInt(s, 16);
    }

    public static int getTheme(String theme, boolean actionbar) {
        switch(theme) {
            case "dawn":
                return actionbar?R.style.dawn:R.style.dawnNoActionBar;
            case "dusk":
                return actionbar?R.style.dusk:R.style.duskNoActionBar;
            case "tropic":
                return actionbar?R.style.tropic:R.style.tropicNoActionBar;
            case "emerald":
                return actionbar?R.style.emerald:R.style.emeraldNoActionBar;
            case "sand":
                return actionbar?R.style.sand:R.style.sandNoActionBar;
            case "rust":
                return actionbar?R.style.rust:R.style.rustNoActionBar;
            case "orchid":
                return actionbar?R.style.orchid:R.style.orchidNoActionBar;
            case "ash":
                return actionbar?R.style.ash:R.style.ashNoActionBar;
            case "midnight":
                return actionbar?R.style.midnight:R.style.midnightNoActionBar;
            default:
                return getSystemDarkMode()?(actionbar?R.style.midnight:R.style.midnightNoActionBar):(actionbar?R.style.dawn:R.style.dawnNoActionBar);
        }
    }

    public static boolean getSystemDarkMode() {
        if(Build.VERSION.SDK_INT < 29) {
            PowerManager pm = (PowerManager)IRCCloudApplication.getInstance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
            return pm.isPowerSaveMode();
        } else {
            int currentNightMode = IRCCloudApplication.getInstance().getApplicationContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
            return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
        }
    }

    public static String defaultTheme() {
        return Build.VERSION.SDK_INT >= 29 ? "auto" : "dawn";
    }

    public static int getDialogTheme(String theme) {
        switch(theme) {
            case "dawn":
                return R.style.dawnDialog;
            case "dusk":
                return R.style.duskDialog;
            case "tropic":
                return R.style.tropicDialog;
            case "emerald":
                return R.style.emeraldDialog;
            case "sand":
                return R.style.sandDialog;
            case "rust":
                return R.style.rustDialog;
            case "orchid":
                return R.style.orchidDialog;
            case "ash":
                return R.style.ashDialog;
            case "midnight":
                return R.style.midnightDialog;
            default:
                return getSystemDarkMode()?R.style.midnightDialog:R.style.dawnDialog;
        }
    }

    public static int getDialogWhenLargeTheme(String theme) {
        switch(theme) {
            case "dawn":
                return R.style.dawnDialogWhenLarge;
            case "dusk":
                return R.style.duskDialogWhenLarge;
            case "tropic":
                return R.style.tropicDialogWhenLarge;
            case "emerald":
                return R.style.emeraldDialogWhenLarge;
            case "sand":
                return R.style.sandDialogWhenLarge;
            case "rust":
                return R.style.rustDialogWhenLarge;
            case "orchid":
                return R.style.orchidDialogWhenLarge;
            case "ash":
                return R.style.ashDialogWhenLarge;
            case "midnight":
                return R.style.midnightDialogWhenLarge;
            default:
                return getSystemDarkMode()?R.style.midnightDialogWhenLarge:R.style.dawnDialogWhenLarge;
        }
    }

    private static String[] light_nick_colors = {
            "b22222",
            "d2691e",
            "ff9166",
            "fa8072",
            "ff8c00",
            "228b22",
            "808000",
            "b7b05d",
            "8ebd2e",
            "2ebd2e",
            "82b482",
            "37a467",
            "57c8a1",
            "1da199",
            "579193",
            "008b8b",
            "00bfff",
            "4682b4",
            "1e90ff",
            "4169e1",
            "6a5acd",
            "7b68ee",
            "9400d3",
            "8b008b",
            "ba55d3",
            "ff00ff",
            "ff1493"
    };

    private static String dark_nick_colors[] = {
            "deb887",
            "ffd700",
            "ff9166",
            "fa8072",
            "ff8c00",
            "00ff00",
            "ffff00",
            "bdb76b",
            "9acd32",
            "32cd32",
            "8fbc8f",
            "3cb371",
            "66cdaa",
            "20b2aa",
            "40e0d0",
            "00ffff",
            "00bfff",
            "87ceeb",
            "339cff",
            "6495ed",
            "b2a9e5",
            "ff69b4",
            "da70d6",
            "ee82ee",
            "d68fff",
            "ff00ff",
            "ffb6c1"
    };

    public static String colorForNick(String nick, boolean isDarkTheme) {
        String colors[] = isDarkTheme ? dark_nick_colors : light_nick_colors;
        // Normalise a bit
        // typically ` and _ are used on the end alone
        String normalizedNick = nick.toLowerCase().replaceAll("[`_]+$", "");
        //remove |<anything> from the end
        normalizedNick = normalizedNick.replaceAll("\\|.*$", "");

        Double hash = 0.0;

        for (int i = 0; i < normalizedNick.length(); i++) {
            hash = ((int) normalizedNick.charAt(i)) + (double) ((int) (hash.longValue()) << 6) + (double) ((int) (hash.longValue()) << 16) - hash;
        }

        return colors[(int) Math.abs(hash.longValue() % colors.length)];
    }

    public void setThemeFromContext(Context ctx, String theme_name) {
        theme = theme_name;
        contentBackgroundColor = colorForAttribute(ctx, R.attr.contentBackgroundColor);
        messageTextColor = colorForAttribute(ctx, R.attr.messageTextColor);
        opersGroupColor = colorForAttribute(ctx, R.attr.opersGroupColor);
        ownersGroupColor = colorForAttribute(ctx, R.attr.ownersGroupColor);
        adminsGroupColor = colorForAttribute(ctx, R.attr.adminsGroupColor);
        opsGroupColor = colorForAttribute(ctx, R.attr.opsGroupColor);
        halfopsGroupColor = colorForAttribute(ctx, R.attr.halfopsGroupColor);
        voicedGroupColor = colorForAttribute(ctx, R.attr.voicedGroupColor);
        membersGroupColor = colorForAttribute(ctx, R.attr.membersGroupColor);
        opersHeadingColor = colorForAttribute(ctx, R.attr.opersHeadingColor);
        ownersHeadingColor = colorForAttribute(ctx, R.attr.ownersHeadingColor);
        adminsHeadingColor = colorForAttribute(ctx, R.attr.adminsHeadingColor);
        opsHeadingColor = colorForAttribute(ctx, R.attr.opsHeadingColor);
        halfopsHeadingColor = colorForAttribute(ctx, R.attr.halfopsHeadingColor);
        voicedHeadingColor = colorForAttribute(ctx, R.attr.voicedHeadingColor);
        membersHeadingColor = colorForAttribute(ctx, R.attr.membersHeadingColor);
        memberListTextColor = colorForAttribute(ctx, R.attr.memberListTextColor);
        memberListAwayTextColor = colorForAttribute(ctx, R.attr.memberListAwayTextColor);
        timestampColor = colorForAttribute(ctx, R.attr.timestampColor);
        darkBlueColor = colorForAttribute(ctx, R.attr.darkBlueColor);
        networkErrorBackgroundColor = colorForAttribute(ctx, R.attr.networkErrorBackgroundColor);
        networkErrorColor = colorForAttribute(ctx, R.attr.networkErrorColor);
        errorBackgroundColor = colorForAttribute(ctx, R.attr.errorBackgroundColor);
        statusBackgroundColor = colorForAttribute(ctx, R.attr.statusBackgroundColor);
        selfBackgroundColor = colorForAttribute(ctx, R.attr.selfBackgroundColor);
        highlightBackgroundColor = colorForAttribute(ctx, R.attr.highlightBackgroundColor);
        highlightTimestampColor = colorForAttribute(ctx, R.attr.highlightTimestampColor);
        noticeBackgroundColor = colorForAttribute(ctx, R.attr.noticeBackgroundColor);
        timestampBackgroundColor = colorForAttribute(ctx, R.attr.timestampBackgroundColor);
        newMsgsBackgroundColor = colorForAttribute(ctx, R.attr.newMsgsBackgroundColor);
        collapsedRowTextColor = colorForAttribute(ctx, R.attr.collapsedRowTextColor);
        collapsedRowNickColor = colorForAttribute(ctx, R.attr.collapsedRowNickColor);
        collapsedHeadingBackgroundColor = colorForAttribute(ctx, R.attr.collapsedHeadingBackgroundColor);
        navBarColor = colorForAttribute(ctx, R.attr.navBarColor);
        navBarHeadingColor = colorForAttribute(ctx, R.attr.navBarHeadingColor);
        navBarSubheadingColor = colorForAttribute(ctx, R.attr.navBarSubheadingColor);
        navBarBorderColor = colorForAttribute(ctx, R.attr.navBarBorderColor);
        textareaTextColor = colorForAttribute(ctx, R.attr.textareaTextColor);
        textareaBackgroundColor = colorForAttribute(ctx, R.attr.textareaBackgroundColor);
        linkColor = colorForAttribute(ctx, R.attr.linkColor);
        lightLinkColor = colorForAttribute(ctx, R.attr.lightLinkColor);
        serverBackgroundColor = colorForAttribute(ctx, R.attr.serverBackgroundColor);
        bufferBackgroundColor = colorForAttribute(ctx, R.attr.bufferBackgroundColor);
        unreadBorderColor = colorForAttribute(ctx, R.attr.unreadBorderColor);
        highlightBorderColor = colorForAttribute(ctx, R.attr.highlightBorderColor);
        networkErrorBorderColor = colorForAttribute(ctx, R.attr.networkErrorBorderColor);
        bufferTextColor = colorForAttribute(ctx, R.attr.bufferTextColor);
        inactiveBufferTextColor = colorForAttribute(ctx, R.attr.inactiveBufferTextColor);
        unreadBufferTextColor = colorForAttribute(ctx, R.attr.unreadBufferTextColor);
        selectedBufferTextColor = colorForAttribute(ctx, R.attr.selectedBufferTextColor);
        selectedBufferBackgroundColor = colorForAttribute(ctx, R.attr.selectedBufferBackgroundColor);
        bufferBorderColor = colorForAttribute(ctx, R.attr.bufferBorderColor);
        selectedBufferBorderColor = colorForAttribute(ctx, R.attr.selectedBufferBorderColor);
        backlogDividerColor = colorForAttribute(ctx, R.attr.backlogDividerColor);
        chatterBarTextColor = colorForAttribute(ctx, R.attr.chatterBarTextColor);
        chatterBarColor = colorForAttribute(ctx, R.attr.chatterBarColor);
        awayBarTextColor = colorForAttribute(ctx, R.attr.awayBarTextColor);
        awayBarColor = colorForAttribute(ctx, R.attr.awayBarColor);
        connectionBarTextColor = colorForAttribute(ctx, R.attr.connectionBarTextColor);
        connectionBarColor = colorForAttribute(ctx, R.attr.connectionBarColor);
        placeholderColor = colorForAttribute(ctx, R.attr.placeholderColor);
        unreadBlueColor = colorForAttribute(ctx, R.attr.unreadBlueColor);
        serverBorderColor = colorForAttribute(ctx, R.attr.serverBorderColor);
        failedServerBorderColor = colorForAttribute(ctx, R.attr.failedServerBorderColor);
        archivesHeadingTextColor = colorForAttribute(ctx, R.attr.archivesHeadingTextColor);
        archivedChannelTextColor = colorForAttribute(ctx, R.attr.archivedChannelTextColor);
        archivedBufferTextColor = colorForAttribute(ctx, R.attr.archivedBufferTextColor);
        selectedArchivesHeadingColor = colorForAttribute(ctx, R.attr.selectedArchivesHeadingColor);
        timestampTopBorderColor = colorForAttribute(ctx, R.attr.timestampTopBorderColor);
        timestampBottomBorderColor = colorForAttribute(ctx, R.attr.timestampBottomBorderColor);
        expandCollapseIndicatorColor = colorForAttribute(ctx, R.attr.expandCollapseIndicatorColor);
        bufferHighlightColor = colorForAttribute(ctx, R.attr.bufferHighlightColor);
        selectedBufferHighlightColor = colorForAttribute(ctx, R.attr.selectedBufferHighlightColor);
        archivedBufferHighlightColor = colorForAttribute(ctx, R.attr.archivedBufferHighlightColor);
        selectedArchivedBufferHighlightColor = colorForAttribute(ctx, R.attr.selectedArchivedBufferHighlightColor);
        selectedArchivedBufferBackgroundColor = colorForAttribute(ctx, R.attr.selectedArchivedBufferBackgroundColor);
        contentBorderColor = colorForAttribute(ctx, R.attr.contentBorderColor);
        bufferBorderDrawable = resourceForAttribute(ctx, R.attr.bufferBorderDrawable);
        serverBorderDrawable = resourceForAttribute(ctx, R.attr.serverBorderDrawable);
        selectedBorderDrawable = resourceForAttribute(ctx, R.attr.selectedBorderDrawable);
        collapsedBorderDrawable = resourceForAttribute(ctx, R.attr.collapsedBorderDrawable);
        bufferBackgroundDrawable = resourceForAttribute(ctx, R.attr.bufferBackgroundDrawable);
        serverBackgroundDrawable = resourceForAttribute(ctx, R.attr.serverBackgroundDrawable);
        selectedBackgroundDrawable = resourceForAttribute(ctx, R.attr.selectedBackgroundDrawable);
        lastSeenEIDBackgroundDrawable = resourceForAttribute(ctx, R.attr.lastSeenEIDBackgroundDrawable);
        socketclosedBackgroundDrawable = resourceForAttribute(ctx, R.attr.socketclosedBackgroundDrawable);
        timestampBackgroundDrawable = resourceForAttribute(ctx, R.attr.timestampBackgroundDrawable);
        actionBarDrawable = resourceForAttribute(ctx, R.attr.actionbarDrawable);
        colorControlNormal = colorForAttribute(ctx, R.attr.colorControlNormal);
        dialogBackgroundColor = colorForAttribute(ctx, R.attr.dialogBackgroundColor);
        windowBackgroundDrawable = resourceForAttribute(ctx, R.attr.windowBackgroundDrawable);
        row_opers_bg_drawable = resourceForAttribute(ctx, R.attr.row_opers_bg_drawable);
        row_owners_bg_drawable = resourceForAttribute(ctx, R.attr.row_owners_bg_drawable);
        row_admins_bg_drawable = resourceForAttribute(ctx, R.attr.row_admins_bg_drawable);
        row_ops_bg_drawable = resourceForAttribute(ctx, R.attr.row_ops_bg_drawable);
        row_halfops_bg_drawable = resourceForAttribute(ctx, R.attr.row_halfops_bg_drawable);
        row_voiced_bg_drawable = resourceForAttribute(ctx, R.attr.row_voiced_bg_drawable);
        row_members_bg_drawable = resourceForAttribute(ctx, R.attr.row_members_bg_drawable);
        codeSpanForegroundColor = colorForAttribute(ctx, R.attr.codeSpanForegroundColor);
        codeSpanBackgroundColor = colorForAttribute(ctx, R.attr.codeSpanBackgroundColor);
        statusBarColor = colorForAttribute(ctx, android.R.attr.statusBarColor);
        isDarkTheme = !theme.equals("dawn");
        selfTextColor = isDarkTheme?"ffffff":"142b43";
    }

    private int colorForAttribute(Context ctx, int attribute) {
        TypedValue v = new TypedValue();
        ctx.getTheme().resolveAttribute(attribute, v, true);
        return v.data;
    }

    private int resourceForAttribute(Context ctx, int attribute) {
        TypedValue v = new TypedValue();
        ctx.getTheme().resolveAttribute(attribute, v, true);
        return v.resourceId;
    }

    public int contentBackgroundColor;
    public int messageTextColor;
    public int opersGroupColor;
    public int ownersGroupColor;
    public int adminsGroupColor;
    public int opsGroupColor;
    public int halfopsGroupColor;
    public int voicedGroupColor;
    public int membersGroupColor;
    public int opersHeadingColor;
    public int ownersHeadingColor;
    public int adminsHeadingColor;
    public int opsHeadingColor;
    public int halfopsHeadingColor;
    public int voicedHeadingColor;
    public int membersHeadingColor;
    public int memberListTextColor;
    public int memberListAwayTextColor;
    public int timestampColor;
    public int darkBlueColor;
    public int networkErrorBackgroundColor;
    public int networkErrorColor;
    public int errorBackgroundColor;
    public int statusBackgroundColor;
    public int selfBackgroundColor;
    public int highlightBackgroundColor;
    public int highlightTimestampColor;
    public int noticeBackgroundColor;
    public int timestampBackgroundColor;
    public int newMsgsBackgroundColor;
    public int collapsedRowTextColor;
    public int collapsedRowNickColor;
    public int collapsedHeadingBackgroundColor;
    public int navBarColor;
    public int navBarHeadingColor;
    public int navBarSubheadingColor;
    public int navBarBorderColor;
    public int textareaTextColor;
    public int textareaBackgroundColor;
    public int linkColor;
    public int lightLinkColor;
    public int serverBackgroundColor;
    public int bufferBackgroundColor;
    public int unreadBorderColor;
    public int highlightBorderColor;
    public int networkErrorBorderColor;
    public int bufferTextColor;
    public int inactiveBufferTextColor;
    public int unreadBufferTextColor;
    public int selectedBufferTextColor;
    public int selectedBufferBackgroundColor;
    public int bufferBorderColor;
    public int selectedBufferBorderColor;
    public int backlogDividerColor;
    public int chatterBarTextColor;
    public int chatterBarColor;
    public int awayBarTextColor;
    public int awayBarColor;
    public int connectionBarTextColor;
    public int connectionBarColor;
    public int placeholderColor;
    public int unreadBlueColor;
    public int serverBorderColor;
    public int failedServerBorderColor;
    public int archivesHeadingTextColor;
    public int archivedChannelTextColor;
    public int archivedBufferTextColor;
    public int selectedArchivesHeadingColor;
    public int timestampTopBorderColor;
    public int timestampBottomBorderColor;
    public int expandCollapseIndicatorColor;
    public int bufferHighlightColor;
    public int selectedBufferHighlightColor;
    public int archivedBufferHighlightColor;
    public int selectedArchivedBufferHighlightColor;
    public int selectedArchivedBufferBackgroundColor;
    public int contentBorderColor;
    public int bufferBorderDrawable;
    public int serverBorderDrawable;
    public int selectedBorderDrawable;
    public int collapsedBorderDrawable;
    public int bufferBackgroundDrawable;
    public int serverBackgroundDrawable;
    public int selectedBackgroundDrawable;
    public int lastSeenEIDBackgroundDrawable;
    public int socketclosedBackgroundDrawable;
    public int timestampBackgroundDrawable;
    public int colorControlNormal;
    public int actionBarDrawable;
    public int dialogBackgroundColor;
    public int windowBackgroundDrawable;
    public int statusBarColor;
    public int row_opers_bg_drawable;
    public int row_owners_bg_drawable;
    public int row_admins_bg_drawable;
    public int row_ops_bg_drawable;
    public int row_halfops_bg_drawable;
    public int row_voiced_bg_drawable;
    public int row_members_bg_drawable;
    public String theme;
    public boolean isDarkTheme;
    public String selfTextColor;
    public int codeSpanForegroundColor;
    public int codeSpanBackgroundColor;
}


text:
package akka.contrib.persistence.mongodb

class ScalaDriverLoadSpec extends JournalLoadSpec(classOf[ScalaDriverPersistenceExtension],"official-scala-load")


text:
#include "stereo.h"

stereo::stereo(){
	std::cout << "Initialize stereo class" << std::endl;

}

stereo::~stereo(){

}

int stereo::initialize_intrinsic_distortion(std::string left_file, std::string right_file){
	//Get left information
	cv::FileStorage f_output_left(left_file, cv::FileStorage::READ);
	if (!f_output_left.isOpened()){
		std::cout << "Error opening left info " << std::endl;
		return 0;
	}

	f_output_left["Intrinsic"] >> intrinsic_matrix[0];
	f_output_left["Distortion"] >> distortion_vector[0];

	f_output_left.release();

	//Get right information
	cv::FileStorage f_output_right(right_file, cv::FileStorage::READ);

	if (!f_output_right.isOpened()){
		std::cout << "Error opening right info " << std::endl;
		return 0;
	}

	f_output_right["Intrinsic"] >> intrinsic_matrix[1];
	f_output_right["Distortion"] >> distortion_vector[1];

	f_output_right.release();

	return 1;
}

int stereo::initialize_stereo_parameters(std::string stereo_file){
	cv::FileStorage f_output_stereo(stereo_file, cv::FileStorage::READ);

	if (!f_output_stereo.isOpened()){
		std::cout << "Error : Cannot open stereo parameters " << std::endl;
		return 0;
	}
	f_output_stereo["R"] >> R;
	f_output_stereo["T"] >> T;
	f_output_stereo["E"] >> E;
	f_output_stereo["F"] >> F;
	f_output_stereo["R1"] >> R1;
	f_output_stereo["R2"] >> R2;
	f_output_stereo["P1"] >> P1;
	f_output_stereo["P2"] >> P2;
	f_output_stereo["Q"] >> Q;
	f_output_stereo.release();
	return 1;
}

void stereo::set_images(cv::Mat im_in, DIRECTIONS dir){
	if (dir == DIRECTIONS::LEFT){
		left_image = im_in;
	}
	else if (dir == DIRECTIONS::RIGHT){
		right_image = im_in;
	}
	else {
		std::cout << "ERROR direction specified is nonexistent, choose left or right" << std::endl;
	}
}

void stereo::set_points(imagePointVector vec_in, DIRECTIONS dir){
	if (dir == DIRECTIONS::LEFT){
		left_image_points = vec_in;
	}
	else if (dir == DIRECTIONS::RIGHT){
		right_image_points = vec_in;
	}
	else {
		std::cout << "ERROR direction specified is nonexistent, choose left or right" << std::endl;
	}

}

imagePointVector stereo::undistort_points(imagePointVector dist_points, DIRECTIONS dir){
	imagePointVector undistorted;
	if (dist_points.empty()){
		std::cout << "ERROR :Vector to be undistorted cannot be empty" << std::endl;
		return undistorted;
	}

	if (dir == DIRECTIONS::LEFT){
		cv::undistortPoints(dist_points, undistorted, intrinsic_matrix[0], distortion_vector[0], R1, P1);
	}
	else if (dir == DIRECTIONS::RIGHT){
		cv::undistortPoints(dist_points, undistorted, intrinsic_matrix[1], distortion_vector[1], R2, P2);
	}

	return undistorted;
}

std::vector<cv::Point3f> stereo::triangulation(imagePointVector left_pnts, imagePointVector right_pnts){

	set_points(left_pnts, DIRECTIONS::LEFT);
	set_points(right_pnts, DIRECTIONS::RIGHT);
	worldPointVector result = triangulation();

	return result;

}

std::vector<cv::Point3f> stereo::triangulation(){

	//Container to store final 3d pos
	worldPointVector solution_container;

	int number_points;
	if ((left_image_points.size() == right_image_points.size())
		&& !right_image_points.empty()
		&& !left_image_points.empty()){
		number_points = left_image_points.size();
	}
	else {
		std::cout << "ERROR : ensure that left and right points are the same size . " << std::endl;
		return solution_container;

	}

	/*First we have to undistort the points*/
	left_image_points = undistort_points(left_image_points, DIRECTIONS::LEFT);
	right_image_points = undistort_points(right_image_points, DIRECTIONS::RIGHT);

	for (int counter = 0; counter < number_points; counter++){

		imagePointVector left_temp, right_temp;
		left_temp.push_back(left_image_points[counter]);
		right_temp.push_back(right_image_points[counter]);

		cv::Mat homogeneous_output;
		cv::triangulatePoints(P1, P2, (left_temp), (right_temp), homogeneous_output);

		//Change from homogeneous to non homogeneous
		cv::Vec4f euclidean_output = homogeneous_output.col(0);

		euclidean_output[0] /= euclidean_output[3];
		euclidean_output[1] /= euclidean_output[3];
		euclidean_output[2] /= euclidean_output[3];

		solution_container.push_back(cv::Point3f(euclidean_output[0], euclidean_output[1], euclidean_output[2]));

	}

	return solution_container;

}

void stereo::set_roi(cv::Mat input_image,DIRECTIONS dir){
	if (dir == DIRECTIONS::LEFT){
		roi_left = cv::selectROI(input_image, true);
	}
	else if (dir == DIRECTIONS::RIGHT){
		roi_right = cv::selectROI(input_image, true);
	}
}


text:
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace OCM.API.OutputProviders
{
    public class XMLOutputProvider : OutputProviderBase, IOutputProvider
    {
        public XMLOutputProvider()
        {
            ContentType = "text/xml";
        }

        public Task GetOutput(HttpContext context, System.IO.Stream outputStream, IEnumerable<Common.Model.ChargePoint> dataList, Common.APIRequestParams settings)
        {
            bool isVerboseMode = settings.IsVerboseOutput;

            XmlTextWriter xml = new XmlTextWriter(outputStream, Encoding.UTF8);

            //start xml document
            xml.WriteStartDocument();
            xml.WriteStartElement("ChargePoints");

            foreach (var item in dataList)
            {
                xml.WriteStartElement("ChargePoint");
                xml.WriteAttributeString("ID", item.ID.ToString());
                xml.WriteAttributeString("UUID", item.UUID.ToString());
                xml.WriteAttributeString("DateLastConfirmed", item.DateLastConfirmed.ToString());
                if (item.OperatorInfo != null)
                {
                    xml.WriteAttributeString("OperatorID", item.OperatorInfo.ID.ToString());
                    if (isVerboseMode)
                    {
                        xml.WriteAttributeString("OperatorTitle", item.OperatorInfo.Title.ToString());
                    }
                }
                if (item.DataProvider != null) xml.WriteAttributeString("DataProviderID", item.DataProvider.ID.ToString());
                xml.WriteAttributeString("NumberOfPoints", item.NumberOfPoints.ToString());
                xml.WriteAttributeString("DataQualityLevel", item.DataQualityLevel.ToString());
                xml.WriteAttributeString("PercentageSimilarity", item.PercentageSimilarity.ToString());
                xml.WriteElementString("GeneralComments", item.GeneralComments);

                //output address info
                if (item.AddressInfo != null)
                {
                    xml.WriteStartElement("AddressInfo");
                    xml.WriteElementString("LocationTitle", item.AddressInfo.Title);
                    xml.WriteElementString("AddressLine1", item.AddressInfo.AddressLine1);
                    xml.WriteElementString("AddressLine2", item.AddressInfo.AddressLine2);
                    xml.WriteElementString("Town", item.AddressInfo.Town);
                    xml.WriteElementString("StateOrProvince", item.AddressInfo.StateOrProvince);
                    xml.WriteElementString("Postcode", item.AddressInfo.Postcode);

                    if (item.AddressInfo.Country != null) xml.WriteElementString("Country", item.AddressInfo.Country.Title);
                    xml.WriteElementString("Latitude", item.AddressInfo.Latitude.ToString());
                    xml.WriteElementString("Longitude", item.AddressInfo.Longitude.ToString());

                    if (item.AddressInfo.Distance != null)
                    {
                        xml.WriteStartElement("Distance");
                        xml.WriteAttributeString("Unit", item.AddressInfo.DistanceUnit.ToString());
                        xml.WriteAttributeString("Value", item.AddressInfo.Distance.ToString());
                        xml.WriteEndElement();
                    }

                    if (item.AddressInfo.ContactTelephone1 != null) xml.WriteElementString("ContactTelephone1", item.AddressInfo.ContactTelephone1);
                    if (item.AddressInfo.ContactTelephone2 != null) xml.WriteElementString("ContactTelephone2", item.AddressInfo.ContactTelephone2);
                    if (item.AddressInfo.ContactEmail != null) xml.WriteElementString("ContactEmail", item.AddressInfo.ContactEmail);
                    if (item.AddressInfo.AccessComments != null) xml.WriteElementString("AccessComments", item.AddressInfo.AccessComments);
#pragma warning disable 0612
                    //if (item.AddressInfo.GeneralComments != null) xml.WriteElementString("GeneralComments", item.AddressInfo.GeneralComments);
#pragma warning restore 0612
                    if (item.AddressInfo.RelatedURL != null) xml.WriteElementString("RelatedURL", item.AddressInfo.RelatedURL);

                    xml.WriteEndElement();
                }

                if (item.Connections != null)
                {
                    xml.WriteStartElement("Connections");
                    foreach (var ct in item.Connections)
                    {
                        xml.WriteStartElement("ConnectionInfo");
                        xml.WriteAttributeString("ID", ct.ID.ToString());
                        if (ct.ConnectionType != null)
                        {
                            xml.WriteAttributeString("TypeID", ct.ConnectionType.ID.ToString());
                            xml.WriteAttributeString("TypeName", ct.ConnectionType.Title);
                        }

                        if (ct.Level != null)
                        {
                            xml.WriteAttributeString("LevelID", ct.Level.ID.ToString());
                            xml.WriteAttributeString("LevelName", ct.Level.Title);
                        }

                        if (ct.StatusType != null)
                        {
                            xml.WriteAttributeString("Status", ct.StatusType.Title);
                        }

                        if (ct.Amps != null)
                        {
                            xml.WriteAttributeString("Amps", ct.Amps.ToString());
                        }

                        if (ct.Voltage != null)
                        {
                            xml.WriteAttributeString("Voltage", ct.Voltage.ToString());
                        }

                        if (ct.Quantity != null)
                        {
                            xml.WriteAttributeString("Quantity", ct.Quantity.ToString());
                        }

                        if (ct.Reference != null)
                        {
                            xml.WriteAttributeString("Reference", ct.Reference.ToString());
                        }
                        xml.WriteEndElement();
                    }
                    xml.WriteEndElement();
                }
#pragma warning disable 0612
                var chargerList = item.Chargers;
                if (chargerList == null || chargerList.Count == 0)
                {
                    if (item.Connections != null)
                    {
                        chargerList = new List<Common.Model.ChargerInfo>();
                        foreach (var con in item.Connections)
                        {
                            if (con.Level != null)
                            {
                                if (!chargerList.Exists(c => c.ChargerType == con.Level))
                                {
                                    chargerList.Add(new Common.Model.ChargerInfo() { ChargerType = con.Level });
                                }
                            }
                        }
                        chargerList = chargerList.Distinct().ToList();

                    }
                }

#pragma warning restore 0612

                if (chargerList != null)
                {
                    xml.WriteStartElement("ChargerTypes");
                    foreach (var cg in chargerList)
                    {
                        if (cg.ChargerType != null)
                        {
                            xml.WriteStartElement("ChargerType");
                            xml.WriteAttributeString("ID", cg.ChargerType.ID.ToString());
                            if (isVerboseMode && !settings.IsCompactOutput)
                            {
                                xml.WriteAttributeString("Title", cg.ChargerType.Title);
                                xml.WriteAttributeString("IsFastChargeCapable", cg.ChargerType.IsFastChargeCapable.ToString());
                            }
                            xml.WriteEndElement();
                        }
                    }
                    xml.WriteEndElement();
                }

                if (item.UsageType != null)
                {
                    xml.WriteStartElement("UsageType");
                    xml.WriteAttributeString("ID", item.UsageType.ID.ToString());
                    if (isVerboseMode)
                    {
                        xml.WriteValue(item.UsageType.Title);
                    }
                    xml.WriteEndElement();
                }

                if (!String.IsNullOrEmpty(item.UsageCost))
                {
                    xml.WriteElementString("UsageCost", item.UsageCost);
                }

                /*if (!String.IsNullOrEmpty(item.MetadataTags))
                {
                    xml.WriteStartElement("MetadataTags");
                    xml.WriteCData(item.MetadataTags);
                    xml.WriteEndElement();
                }*/

                if (item.StatusType != null)
                {
                    xml.WriteStartElement("StatusType");
                    xml.WriteAttributeString("ID", item.StatusType.ID.ToString());
                    if (isVerboseMode && !settings.IsCompactOutput)
                    {
                        xml.WriteAttributeString("Title", item.StatusType.Title);
                    }
                    xml.WriteAttributeString("DateLastStatusUpdate", item.DateLastStatusUpdate.ToString());
                    xml.WriteEndElement(); //end status
                }

                if (item.UserComments != null)
                {
                    xml.WriteStartElement("UserComments");
                    foreach (var comment in item.UserComments)
                    {
                        xml.WriteStartElement("UserComment");
                        xml.WriteAttributeString("CommentTypeID", comment.CommentTypeID.ToString());
                        if (isVerboseMode && !settings.IsCompactOutput)
                        {
                            xml.WriteAttributeString("CommentType", comment.CommentType.Title);
                        }
                        xml.WriteAttributeString("UserName", comment.UserName);
                        xml.WriteAttributeString("Rating", comment.Rating.ToString());
                        xml.WriteAttributeString("RelatedURL", comment.RelatedURL);
                        xml.WriteValue(comment.Comment);
                        xml.WriteEndElement();
                    }
                    xml.WriteEndElement();
                }
                xml.WriteEndElement(); //end charge point
            }

            xml.WriteEndElement(); //end charge points list
            xml.WriteEndDocument(); //end xml
            xml.Flush();
            //xml.Close();
            return Task.CompletedTask;
        }

        public Task GetOutput(HttpContext context, System.IO.Stream outputStream, Common.Model.CoreReferenceData data, Common.APIRequestParams settings)
        {
            throw new NotImplementedException();
        }

        public Task GetOutput(HttpContext context, System.IO.Stream outputStream, Object data, Common.APIRequestParams settings)
        {
            throw new NotImplementedException();
        }
    }
}


text:
/* secure_bind.c
 *
 * Benjamin Ellerby
 * Ray Luo
 * Evan Ricks
 * Oliver Smith-Denny
 *
 * secure_bind.c function to receive a reserved port from Portcullis, the Secure Port Reservation Daemon
 * On success, returns a 0, returnSet is filled out with relevant information
 * On failure returns -1, returnSet is not defined
 *
 */

#include "spr.h"
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <linux/limits.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>

#define PORT_MIN 0
#define PORT_MAX 65535
#define PORT_DIGITS 6
#define QLEN 5
#define RETURN_FAILURE -1
#define RETURN_SUCCESS 0
#define NAMED_FIFO "/tmp/spr_fifo"

int secure_bind(int portNum, sprFDSet *returnSet){

  int recvFD, udsConnectSock, udsListenSock, localLen, remoteLen, flag, fifo;
  time_t seedTime;
  struct sockaddr_un local, remote;
  struct msghdr daemonPermissions, recvFDMsg;
  struct cmsghdr *daemonControl, *recvFDControl;
  struct iovec junkData, fdJunk;
  char cmsgbuf[CMSG_SPACE(sizeof(int))], portBuf[PORT_DIGITS], junkBase, fdBase, udsPath[PATH_MAX + 1];
  /* Begin BSD incompatible */
  char cDataBuf[CMSG_SPACE(sizeof(struct ucred))];
  struct ucred dCred;
  struct ucred *daemonCredentials = &dCred;
  /* End BSD incompatible */

  if(portNum < PORT_MIN || portNum > PORT_MAX) {
    errno = EINVAL;
    return RETURN_FAILURE;
  }

  if(strlen(udsPath) >= PATH_MAX) {
    errno = ENAMETOOLONG;
    return RETURN_FAILURE;
  }

  memset((void *)&local, 0, sizeof(local));
  memset((void *)&remote, 0, sizeof(remote));
  memset((void *)&daemonPermissions, 0, sizeof(daemonPermissions));
  memset((void *)cDataBuf, 0, sizeof(cDataBuf));
  memset((void *)daemonCredentials, 0, sizeof(*daemonCredentials));
  memset((void *)portBuf, 0, sizeof(portBuf));
  memset((void *)returnSet, 0, sizeof(*returnSet));
  memset((void *)&recvFDMsg, 0, sizeof(recvFDMsg));
  memset((void *)cmsgbuf, 0, sizeof(cmsgbuf));
  memset((void *)&junkData, 0, sizeof(junkData));
  memset((void *)&fdJunk, 0, sizeof(fdJunk));
  memset((void *)udsPath, 0, PATH_MAX + 1);

  fdBase = '3';

  recvFDMsg.msg_control = cmsgbuf;
  recvFDMsg.msg_controllen = sizeof(cmsgbuf);
  recvFDMsg.msg_iov = &fdJunk;
  recvFDMsg.msg_iovlen = 1;
  fdJunk.iov_base = &fdBase;
  fdJunk.iov_len = sizeof(fdBase);

  srand((unsigned)time(&seedTime));
  snprintf(udsPath, PATH_MAX, "/tmp/proc%dr%d", getpid(), rand() % 100);
  returnSet->udsLoc = calloc(1, strlen(udsPath)+1);
  strncpy(returnSet->udsLoc, udsPath, strlen(udsPath));

  if((udsListenSock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
    return RETURN_FAILURE;

  local.sun_family = AF_UNIX;
  strncpy(local.sun_path, udsPath, strlen(udsPath));

  if (unlink(local.sun_path) < 0) {
    if (errno != ENOENT) {
        return RETURN_FAILURE;
    }
  }

  localLen = sizeof(local);

  if((bind(udsListenSock, (struct sockaddr *)&local, localLen)) < 0)
    return RETURN_FAILURE;

  if((listen(udsListenSock, QLEN)) < 0)
    return RETURN_FAILURE;

  /* Write the pathname of the UDS Sock to the Daemon's named FIFO */

  if((fifo = open(NAMED_FIFO, O_WRONLY)) < 0) {
    return RETURN_FAILURE;
  }

  if((write(fifo, udsPath, strlen(udsPath))) < strlen(udsPath)) {
    return RETURN_FAILURE;
  }

  close(fifo);

  /* Receive credentials from the Daemon and verify them (recvmsg) */

  remote.sun_family = AF_UNIX;
  strncpy(remote.sun_path, udsPath, strlen(udsPath));
  remoteLen = sizeof(remote);

  if((udsConnectSock = accept(udsListenSock, (struct sockaddr *)&remote, (socklen_t *)&remoteLen)) < 0) {
    close(udsListenSock);
    close(udsConnectSock);
    return RETURN_FAILURE;
  }

  flag = 1;
  if((setsockopt(udsConnectSock, SOL_SOCKET, SO_PASSCRED, &flag, sizeof(flag))) < 0) {
    close(udsListenSock);
    close(udsConnectSock);
    return RETURN_FAILURE;
  }

  daemonPermissions.msg_control = cDataBuf;
  daemonPermissions.msg_controllen = sizeof(cDataBuf);
  daemonPermissions.msg_iov = &junkData;
  daemonPermissions.msg_iovlen = 1;
  junkBase = 'a';
  junkData.iov_base = &junkBase;
  junkData.iov_len = sizeof(junkBase);

  if((recvmsg(udsConnectSock, &daemonPermissions, MSG_WAITALL)) < 0) {
    close(udsListenSock);
    close(udsConnectSock);
    return RETURN_FAILURE;
  }

  daemonControl = CMSG_FIRSTHDR(&daemonPermissions);

  if(daemonControl == NULL || daemonControl->cmsg_type != SCM_CREDENTIALS) {
    errno = ENOMSG;
    close(udsListenSock);
    close(udsConnectSock);
    return RETURN_FAILURE;
  }

  /* Begin BSD incompatible */

  daemonCredentials = (struct ucred *)CMSG_DATA(daemonControl);

  /* TODO: If it is not Daemon process, drop connection, goto line 87 (or current except line) (just kidding), return or loop back */

  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

  /* TEMPORARY for debugging until daemon can have its own uid */

  printf("Received credentials were:\npid: %ld\nuid: %ld\ngid: %ld\n", (long)daemonCredentials->pid, (long)daemonCredentials->uid, (long)daemonCredentials->gid);

  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

  /* End BSD incompatible */

  /* Send desired portNum to Daemon (send) */

  snprintf(portBuf, sizeof(portBuf), "%d", portNum);

  if((send(udsConnectSock, portBuf, sizeof(portBuf), 0)) < 0) {
    close(udsListenSock);
    close(udsConnectSock);
    return RETURN_FAILURE;
  }

  /* Remove SO_PASSCRED from connected socket, no longer needed */

  flag = 0;
  if((setsockopt(udsConnectSock, SOL_SOCKET, SO_PASSCRED, &flag, sizeof(flag))) < 0) {
    close(udsListenSock);
    close(udsConnectSock);
    return RETURN_FAILURE;
  }

  /* Receive (recvmsg) the file descriptor or null from the Daemon */

  if((recvmsg(udsConnectSock, &recvFDMsg, MSG_WAITALL)) < 0) {
    close(udsListenSock);
    close(udsConnectSock);
    return RETURN_FAILURE;
  }

  recvFDControl = CMSG_FIRSTHDR(&recvFDMsg);

  /* If null or no file descriptor, EXIT_FAILURE */

  if(recvFDControl == NULL || recvFDControl->cmsg_type != SCM_RIGHTS) {
    close(udsListenSock);
    close(udsConnectSock);
    return RETURN_FAILURE;
  }

  /* Else, return the received file descriptor (recvFD) */

  memcpy(&recvFD, CMSG_DATA(recvFDControl), sizeof(recvFD));

  returnSet->recvSock = recvFD;
  returnSet->udsListen = udsListenSock;
  returnSet->udsConnect = udsConnectSock;

  return RETURN_SUCCESS;

}


text:
package com.google.android.exoplayer2.source.dash;

import android.net.Uri;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.extractor.ChunkIndex;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.extractor.mkv.MatroskaExtractor;
import com.google.android.exoplayer2.extractor.mp4.FragmentedMp4Extractor;
import com.google.android.exoplayer2.source.chunk.ChunkExtractorWrapper;
import com.google.android.exoplayer2.source.chunk.InitializationChunk;
import com.google.android.exoplayer2.source.dash.manifest.AdaptationSet;
import com.google.android.exoplayer2.source.dash.manifest.DashManifest;
import com.google.android.exoplayer2.source.dash.manifest.DashManifestParser;
import com.google.android.exoplayer2.source.dash.manifest.Period;
import com.google.android.exoplayer2.source.dash.manifest.RangedUri;
import com.google.android.exoplayer2.source.dash.manifest.Representation;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSourceInputStream;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.HttpDataSource;
import com.google.android.exoplayer2.util.MimeTypes;
import java.io.IOException;
import java.util.List;

/**
 * Utility methods for DASH streams.
 */
public final class DashUtil {

  /**
   * Loads a DASH manifest.
   *
   * @param dataSource The {@link HttpDataSource} from which the manifest should be read.
   * @param manifestUri The URI of the manifest to be read.
   * @return An instance of {@link DashManifest}.
   * @throws IOException Thrown when there is an error while loading.
   */
  public static DashManifest loadManifest(DataSource dataSource, String manifestUri)
      throws IOException {
    DataSourceInputStream inputStream = new DataSourceInputStream(dataSource,
        new DataSpec(Uri.parse(manifestUri), DataSpec.FLAG_ALLOW_CACHING_UNKNOWN_LENGTH));
    try {
      inputStream.open();
      DashManifestParser parser = new DashManifestParser();
      return parser.parse(dataSource.getUri(), inputStream);
    } finally {
      inputStream.close();
    }
  }

  /**
   * Loads {@link DrmInitData} for a given manifest.
   *
   * @param dataSource The {@link HttpDataSource} from which data should be loaded.
   * @param dashManifest The {@link DashManifest} of the DASH content.
   * @return The loaded {@link DrmInitData}.
   */
  public static DrmInitData loadDrmInitData(DataSource dataSource, DashManifest dashManifest)
      throws IOException, InterruptedException {
    // Prefer drmInitData obtained from the manifest over drmInitData obtained from the stream,
    // as per DASH IF Interoperability Recommendations V3.0, 7.5.3.
    if (dashManifest.getPeriodCount() < 1) {
      return null;
    }
    Period period = dashManifest.getPeriod(0);
    int adaptationSetIndex = period.getAdaptationSetIndex(C.TRACK_TYPE_VIDEO);
    if (adaptationSetIndex == C.INDEX_UNSET) {
      adaptationSetIndex = period.getAdaptationSetIndex(C.TRACK_TYPE_AUDIO);
      if (adaptationSetIndex == C.INDEX_UNSET) {
        return null;
      }
    }
    AdaptationSet adaptationSet = period.adaptationSets.get(adaptationSetIndex);
    if (adaptationSet.representations.isEmpty()) {
      return null;
    }
    Representation representation = adaptationSet.representations.get(0);
    DrmInitData drmInitData = representation.format.drmInitData;
    if (drmInitData == null) {
      Format sampleFormat = DashUtil.loadSampleFormat(dataSource, representation);
      if (sampleFormat != null) {
        drmInitData = sampleFormat.drmInitData;
      }
      if (drmInitData == null) {
        return null;
      }
    }
    return drmInitData;
  }

  /**
   * Loads initialization data for the {@code representation} and returns the sample {@link
   * Format}.
   * Loads {@link DrmInitData} for a given period in a DASH manifest.
   *
   * @param dataSource The {@link HttpDataSource} from which data should be loaded.
   * @param period The {@link Period}.
   * @return The loaded {@link DrmInitData}, or null if none is defined.
   * @throws IOException Thrown when there is an error while loading.
   * @throws InterruptedException Thrown if the thread was interrupted.
   */
  public static DrmInitData loadDrmInitData(DataSource dataSource, Period period)
      throws IOException, InterruptedException {
    Representation representation = getFirstRepresentation(period, C.TRACK_TYPE_VIDEO);
    if (representation == null) {
      representation = getFirstRepresentation(period, C.TRACK_TYPE_AUDIO);
      if (representation == null) {
        return null;
      }
    }
    DrmInitData drmInitData = representation.format.drmInitData;
    if (drmInitData != null) {
      // Prefer drmInitData obtained from the manifest over drmInitData obtained from the stream,
      // as per DASH IF Interoperability Recommendations V3.0, 7.5.3.
      return drmInitData;
    }
    Format sampleFormat = DashUtil.loadSampleFormat(dataSource, representation);
    return sampleFormat == null ? null : sampleFormat.drmInitData;
  }

  /**
   * Loads initialization data for the {@code representation} and returns the sample {@link Format}.
   *
   * @param dataSource The source from which the data should be loaded.
   * @param representation The representation which initialization chunk belongs to.
   * @return the sample {@link Format} of the given representation.
   * @throws IOException Thrown when there is an error while loading.
   * @throws InterruptedException Thrown if the thread was interrupted.
   */
  public static Format loadSampleFormat(DataSource dataSource, Representation representation)
      throws IOException, InterruptedException {
    ChunkExtractorWrapper extractorWrapper = loadInitializationData(dataSource, representation,
        false);
    return extractorWrapper == null ? null : extractorWrapper.getSampleFormats()[0];
  }

  /**
   * Loads initialization and index data for the {@code representation} and returns the {@link
   * ChunkIndex}.
   *
   * @param dataSource The source from which the data should be loaded.
   * @param representation The representation which initialization chunk belongs to.
   * @return {@link ChunkIndex} of the given representation.
   * @throws IOException Thrown when there is an error while loading.
   * @throws InterruptedException Thrown if the thread was interrupted.
   */
  public static ChunkIndex loadChunkIndex(DataSource dataSource, Representation representation)
      throws IOException, InterruptedException {
    ChunkExtractorWrapper extractorWrapper = loadInitializationData(dataSource, representation,
        true);
    return extractorWrapper == null ? null : (ChunkIndex) extractorWrapper.getSeekMap();
  }

  /**
   * Loads initialization data for the {@code representation} and optionally index data then
   * returns a {@link ChunkExtractorWrapper} which contains the output.
   *
   * @param dataSource The source from which the data should be loaded.
   * @param representation The representation which initialization chunk belongs to.
   * @param loadIndex Whether to load index data too.
   * @return A {@link ChunkExtractorWrapper} for the {@code representation}, or null if no
   *     initialization or (if requested) index data exists.
   * @throws IOException Thrown when there is an error while loading.
   * @throws InterruptedException Thrown if the thread was interrupted.
   */
  private static ChunkExtractorWrapper loadInitializationData(DataSource dataSource,
      Representation representation, boolean loadIndex)
      throws IOException, InterruptedException {
    RangedUri initializationUri = representation.getInitializationUri();
    if (initializationUri == null) {
      return null;
    }
    ChunkExtractorWrapper extractorWrapper = newWrappedExtractor(representation.format);
    RangedUri requestUri;
    if (loadIndex) {
      RangedUri indexUri = representation.getIndexUri();
      if (indexUri == null) {
        return null;
      }
      // It's common for initialization and index data to be stored adjacently. Attempt to merge
      // the two requests together to request both at once.
      requestUri = initializationUri.attemptMerge(indexUri, representation.baseUrl);
      if (requestUri == null) {
        loadInitializationData(dataSource, representation, extractorWrapper, initializationUri);
        requestUri = indexUri;
      }
    } else {
      requestUri = initializationUri;
    }
    loadInitializationData(dataSource, representation, extractorWrapper, requestUri);
    return extractorWrapper;
  }

  private static void loadInitializationData(DataSource dataSource,
      Representation representation, ChunkExtractorWrapper extractorWrapper, RangedUri requestUri)
      throws IOException, InterruptedException {
    DataSpec dataSpec = new DataSpec(requestUri.resolveUri(representation.baseUrl),
        requestUri.start, requestUri.length, representation.getCacheKey());
    InitializationChunk initializationChunk = new InitializationChunk(dataSource, dataSpec,
        representation.format, C.SELECTION_REASON_UNKNOWN, null /* trackSelectionData */,
        extractorWrapper);
    initializationChunk.load();
  }

  private static ChunkExtractorWrapper newWrappedExtractor(Format format) {
    String mimeType = format.containerMimeType;
    boolean isWebm = mimeType.startsWith(MimeTypes.VIDEO_WEBM)
        || mimeType.startsWith(MimeTypes.AUDIO_WEBM);
    Extractor extractor = isWebm ? new MatroskaExtractor() : new FragmentedMp4Extractor();
    return new ChunkExtractorWrapper(extractor, format);
  }

  private static Representation getFirstRepresentation(Period period, int type) {
    int index = period.getAdaptationSetIndex(type);
    if (index == C.INDEX_UNSET) {
      return null;
    }
    List<Representation> representations = period.adaptationSets.get(index).representations;
    return representations.isEmpty() ? null : representations.get(0);
  }

  private DashUtil() {}

}


text:
import test from 'ava';
import fn from './';
import path from 'path';

const nm = path.join(__dirname, 'node_modules');

let absolutePath;
let relativePath;
let tildePath;

test('absolute path', t => {
  const pkg = 'ava';
  absolutePath = path.join(nm, pkg);
  return fn(absolutePath, 'blue').then(res => {
    t.is(res.code, 0);
    t.is(res.tag, 'blue');
    t.is(res.path, absolutePath);
    t.true(res.command.length > 10);
  }, t.fail);
});

test('relative path', t => {
  const pkg = 'pify';
  relativePath = './node_modules/' + pkg;
  return fn(relativePath, 'green').then(res => {
    t.is(res.code, 0);
    t.is(res.tag, 'green');
    t.is(res.path, path.join(nm, pkg));
    t.true(res.command.length > 10);
  }, t.fail);
});

test('tilde path', t => {
  tildePath = '~/Desktop';
  return fn(tildePath, 'yellow').then(res => {
    t.is(res.code, 0);
    t.is(res.tag, 'yellow');
    t.true(res.path.includes('/Users/'));
    t.true(res.command.length > 10);
  }, t.fail);
});

test('path does not exist', t =>
  fn(path.join(__dirname, 'node_modules/doesnotexist'), 'blue').then(
    t.fail,
    err => t.is(err.code, 'ENOENT')
  ));

test('color does not exist', t =>
  fn(absolutePath, 'hotpink').then(t.fail, err =>
    t.true(err.message.includes('color must be one of'))
  ));

test('path is not string', t =>
  fn(92403, 'hotpink').then(t.fail, err =>
    t.true(err.message.includes('path should be a string'))
  ));

test.after('clear test tags', () =>
  Promise.all([
    fn(absolutePath, 'clear'),
    fn(relativePath, 'clear'),
    fn(tildePath, 'clear')
  ])
);


text:
package org.omg.PortableServer;

/**
* org/omg/PortableServer/IdAssignmentPolicy.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/workspace/8-2-build-windows-amd64-cygwin/jdk8u65/4987/corba/src/share/classes/org/omg/PortableServer/poa.idl
* Tuesday, October 6, 2015 4:40:34 PM PDT
*/

/**
	 * IdAssignmentPolicy specifies whether Object Ids in
	 * the created POA are generated by the application or
	 * by the ORB. The default is SYSTEM_ID.
	 */
public interface IdAssignmentPolicy extends IdAssignmentPolicyOperations, org.omg.CORBA.Policy, org.omg.CORBA.portable.IDLEntity
{
} // interface IdAssignmentPolicy


text:
[![PyPI Version](https://img.shields.io/pypi/v/puppetboard)](https://pypi.org/project/puppetboard/)
[![PyPI Downloads](https://img.shields.io/pypi/dm/puppetboard)](https://pypi.org/project/puppetboard/)
![Tests Status](https://github.com/voxpupuli/puppetboard/workflows/tests%20(unit)/badge.svg)
[![codecov](https://codecov.io/gh/voxpupuli/puppetboard/branch/master/graph/badge.svg?token=uez5RoiU6I)](https://codecov.io/gh/voxpupuli/puppetboard)
[![By Voxpupuli](https://img.shields.io/badge/by-Vox%20Pupuli%20%F0%9F%A6%8A-ef902f.svg)](http://voxpupuli.org)

Puppetboard is a web interface to [PuppetDB](https://puppet.com/docs/puppetdb/latest/index.html) aiming to replace
the reporting functionality of [Puppet Enterprise console (previously: Puppet Dashboard)](https://puppet.com/docs/pe/latest/console_accessing.html)
for the open source Puppet.

![Overview](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/overview.png)

See [more screenshots here](#more-screenshots).

## Table of Contents

* [Requirements](#requirements)
* [Installation](#installation)
* [Configuration](#configuration)
* [Getting Help](#getting-help)
* [Contributing](#contributing)
* [Legal](#legal)

## Requirements

* PuppetDB v. 5.2-7.10 (will most probably work with newer, but this has not been tested yet)
* Python 3.7-3.11 or Docker

## Installation

Puppetboard is packaged and available on PyPI.

### With Puppet module

There is a [Puppet module](https://forge.puppetlabs.com/puppet/puppetboard) originally written by
 [Spencer Krum](https://github.com/nibalizer) and currently maintained by [Voxpupuli](https://voxpupuli.org/)
that takes care of installing the Puppetboard for you.

To see how to get it working with RedHat/Centos 7 check out these [docs](https://github.com/voxpupuli/puppetboard/blob/master/docs/EL7.md).

### Using Docker

We provide [an official Docker image in the GitHub Container Registry](https://github.com/orgs/voxpupuli/packages/container/package/puppetboard).

You can run the app on your PuppetDB host with this command:

```bash
docker run -it \
  -e PUPPETDB_HOST=localhost \
  -e PUPPETDB_PORT=8080 \
  --net=host \
  ghcr.io/voxpupuli/puppetboard
```

Optionally you can set `PUPPETBOARD_URL_PREFIX` env variable to a value like `/puppetboard` to run the app under a URL prefix.

You can use the following Puppet Code to have Puppetboard managed by Puppet:

```puppet
include docker

docker::image { 'ghcr.io/voxpupuli/puppetboard': }

docker::run { 'puppetboard':
  image => 'ghcr.io/voxpupuli/puppetboard',
  env   => [
    'PUPPETDB_HOST=127.0.0.1',
    'PUPPETDB_PORT=8080',
    'PUPPETBOARD_PORT=8088',
  ],
  net   => 'host',
}
```

We also provide the Dockerfile, so you can build the image yourself:
```bash
docker build -t puppetboard .
```

### From a package

Actively maintained packages:

* [FreeBSD](https://www.freshports.org/www/py-puppetboard/)
  maintained by [Romain Tartière](https://github.com/smortex)
* [OpenBSD](https://cvsweb.openbsd.org/cgi-bin/cvsweb/ports/www/puppetboard/)
  maintained by [Sebastian Reitenbach](https://github.com/buzzdeee)

### Manually

You can also install the package from PyPI and configure a WSGI-capable application server to serve it.

We recommend using virtualenv to provide a separate environment for the app.

```bash
virtualenv -p python3 venv
. venv/bin/activate
pip install puppetboard
```

Please see [an article about more deployment setups here](https://github.com/voxpupuli/puppetboard/blob/master/docs/Deployment-setups.md).

## Configuration

### Puppet agents

The default value of `usecacheonfailure = true` configuration setting for Puppet agents causes Puppet runs to always succeed,
event if there are catalog compilation failures f.e. because of a syntax error in your code. This is because in such
cases with this setting Puppet will just use a cached working catalog and report the run to PuppetDB as successful.
(Although with an error visible in the Puppet run log.)

Therefore, to show the nodes with a catalog compilation as failed in Puppetboard you need to set
`usecacheonfailure = false` in your nodes' `puppet.conf`.

### PuppetDB

Of course you need to configure your Puppet Server to store the Puppet run reports in PuppetDB.
If you haven't done that already please follow the [PuppetDB documentation](https://puppet.com/docs/puppetdb/latest/connect_puppet_server.html)
about this.

If you run Puppetboard on a different host than PuppetDB then you may want to configure the certificate
allow-list for which certificates are allowed to access data from PuppetDB.
Please read more about this feature in the [PuppetDB documentation here](https://puppet.com/docs/puppetdb/latest/configure.html#certificate-allowlist).

### App settings

Puppetboard will look for a file pointed at by the `PUPPETBOARD_SETTINGS` environment variable.
The file has to be identical to
[default_settings.py](https://github.com/voxpupuli/puppetboard/blob/master/puppetboard/default_settings.py)
but should only override the settings you need changed.

If you run PuppetDB and Puppetboard on the same machine the default settings provided will be enough to get you started
and you won't need a custom settings file.

Assuming your webserver and PuppetDB machine are not identical you will at least have to change the following settings:

-   `PUPPETDB_HOST`
-   `PUPPETDB_PORT`

By default PuppetDB requires SSL to be used when a non-local client wants to connect. Therefore you'll also have to
supply the following settings:

-   `PUPPETDB_SSL_VERIFY = /path/to/ca/keyfile.pem`
-   `PUPPETDB_KEY = /path/to/private/keyfile.pem`
-   `PUPPETDB_CERT = /path/to/public/keyfile.crt`

When using the Puppetboard Docker image, you may also pass Puppetboard it's certificate contents via these environment
variables, either as a multiline string or pre-base64 encoded. This can be useful where the certificate is stored in a
secrets store i.e. AWS SSM Parameter Store.

```
PUPPETDB_CERT="-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----"
```

```
PUPPETDB_CERT=LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQouLi4KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQ==
```

For information about how to generate the correct keys please refer to the
[pypuppetdb documentation](https://pypuppetdb.readthedocs.io/en/latest/connecting.html#ssl). Alternatively it is possible
to explicitly specify the protocol to be used setting the `PUPPETDB_PROTO` variable.

Other settings that might be interesting, in no particular order:

- `FAVORITE_ENVS`: an ordered list of Puppet environment names that will be shown immediately after "All Environments"
    and before other environments (which are sorted by name) in the dropdown for choosing the environment shown
    in the top-right of the UI. Environments listed here that do not really exist in your deployment are silently ignored.
- `SHOW_ERROR_AS`: `friendly` or `raw`. The former makes Puppet run errors in Report and Failures views shown
    in a modified, (arguably) more user-friendly form. The latter shows them as they are.
    Defaults to `friendly`.
- `CODE_PREFIX_TO_REMOVE`: what code path that should be shortened in "Friendly errors" to "…" for readability.
    A regexp. Defaults to `/etc/puppetlabs/code/environments(/.*?/modules)?`.
- `SECRET_KEY`: Refer to [Flask documentation](https://flask.palletsprojects.com/en/1.1.x/quickstart/#sessions),
    section "How to generate good secret keys" for more info. Defaults to a random 24-char string generated by
    `os.random(24)`.
- `PUPPETDB_TIMEOUT`: Defaults to 20 seconds, but you might need to increase this value. It depends on how big the
    results are when querying PuppetDB. This behaviour will change in a future release when pagination will be introduced.
- `UNRESPONSIVE_HOURS`: The amount of hours since the last check-in after which a node is considered unresponsive.
- `LOGLEVEL`: A string representing the loglevel. It defaults to `'info'` but can be changed to `'warning'` or
    `'critical'` for less verbose logging or `'debug'` for more information.
- `ENABLE_QUERY`: Defaults to `True` causing a Query tab to show up in the web interface allowing users to write
    and execute arbitrary queries against a set of endpoints in PuppetDB. Change this to `False` to disable this.
    See `ENABLED_QUERY_ENDPOINTS` to fine-tune which endpoints are allowed.
- `ENABLED_QUERY_ENDPOINTS`: If `ENABLE_QUERY` is `True`, allow to fine tune the endpoints of PuppetDB APIs that
    can be queried. It must be a list of strings of PuppetDB endpoints for which the query is enabled.
    See the `QUERY_ENDPOINTS` constant in the `puppetboard.app` module for a list of the available endpoints.
- `GRAPH_TYPE`: Specify the type of graph to display.   Default is
    pie, other good option is donut.   Other choices can be found here:
    \_C3JS\_documentation\`
- `GRAPH_FACTS`: A list of fact names to tell PuppetBoard to generate a pie-chart on the fact page. With some fact
    values being unique per node, like ipaddress, uuid, and serial number, as well as structured facts it was no longer
    feasible to generate a graph for everything.
- `INVENTORY_FACTS`: A list of tuples that serve as the column header and the fact name to search for to create
    the inventory page. If a fact is not found for a node then `undef` is printed.
- `INVENTORY_FACT_TEMPLATES`: A mapping between fact name and jinja template to customize display
- `ENABLE_CATALOG`: If set to `True` allows the user to view a node's latest catalog. This includes all managed
    resources, their file-system locations and their relationships, if available. Defaults to `False`.
- `REFRESH_RATE`: Defaults to `30` the number of seconds to wait until the index page is automatically refreshed.
- `DEFAULT_ENVIRONMENT`: Defaults to `'production'`, as the name suggests, load all information filtered by this
    environment value.
- `REPORTS_COUNT`: Defaults to `10` the limit of the number of reports to load on the node or any reports page.
- `OFFLINE_MODE`: If set to `True` load static assets (jquery, semantic-ui, etc) from the local web server instead
    of a CDN. Defaults to `False`.
- `DAILY_REPORTS_CHART_ENABLED`: Enable the use of daily chart graphs when looking at dashboard and node view.
- `DAILY_REPORTS_CHART_DAYS`: Number of days to show history for on the daily report graphs.
- `DISPLAYED_METRICS`: Metrics to show when displaying node summary. Example: `'resources.total'`, `'events.noop'`.
- `TABLE_COUNT_SELECTOR`: Configure the dropdown to limit number of hosts to show per page.
- `LITTLE_TABLE_COUNT`: Default number of reports to show when when looking at a node.
- `NORMAL_TABLE_COUNT`: Default number of nodes to show when displaying reports and catalog nodes.
- `LOCALISE_TIMESTAMP`: If set to `True` then timestamps are shown using your browser's timezone. Otherwise UTC is used. Defaults to `True`.
- `WITH_EVENT_NUMBERS`: If set to `True` then Overview and Nodes list shows exact number of changed resources
    in the last report. Otherwise shows only 'some' string if there are resources with given status. Setting this
    to `False` gives performance benefits, especially in big Puppet environments (more than few hundreds of nodes).
    Defaults to `True`.

## Getting Help

For questions or bug reports you can file an [issue](https://github.com/voxpupuli/puppetboard/issues).

## Contributing

### Development

Puppetboard relies on the [pypuppetdb](https://pypi.org/project/pypuppetdb/) library to fetch data from PuppetDB
and is built with the help of the [Flask](https://flask.palletsprojects.com) microframework.

If you wish to hack on Puppetboard you should fork/clone the Github repository and then install the requirements through:

```bash
pip install --upgrade wheel setuptools
python setup.py develop
pip install --upgrade -r requirements-test.txt
mypy --install-types --non-interactive puppetboard/ test/
```

You're advised to do this inside a virtualenv specifically created to work on Puppetboard as to not pollute your global Python installation.

You can run the tests with:
```bash
pytest --cov=. --cov-report=xml --strict-markers --mypy puppetboard test
flake8 -v .
```

You can run the app it in development mode by simply executing:

```bash
flask run
```

You can specify listening host and port with environment variables or command line otions:

```bash
export FLASK_RUN_HOST=0.0.0.0
export FLASK_RUN_PORT=8000

flask run
```

or

```bash
flask run --host '0.0.0.0' --port '8000'
```

Use `PUPPETBOARD_SETTINGS` to change the different settings or patch `default_settings.py` directly.
Take care not to include your local changes on that file when submitting patches for Puppetboard.
Place a `settings.py` file inside the base directory of the git repository that will be used, if the environment
variable is not set.

We welcome contributions to this project. However, there are a few ground rules contributors should be aware of.

### License

This project is licensed under the Apache v2.0 License. As such, your contributions, once accepted, are automatically
covered by this license.

### Commit messages

Write decent commit messages. Don't use swear words and refrain from uninformative commit messages as 'fixed typo'.

The preferred format of a commit message:

    docs/quickstart: Fixed a typo in the Nodes section.

    If needed, elaborate further on this commit. Feel free to write a
    complete blog post here if that helps us understand what this is
    all about.

    Fixes #4 and resolves #2.

If you'd like a more elaborate guide on how to write and format your commit messages have a look at [this post
by Tim Pope](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).

## More Screenshots

* Overview / Index / Homepage

![Overview / Index / Homepage](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/overview.png)

* Nodes view, all active nodes

![Nodes view, all active nodes](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/nodes.png)

* Single node page / overview

![Single node page / overview](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/node.png)

* Report view

![Report view](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/report.png)

* Facts view

![Facts view](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/facts.png)

* Single fact, with graphs

![Single fact, with graphs](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/fact.png)

* All nodes that have this fact with that value

![All nodes that have this fact with that value](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/fact_value.png)

* Query view - results as table

![Query view](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/query_result_table.png)

* Query view - results as JSON

![Query view](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/query_result_json.png)

* Metrics view

![Metrics view](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/metrics.png)

* Single metric

![Single metric](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/metric.png)

* Inventory view

![Inventory view](https://raw.githubusercontent.com/voxpupuli/puppetboard/master/screenshots/inventory.png)

# Legal

The app code is licensed under the [Apache License, Version 2.0](./LICENSE).

The favicon has been created based on the icon created by [Jonathan Coutiño](https://thenounproject.com/ralts01/)
under the [Attribution 3.0 Unported (CC BY 3.0) license](https://creativecommons.org/licenses/by/3.0/),
downloaded from the [Noun Project](https://thenounproject.com).


text:
package io.resourcepool.dashboard.ui.adapters;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

import io.resourcepool.dashboard.ui.displayables.AbstractDisplayable;
import io.resourcepool.dashboard.ui.displayables.Displayable;
import io.resourcepool.dashboard.ui.fragments.MediaFragment;
import io.resourcepool.dashboard.ui.utils.LoopingPagerAdapter;
import io.resourcepool.dashboard.ui.views.DashboardView;

import java.util.List;

public class MediaPagerAdapter extends LoopingPagerAdapter<AbstractDisplayable> implements AbstractDisplayable.OnCompletionListener {
    private List<AbstractDisplayable> mDisplayables;
    private DashboardView mDashboardView;
    private int mCurrentPage;

    public MediaPagerAdapter(FragmentManager fragmentManager, DashboardView dashboardView, List<AbstractDisplayable> displayables) {
        super(fragmentManager, displayables);
        this.mDisplayables = displayables;
        this.mDashboardView = dashboardView;
    }

    @Override
    public Fragment getRealItem(int position) {
        AbstractDisplayable displayable = mDisplayables.get(position);
        return MediaFragment.newInstance(displayable);
    }

    @Override
    public void onRealPageSelected(int position) {
        if (mDisplayables.isEmpty()) {
            return;
        }
        mDisplayables.get(position).start();
        mCurrentPage = position;
    }

    @Override
    public void onDisplayableCompletion() {
        if (mDisplayables.size() != 1) {
            mDashboardView.nextMedia();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    public Displayable getCurrentDisplayable() {
        return mDisplayables.get(mCurrentPage);
    }
}


text:
module PublishesToPublishingApi
  extend ActiveSupport::Concern

  included do
    before_validation :generate_content_id, on: :create
    validates :content_id, presence: true
    after_commit :publish_to_publishing_api, if: :can_publish_to_publishing_api?
  end

  def generate_content_id
    self.content_id ||= SecureRandom.uuid
  end

  def can_publish_to_publishing_api?
    persisted?
  end

  def publish_to_publishing_api
    Whitehall::PublishingApi.publish_async(self)
  end
end


text:
require 'spec_helper.rb'

describe 'Role' do
  it "can fetch" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                             .roles("RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch()
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    ))).to eq(true)
  end

  it "receives fetch responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        200,
      %q[
      {
          "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "friendly_name": "channel user",
          "type": "channel",
          "permissions": [
              "sendMessage",
              "leaveChannel",
              "editOwnMessage",
              "deleteOwnMessage"
          ],
          "date_created": "2016-03-03T19:47:15Z",
          "date_updated": "2016-03-03T19:47:15Z",
          "url": "https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                    .roles("RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch()

    expect(actual).to_not eq(nil)
  end

  it "can delete" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                             .roles("RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").delete()
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'delete',
        url: 'https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    ))).to eq(true)
  end

  it "receives delete responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        204,
      nil,
    ))

    actual = @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                    .roles("RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").delete()

    expect(actual).to eq(true)
  end

  it "can create" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                             .roles.create(friendly_name: "friendly_name", type: "channel", permission: ['permission'])
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {
        'FriendlyName' => "friendly_name",
        'Type' => "channel",
        'Permission' => ['permission'],
    }
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'post',
        url: 'https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles',
        data: values,
    ))).to eq(true)
  end

  it "receives create responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        201,
      %q[
      {
          "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "friendly_name": "channel user",
          "type": "channel",
          "permissions": [
              "sendMessage",
              "leaveChannel",
              "editOwnMessage",
              "deleteOwnMessage"
          ],
          "date_created": "2016-03-03T19:47:15Z",
          "date_updated": "2016-03-03T19:47:15Z",
          "url": "https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                    .roles.create(friendly_name: "friendly_name", type: "channel", permission: ['permission'])

    expect(actual).to_not eq(nil)
  end

  it "can read" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                             .roles.list()
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles',
    ))).to eq(true)
  end

  it "receives read_full responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        200,
      %q[
      {
          "meta": {
              "page": 0,
              "page_size": 1,
              "first_page_url": "https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=1&Page=0",
              "previous_page_url": null,
              "url": "https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=1&Page=0",
              "next_page_url": null,
              "key": "roles"
          },
          "roles": [
              {
                  "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "friendly_name": "channel user",
                  "type": "channel",
                  "permissions": [
                      "sendMessage",
                      "leaveChannel",
                      "editOwnMessage",
                      "deleteOwnMessage"
                  ],
                  "date_created": "2016-03-03T19:47:15Z",
                  "date_updated": "2016-03-03T19:47:15Z",
                  "url": "https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
              }
          ]
      }
      ]
    ))

    actual = @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                    .roles.list()

    expect(actual).to_not eq(nil)
  end

  it "receives read_empty responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        200,
      %q[
      {
          "meta": {
              "page": 0,
              "page_size": 1,
              "first_page_url": "https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=1&Page=0",
              "previous_page_url": null,
              "url": "https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=1&Page=0",
              "next_page_url": null,
              "key": "roles"
          },
          "roles": []
      }
      ]
    ))

    actual = @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                    .roles.list()

    expect(actual).to_not eq(nil)
  end

  it "can update" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                             .roles("RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").update(friendly_name: "friendly_name", permission: ['permission'])
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {
        'FriendlyName' => "friendly_name",
        'Permission' => ['permission'],
    }
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'post',
        url: 'https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
        data: values,
    ))).to eq(true)
  end

  it "receives update responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        200,
      %q[
      {
          "sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "friendly_name": "channel user",
          "type": "channel",
          "permissions": [
              "sendMessage",
              "leaveChannel",
              "editOwnMessage",
              "deleteOwnMessage"
          ],
          "date_created": "2016-03-03T19:47:15Z",
          "date_updated": "2016-03-03T19:47:15Z",
          "url": "https://ip-messaging.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.ip_messaging.v1.services("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                    .roles("RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").update(friendly_name: "friendly_name", permission: ['permission'])

    expect(actual).to_not eq(nil)
  end
end


text:
package org.cloudfoundry.uaa.users;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;

/**
 * The email addresses for a user
 */
@JsonDeserialize
@Value.Immutable
abstract class _Email {

    /**
     * Whether this email address is the primary
     */
    @JsonProperty("primary")
    abstract Boolean getPrimary();

    /**
     * The email address
     */
    @JsonProperty("value")
    abstract String getValue();

}