text:
package uk.ac.abdn.fits.hibernate.model;

/**
 * @author Cheng Zeng, University of Aberdeen
 *
 */

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="surcharge_distance")
public class SurchargeDistance {

	@Id
	  @GeneratedValue(strategy = GenerationType.AUTO)
	  @Column(name="id", nullable = false)
	  private int id;

	  @Column(name="operator_id", nullable = false)
	  private int operator_id;

	  /*
	  @Column(name="dist1_mile_1", nullable = true)
	  private double dist1_mile_1;

	  @Column(name="dist1_mile_2", nullable = true)
	  private double dist1_mile_2;

	  @Column(name="dist1_type", nullable = true)
	  private String dist1_type;

	  @Column(name="dist1_charge", nullable = true)
	  private double dist1_charge;

	  @Column(name="dist2_mile_1", nullable = true)
	  private double dist2_mile_1;

	  @Column(name="dist2_mile_2", nullable = true)
	  private double dist2_mile_2;

	  @Column(name="dist2_type", nullable = true)
	  private String dist2_type;

	  @Column(name="dist2_charge", nullable = true)
	  private double dist2_charge;

	  @Column(name="dist3_mile_1", nullable = true)
	  private double dist3_mile_1;

	  @Column(name="dist3_mile_2", nullable = true)
	  private double dist3_mile_2;

	  @Column(name="dist3_type", nullable = true)
	  private String dist3_type;

	  @Column(name="dist3_charge", nullable = true)
	  private double dist3_charge;

	  @Column(name="dist4_mile_1", nullable = true)
	  private double dist4_mile_1;

	  @Column(name="dist4_mile_2", nullable = true)
	  private double dist4_mile_2;

	  @Column(name="dist4_type", nullable = true)
	  private String dist4_type;

	  @Column(name="dist4_charge", nullable = true)
	  private double dist4_charge;

	  @Column(name="dist5_other", nullable = true)
	  private String dist5_other;

*/
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getOperator_id() {
		return operator_id;
	}

	public void setOperator_id(int operator_id) {
		this.operator_id = operator_id;
	}

	/*
	public double getDist1_mile_1() {
		return dist1_mile_1;
	}

	public void setDist1_mile_1(double dist1_mile_1) {
		this.dist1_mile_1 = dist1_mile_1;
	}

	public double getDist1_mile_2() {
		return dist1_mile_2;
	}

	public void setDist1_mile_2(double dist1_mile_2) {
		this.dist1_mile_2 = dist1_mile_2;
	}

	public String getDist1_type() {
		return dist1_type;
	}

	public void setDist1_type(String dist1_type) {
		this.dist1_type = dist1_type;
	}

	public double getDist1_charge() {
		return dist1_charge;
	}

	public void setDist1_charge(double dist1_charge) {
		this.dist1_charge = dist1_charge;
	}

	public double getDist2_mile_1() {
		return dist2_mile_1;
	}

	public void setDist2_mile_1(double dist2_mile_1) {
		this.dist2_mile_1 = dist2_mile_1;
	}

	public double getDist2_mile_2() {
		return dist2_mile_2;
	}

	public void setDist2_mile_2(double dist2_mile_2) {
		this.dist2_mile_2 = dist2_mile_2;
	}

	public String getDist2_type() {
		return dist2_type;
	}

	public void setDist2_type(String dist2_type) {
		this.dist2_type = dist2_type;
	}

	public double getDist2_charge() {
		return dist2_charge;
	}

	public void setDist2_charge(double dist2_charge) {
		this.dist2_charge = dist2_charge;
	}

	public double getDist3_mile_1() {
		return dist3_mile_1;
	}

	public void setDist3_mile_1(double dist3_mile_1) {
		this.dist3_mile_1 = dist3_mile_1;
	}

	public double getDist3_mile_2() {
		return dist3_mile_2;
	}

	public void setDist3_mile_2(double dist3_mile_2) {
		this.dist3_mile_2 = dist3_mile_2;
	}

	public String getDist3_type() {
		return dist3_type;
	}

	public void setDist3_type(String dist3_type) {
		this.dist3_type = dist3_type;
	}

	public double getDist3_charge() {
		return dist3_charge;
	}

	public void setDist3_charge(double dist3_charge) {
		this.dist3_charge = dist3_charge;
	}

	public double getDist4_mile_1() {
		return dist4_mile_1;
	}

	public void setDist4_mile_1(double dist4_mile_1) {
		this.dist4_mile_1 = dist4_mile_1;
	}

	public double getDist4_mile_2() {
		return dist4_mile_2;
	}

	public void setDist4_mile_2(double dist4_mile_2) {
		this.dist4_mile_2 = dist4_mile_2;
	}

	public String getDist4_type() {
		return dist4_type;
	}

	public void setDist4_type(String dist4_type) {
		this.dist4_type = dist4_type;
	}

	public double getDist4_charge() {
		return dist4_charge;
	}

	public void setDist4_charge(double dist4_charge) {
		this.dist4_charge = dist4_charge;
	}

	public String getDist5_other() {
		return dist5_other;
	}

	public void setDist5_other(String dist5_other) {
		this.dist5_other = dist5_other;
	}

	*/

}


text:
import logging
import subprocess

logger = logging.getLogger('workers.' + __name__)

def Poll(config):
   ping = subprocess.Popen(
      ["ping", "-c", "3", config['destination']],
      stdout = subprocess.PIPE,
      stderr = subprocess.PIPE
   )

   out, error = ping.communicate()
   #logger.info('poll done: %s' % config)

   return(out)

redpajama_set_name: RedPajamaGithub


text:
layout:     post
title:      Helping Senior Citizens
subtitle:   We've put more effort into helping folks reach old age than into helping them enjoy it.
date:       2017-12-12 12:05:00
author:     "Rohit Naidu"
header-img: "img/oldage.jpg"
categories: Elders
---

* Paint park benches

* Donate used books to your local library

*Become a tour guide at your local museum (ask students of tourism to be guides for tourists in general)

*Repaint community fences


text:
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="20dp"  />
    <solid android:color="#000000" />
</shape>
<!-- From: file:/Users/gmarques/Documents/workspaces/inSPorteGitHub/InsPorte_android/app/src/main/res/drawable/shape.xml -->


text:
define(
    [
        'ko',
        'Magento_Catalog/js/price-utils',
        'mage/translate'
    ],
    function (ko, priceUtils, $t) {
        'use strict';

        return {
            create: function (product, priceConfig) {
                var productPrice = {};

                var displayPriceIncludingTax = priceConfig.displayPriceIncludingTax || priceConfig.displayPriceBoth;

                productPrice.discount = product.discount;
                productPrice.is_discount_percentage = product.is_discount_percentage;

                productPrice.price = ko.observable(product.price);
                productPrice.hasSpecialPrice = ko.observable(product.is_catalog_rule_applied);

                productPrice.priceWithDiscountText = ko.pureComputed(function() {
                    var discount = productPrice.discountValue();
                    var price = parseFloat(productPrice.priceToDisplay()) - discount;
                    if (product.tax_rate && priceConfig.applyTaxAfterDiscount && displayPriceIncludingTax && !priceConfig.priceIncludesTax) {
                        price = (1 + product.tax_rate/100)*(productPrice.priceExclTax() - discount);
                    }
                    var priceText = getFormattedPrice(round(price));
                    if (!priceConfig.applyDiscountToCatalogPrice && productPrice.hasSpecialPrice()) {
                        return getFormattedPrice(productPrice.priceToDisplay());
                    }
                    if (price < discount) {
                        return getFormattedPrice(productPrice.priceToDisplay());
                    }
                    if (discount <= 0) {
                        return priceText;
                    }
                    if (!priceConfig.discountTax && displayPriceIncludingTax) {
                        priceText += ' ' + $t('(incl. tax)');
                    }

                    return priceConfig.discountMessage
                        .replace('%price', priceText)
                        .replace('%discount_amount', getFormattedPrice(discount))
                        .replace('%discount_text', productPrice.discountText());
                });

                productPrice.discountValue = ko.pureComputed(function() {
                    var discount = parseFloat(productPrice.discount);
                    if (productPrice.is_discount_percentage) {
                        var price = priceConfig.discountTax ? productPrice.priceInclTax() : productPrice.priceExclTax();
                        discount = parseFloat(price) * discount;
                    }
                    return round(discount);
                });

                productPrice.formattedPrice = ko.pureComputed(function() {
                    return getFormattedPrice(productPrice.priceToDisplay());
                });

                productPrice.priceToDisplay = ko.pureComputed(function() {
                    return displayPriceIncludingTax ? productPrice.priceInclTax() : productPrice.priceExclTax();
                });

                productPrice.priceInclTax = ko.pureComputed(function() {
                    var price = productPrice.price();
                    if (!product.tax_rate || priceConfig.priceIncludesTax) {
                        return price;
                    }

                    var tax = parseFloat(product.tax_rate)/100 * price;
                    return round(price + tax);
                });

                productPrice.priceExclTax = ko.pureComputed(function() {
                    var price = productPrice.price();
                    if (product.tax_rate && priceConfig.priceIncludesTax) {
                        price = parseFloat(price)/(1 + parseFloat(product.tax_rate)/100);
                    }

                    return round(price);
                });

                productPrice.discountText = ko.pureComputed(function() {
                    return productPrice.is_discount_percentage
                        ? round(100*parseFloat(productPrice.discount)) + '%'
                        : getFormattedPrice(productPrice.discount);
                });

                productPrice.setFrontendPrice = function(frontendPrice) {
                    productPrice.price(getPriceFromFrontendPrice(frontendPrice));
                };

                function getFormattedPrice(price) {
                    return priceUtils.formatPrice(price, priceConfig.priceFormat);
                }

                function round(num) {
                    return +(Math.round(num + 'e+2')  + 'e-2');
                }

                function getPriceFromFrontendPrice(price) {
                    if (!product.tax_rate) {
                        return price;
                    }

                    if (displayPriceIncludingTax && !priceConfig.priceIncludesTax) {
                        return price/(1 + product.tax_rate/100);
                    }
                    if (!displayPriceIncludingTax && priceConfig.priceIncludesTax) {
                        return price*(1 + product.tax_rate/100);
                    }

                    return price;
                }

                return productPrice;
            }
        };
    }
);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/configuration" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/domain" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/engine" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/server" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/web" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/web-ng" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/web-steps" charset="UTF-8" />
  </component>
</project>


text:
import ctypes
import locale

RegisterWindowMessage = ctypes.windll.user32.RegisterWindowMessageA
LoadCursor = ctypes.windll.user32.LoadCursorA
LoadIcon = ctypes.windll.user32.LoadIconA
LoadImage = ctypes.windll.user32.LoadImageA
RegisterClass = ctypes.windll.user32.RegisterClassA
CreateWindowEx = ctypes.windll.user32.CreateWindowExA
UpdateWindow = ctypes.windll.user32.UpdateWindow
DefWindowProc = ctypes.windll.user32.DefWindowProcA
GetSystemMetrics = ctypes.windll.user32.GetSystemMetrics
InsertMenuItem = ctypes.windll.user32.InsertMenuItemA
PostMessage = ctypes.windll.user32.PostMessageA
PostQuitMessage = ctypes.windll.user32.PostQuitMessage
SetMenuDefaultItem = ctypes.windll.user32.SetMenuDefaultItem
GetCursorPos = ctypes.windll.user32.GetCursorPos
SetForegroundWindow = ctypes.windll.user32.SetForegroundWindow
TrackPopupMenu = ctypes.windll.user32.TrackPopupMenu
CreatePopupMenu = ctypes.windll.user32.CreatePopupMenu
CreateCompatibleDC = ctypes.windll.gdi32.CreateCompatibleDC
GetDC = ctypes.windll.user32.GetDC
CreateCompatibleBitmap = ctypes.windll.gdi32.CreateCompatibleBitmap
GetSysColorBrush = ctypes.windll.user32.GetSysColorBrush
FillRect = ctypes.windll.user32.FillRect
DrawIconEx = ctypes.windll.user32.DrawIconEx
SelectObject = ctypes.windll.gdi32.SelectObject
DeleteDC = ctypes.windll.gdi32.DeleteDC
DestroyWindow = ctypes.windll.user32.DestroyWindow
GetModuleHandle = ctypes.windll.kernel32.GetModuleHandleA
GetMessage = ctypes.windll.user32.GetMessageA
TranslateMessage = ctypes.windll.user32.TranslateMessage
DispatchMessage = ctypes.windll.user32.DispatchMessageA
Shell_NotifyIcon = ctypes.windll.shell32.Shell_NotifyIcon
DestroyIcon = ctypes.windll.user32.DestroyIcon

NIM_ADD = 0
NIM_MODIFY = 1
NIM_DELETE = 2
NIF_ICON = 2
NIF_MESSAGE = 1
NIF_TIP = 4
MIIM_ID = 2
MIIM_SUBMENU = 4
MIIM_STRING = 64
MIIM_BITMAP = 128
WM_DESTROY = 2
WM_CLOSE = 16
WM_COMMAND = 273
WM_USER = 1024
WM_LBUTTONDBLCLK = 515
WM_RBUTTONUP = 517
WM_LBUTTONUP = 514
WM_NULL = 0
CS_VREDRAW = 1
CS_HREDRAW = 2
IDC_ARROW = 32512
COLOR_WINDOW = 5
WS_OVERLAPPED = 0
WS_SYSMENU = 524288
CW_USEDEFAULT = -2147483648
LR_LOADFROMFILE = 16
LR_DEFAULTSIZE = 64
IMAGE_ICON = 1
IDI_APPLICATION = 32512
TPM_LEFTALIGN = 0
SM_CXSMICON = 49
SM_CYSMICON = 50
COLOR_MENU = 4
DI_NORMAL = 3

class fState:
    MFS_DEFAULT = 0x1000
    MFS_ENABLED = 0
    MFS_DISABLED = 0x3
    MFS_CHECKED = 0x8
    MFS_HILITE = 0x80

# WPARAM is defined as UINT_PTR (unsigned type)
# LPARAM is defined as LONG_PTR (signed type)
if ctypes.sizeof(ctypes.c_long) == ctypes.sizeof(ctypes.c_void_p):
    WPARAM = ctypes.c_ulong
    LPARAM = ctypes.c_long
    LRESULT = ctypes.c_long
elif ctypes.sizeof(ctypes.c_longlong) == ctypes.sizeof(ctypes.c_void_p):
    WPARAM = ctypes.c_ulonglong
    LPARAM = ctypes.c_longlong
    LRESULT = ctypes.c_longlong
HANDLE = ctypes.c_void_p

SZTIP_MAX_LENGTH = 128
LOCALE_ENCODING = locale.getpreferredencoding()

def convert_to_ascii(s):
    """
    Encode text items for system locale. If encoding fails, fall back to ASCII.
    """
    try:
        return s.encode(LOCALE_ENCODING, 'ignore')
    except (AttributeError, UnicodeDecodeError):
        return s.decode('ascii', 'ignore').encode(LOCALE_ENCODING)

LPFN_WNDPROC = ctypes.CFUNCTYPE(LRESULT, HANDLE, ctypes.c_uint, WPARAM, LPARAM)
class WNDCLASS(ctypes.Structure):
    _fields_ = [("style", ctypes.c_uint),
                ("lpfnWndProc", LPFN_WNDPROC),
                ("cbClsExtra", ctypes.c_int),
                ("cbWndExtra", ctypes.c_int),
                ("hInstance", HANDLE),
                ("hIcon", HANDLE),
                ("hCursor", HANDLE),
                ("hbrBackground", HANDLE),
                ("lpszMenuName", ctypes.c_char_p),
                ("lpszClassName", ctypes.c_char_p),
               ]

class POINT(ctypes.Structure):
    _fields_ = [('x', ctypes.c_long), ('y', ctypes.c_long)]

class RECT(ctypes.Structure):
    _fields_ = [('left', ctypes.c_long), ('top', ctypes.c_long),
                ('right', ctypes.c_long), ('bottom', ctypes.c_long)]

class MENUITEMINFO(ctypes.Structure):
    _fields_ = [("cbSize", ctypes.c_uint),
                ("fMask", ctypes.c_uint),
                ("fType", ctypes.c_uint),
                ("fState", ctypes.c_uint),
                ("wID", ctypes.c_uint),
                ("hSubMenu", HANDLE),
                ("hbmpChecked", HANDLE),
                ("hbmpUnchecked", HANDLE),
                ("dwItemData", ctypes.c_void_p),
                ("dwTypeData", ctypes.c_char_p),
                ("cch", ctypes.c_uint),
                ("hbmpItem", HANDLE),
               ]

class MSG(ctypes.Structure):
    _fields_ = [("hwnd", HANDLE),
                ("message", ctypes.c_uint),
                ("wParam", WPARAM),
                ("lParam", LPARAM),
                ("time", ctypes.c_ulong),
                ("pt", POINT),
               ]

class NOTIFYICONDATA(ctypes.Structure):
    _fields_ = [("cbSize", ctypes.c_uint),
                ("hWnd", HANDLE),
                ("uID", ctypes.c_uint),
                ("uFlags", ctypes.c_uint),
                ("uCallbackMessage", ctypes.c_uint),
                ("hIcon", HANDLE),
                ("szTip", ctypes.c_char * 64),
                ("dwState", ctypes.c_uint),
                ("dwStateMask", ctypes.c_uint),
                ("szInfo", ctypes.c_char * 256),
                ("uTimeout", ctypes.c_uint),
                ("szInfoTitle", ctypes.c_char * 64),
                ("dwInfoFlags", ctypes.c_uint),
                ("guidItem", ctypes.c_char * 16),
                ("hBalloonIcon", HANDLE),
               ]

def PackMENUITEMINFO(text=None, hbmpItem=None, wID=None, hSubMenu=None, fState=fState.MFS_ENABLED):
    res = MENUITEMINFO()
    res.cbSize = ctypes.sizeof(res)
    res.fMask = 1

    res.fState  = fState
    if hbmpItem is not None:
        res.fMask |= MIIM_BITMAP
        res.hbmpItem = hbmpItem
    if wID is not None:
        res.fMask |= MIIM_ID
        res.wID = wID
    if text is not None:
        text = convert_to_ascii(text)
        res.fMask |= MIIM_STRING
        res.dwTypeData = text
    if hSubMenu is not None:
        res.fMask |= MIIM_SUBMENU
        res.hSubMenu = hSubMenu
    return res

def LOWORD(w):
    return w & 0xFFFF

def PumpMessages():
    msg = MSG()
    while GetMessage(ctypes.byref(msg), None, 0, 0) > 0:
        TranslateMessage(ctypes.byref(msg))
        DispatchMessage(ctypes.byref(msg))

def NotifyData(hWnd=0, uID=0, uFlags=0, uCallbackMessage=0, hIcon=0, szTip=""):
    szTip = convert_to_ascii(szTip)
    res = NOTIFYICONDATA()
    res.cbSize = ctypes.sizeof(res)
    res.hWnd = hWnd
    res.uID = uID
    res.uFlags = uFlags
    res.uCallbackMessage = uCallbackMessage
    res.hIcon = hIcon
    res.szTip = szTip
    return res


text:
namespace Microsoft.Azure.Management.Logic.Models
{
    using Azure;
    using Management;
    using Logic;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Error properties indicate why the Logic service was not able to process
    /// the incoming request. The reason is provided in the error message.
    /// </summary>
    public partial class ErrorProperties
    {
        /// <summary>
        /// Initializes a new instance of the ErrorProperties class.
        /// </summary>
        public ErrorProperties() { }

        /// <summary>
        /// Initializes a new instance of the ErrorProperties class.
        /// </summary>
        /// <param name="code">Error code.</param>
        /// <param name="message">Error message indicating why the operation
        /// failed.</param>
        public ErrorProperties(string code = default(string), string message = default(string))
        {
            Code = code;
            Message = message;
        }

        /// <summary>
        /// Gets or sets error code.
        /// </summary>
        [JsonProperty(PropertyName = "code")]
        public string Code { get; set; }

        /// <summary>
        /// Gets or sets error message indicating why the operation failed.
        /// </summary>
        [JsonProperty(PropertyName = "message")]
        public string Message { get; set; }

    }
}


text:
using Simple.Data;
using System.Collections.Generic;
using System.Linq;
using X.Insert.DTO.DTOs;
using X.Insert.DTO.Enums;
using X.Insert.Reader.Services.Interfaces;

namespace X.Insert.Reader.Services
{
    public class AddressReadService : ReadService, IAddressReadService
    {
        public AddressReadService()
            : base()
        {

        }

        public AddressReadService(string connectionStringName)
            : base(connectionStringName)
        {

        }

        public AddressDTO GetAddress(int addressId)
        {
            var address = GetAddresses(new[] { addressId });
            return address.FirstOrDefault();
        }

        public AddressDTO GetAddressForObjectByType(int objectId, AddressTypeEnum addressType)
        {
            var addressesForObjectByTypes = GetAddressForObjectByTypes(objectId, new[] { addressType });
            return addressesForObjectByTypes.FirstOrDefault();
        }

        public List<AddressDTO> GetAddresses(IEnumerable<int> addressesIds)
        {
            var db = GetDatabaseConnection();
            return db.adr__Ewid.FindAll(db.adr__Ewid.adr_Id == addressesIds)
                .Select(GetColumnsMapping());
        }

        public List<AddressDTO> GetAddressForObjectByTypes(int objectId, IEnumerable<AddressTypeEnum> addressTypes)
        {
            var db = GetDatabaseConnection();
            return db.adr__Ewid.FindAll(db.adr__Ewid.adr_IdObiektu == objectId && db.adr__Ewid.adr_TypAdresu == addressTypes)
                .Select(GetColumnsMapping());
        }

        public List<int> GetAddressesIdsByAddressType(AddressTypeEnum addressType)
        {
            var db = GetDatabaseConnection();
            return db.adr__Ewid.FindAll(db.adr__Ewid.adr_TypAdresu == addressType)
                .Select(db.adr__Ewid.adr_Id)
                .ToScalarList<int>();
        }

        protected IEnumerable<SimpleReference> GetColumnsMapping()
        {
            var db = GetDatabaseConnection();
            return new List<SimpleReference>
            {
                db.adr__Ewid.adr_Id.As("Id"),
                db.adr__Ewid.adr_IdObiektu.As("ObjectId"),
                db.adr__Ewid.adr_TypAdresu.As("Type"),
                db.adr__Ewid.adr_Nazwa.As("Name"),
                db.adr__Ewid.adr_NazwaPelna.As("FullName"),
                db.adr__Ewid.adr_Telefon.As("PhoneNumber"),
                db.adr__Ewid.adr_Faks.As("FaxNumber"),
                db.adr__Ewid.adr_Ulica.As("Street"),
                db.adr__Ewid.adr_NrDomu.As("BuildingNumber"),
                db.adr__Ewid.adr_NrLokalu.As("FlatNumber"),
                db.adr__Ewid.adr_Kod.As("ZipCode"),
                db.adr__Ewid.adr_Miejscowosc.As("City"),
                db.adr__Ewid.adr_IdWojewodztwo.As("CountryRegionId"),
                db.adr__Ewid.adr_IdPanstwo.As("CountryId"),
                db.adr__Ewid.adr_NIP.As("TaxNumber"),
                db.adr__Ewid.adr_Poczta.As("PostOfficeCity"),
                db.adr__Ewid.adr_Gmina.As("Community"),
                db.adr__Ewid.adr_Powiat.As("County"),
                db.adr__Ewid.adr_IdGminy.As("CommunityId"),
                db.adr__Ewid.adr_Skrytka.As("PostBox"),
                db.adr__Ewid.adr_DataZmiany.As("ModificationTime")
            };
        }
    }
}


text:
package com.sega.vimarket.config;

import android.content.Context;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.module.GlideModule;

/**
 * Created by Sega on 8/1/2016.
 */
public class GlideConfiguration implements GlideModule {
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        // Set Glide decode format to the higher quality ARGB_8888 format
        builder.setDecodeFormat(DecodeFormat.PREFER_RGB_565);
    }

    @Override
    public void registerComponents(Context context, Glide glide) {
    }
}


text:
#ifndef GRPCXX_IMPL_THD_NO_CXX11_H
#define GRPCXX_IMPL_THD_NO_CXX11_H

#include <grpc/support/thd.h>

namespace grpc {

class thread {
 public:
  template<class T> thread(void (T::*fptr)(), T *obj) {
    func_ = new thread_function<T>(fptr, obj);
    joined_ = false;
    start();
  }
  ~thread() {
    if (!joined_) std::terminate();
    delete func_;
  }
  void join() {
    gpr_thd_join(thd_);
    joined_ = true;
  }
 private:
  void start() {
    gpr_thd_options options = gpr_thd_options_default();
    gpr_thd_options_set_joinable(&options);
    gpr_thd_new(&thd_, thread_func, (void *) func_, &options);
  }
  static void thread_func(void *arg) {
    thread_function_base *func = (thread_function_base *) arg;
    func->call();
  }
  class thread_function_base {
   public:
    virtual ~thread_function_base() { }
    virtual void call() = 0;
  };
  template<class T>
  class thread_function : public thread_function_base {
   public:
    thread_function(void (T::*fptr)(), T *obj)
      : fptr_(fptr)
      , obj_(obj) { }
    virtual void call() { (obj_->*fptr_)(); }
   private:
    void (T::*fptr_)();
    T *obj_;
  };
  thread_function_base *func_;
  gpr_thd_id thd_;
  bool joined_;

  // Disallow copy and assign.
  thread(const thread&);
  void operator=(const thread&);
};

}  // namespace grpc

#endif  // GRPCXX_IMPL_THD_NO_CXX11_H


text:
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module    : QGraphicsSceneHoverEvent.hs
    Copyright : (c) David Harley 2010
    Project   : qtHaskell
    Version   : 1.1.4
    Modified  : 2010-09-02 17:02:27

    Warning   : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------

module Qtc.Gui.QGraphicsSceneHoverEvent (
  qGraphicsSceneHoverEvent_delete
  )
  where

import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.QEvent

import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui

instance Qpos (QGraphicsSceneHoverEvent a) (()) (IO (PointF)) where
 pos x0 ()
  = withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QGraphicsSceneHoverEvent_pos_qth cobj_x0 cpointf_ret_x cpointf_ret_y

foreign import ccall "qtc_QGraphicsSceneHoverEvent_pos_qth" qtc_QGraphicsSceneHoverEvent_pos_qth :: Ptr (TQGraphicsSceneHoverEvent a) -> Ptr CDouble -> Ptr CDouble -> IO ()

instance Qqpos (QGraphicsSceneHoverEvent a) (()) (IO (QPointF ())) where
 qpos x0 ()
  = withQPointFResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QGraphicsSceneHoverEvent_pos cobj_x0

foreign import ccall "qtc_QGraphicsSceneHoverEvent_pos" qtc_QGraphicsSceneHoverEvent_pos :: Ptr (TQGraphicsSceneHoverEvent a) -> IO (Ptr (TQPointF ()))

instance QscenePos (QGraphicsSceneHoverEvent a) (()) where
 scenePos x0 ()
  = withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QGraphicsSceneHoverEvent_scenePos_qth cobj_x0 cpointf_ret_x cpointf_ret_y

foreign import ccall "qtc_QGraphicsSceneHoverEvent_scenePos_qth" qtc_QGraphicsSceneHoverEvent_scenePos_qth :: Ptr (TQGraphicsSceneHoverEvent a) -> Ptr CDouble -> Ptr CDouble -> IO ()

instance QqscenePos (QGraphicsSceneHoverEvent a) (()) where
 qscenePos x0 ()
  = withQPointFResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QGraphicsSceneHoverEvent_scenePos cobj_x0

foreign import ccall "qtc_QGraphicsSceneHoverEvent_scenePos" qtc_QGraphicsSceneHoverEvent_scenePos :: Ptr (TQGraphicsSceneHoverEvent a) -> IO (Ptr (TQPointF ()))

instance QscreenPos (QGraphicsSceneHoverEvent a) (()) where
 screenPos x0 ()
  = withPointResult $ \cpoint_ret_x cpoint_ret_y ->
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QGraphicsSceneHoverEvent_screenPos_qth cobj_x0 cpoint_ret_x cpoint_ret_y

foreign import ccall "qtc_QGraphicsSceneHoverEvent_screenPos_qth" qtc_QGraphicsSceneHoverEvent_screenPos_qth :: Ptr (TQGraphicsSceneHoverEvent a) -> Ptr CInt -> Ptr CInt -> IO ()

instance QqscreenPos (QGraphicsSceneHoverEvent a) (()) where
 qscreenPos x0 ()
  = withQPointResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QGraphicsSceneHoverEvent_screenPos cobj_x0

foreign import ccall "qtc_QGraphicsSceneHoverEvent_screenPos" qtc_QGraphicsSceneHoverEvent_screenPos :: Ptr (TQGraphicsSceneHoverEvent a) -> IO (Ptr (TQPoint ()))

instance QsetPos (QGraphicsSceneHoverEvent a) ((PointF)) where
 setPos x0 (x1)
  = withObjectPtr x0 $ \cobj_x0 ->
    withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
    qtc_QGraphicsSceneHoverEvent_setPos_qth cobj_x0 cpointf_x1_x cpointf_x1_y

foreign import ccall "qtc_QGraphicsSceneHoverEvent_setPos_qth" qtc_QGraphicsSceneHoverEvent_setPos_qth :: Ptr (TQGraphicsSceneHoverEvent a) -> CDouble -> CDouble -> IO ()

instance QqsetPos (QGraphicsSceneHoverEvent a) ((QPointF t1)) where
 qsetPos x0 (x1)
  = withObjectPtr x0 $ \cobj_x0 ->
    withObjectPtr x1 $ \cobj_x1 ->
    qtc_QGraphicsSceneHoverEvent_setPos cobj_x0 cobj_x1

foreign import ccall "qtc_QGraphicsSceneHoverEvent_setPos" qtc_QGraphicsSceneHoverEvent_setPos :: Ptr (TQGraphicsSceneHoverEvent a) -> Ptr (TQPointF t1) -> IO ()

instance QsetScenePos (QGraphicsSceneHoverEvent a) ((PointF)) where
 setScenePos x0 (x1)
  = withObjectPtr x0 $ \cobj_x0 ->
    withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
    qtc_QGraphicsSceneHoverEvent_setScenePos_qth cobj_x0 cpointf_x1_x cpointf_x1_y

foreign import ccall "qtc_QGraphicsSceneHoverEvent_setScenePos_qth" qtc_QGraphicsSceneHoverEvent_setScenePos_qth :: Ptr (TQGraphicsSceneHoverEvent a) -> CDouble -> CDouble -> IO ()

instance QqsetScenePos (QGraphicsSceneHoverEvent a) ((QPointF t1)) where
 qsetScenePos x0 (x1)
  = withObjectPtr x0 $ \cobj_x0 ->
    withObjectPtr x1 $ \cobj_x1 ->
    qtc_QGraphicsSceneHoverEvent_setScenePos cobj_x0 cobj_x1

foreign import ccall "qtc_QGraphicsSceneHoverEvent_setScenePos" qtc_QGraphicsSceneHoverEvent_setScenePos :: Ptr (TQGraphicsSceneHoverEvent a) -> Ptr (TQPointF t1) -> IO ()

instance QsetScreenPos (QGraphicsSceneHoverEvent a) ((Point)) where
 setScreenPos x0 (x1)
  = withObjectPtr x0 $ \cobj_x0 ->
    withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
    qtc_QGraphicsSceneHoverEvent_setScreenPos_qth cobj_x0 cpoint_x1_x cpoint_x1_y

foreign import ccall "qtc_QGraphicsSceneHoverEvent_setScreenPos_qth" qtc_QGraphicsSceneHoverEvent_setScreenPos_qth :: Ptr (TQGraphicsSceneHoverEvent a) -> CInt -> CInt -> IO ()

instance QqsetScreenPos (QGraphicsSceneHoverEvent a) ((QPoint t1)) where
 qsetScreenPos x0 (x1)
  = withObjectPtr x0 $ \cobj_x0 ->
    withObjectPtr x1 $ \cobj_x1 ->
    qtc_QGraphicsSceneHoverEvent_setScreenPos cobj_x0 cobj_x1

foreign import ccall "qtc_QGraphicsSceneHoverEvent_setScreenPos" qtc_QGraphicsSceneHoverEvent_setScreenPos :: Ptr (TQGraphicsSceneHoverEvent a) -> Ptr (TQPoint t1) -> IO ()

qGraphicsSceneHoverEvent_delete :: QGraphicsSceneHoverEvent a -> IO ()
qGraphicsSceneHoverEvent_delete x0
  = withObjectPtr x0 $ \cobj_x0 ->
    qtc_QGraphicsSceneHoverEvent_delete cobj_x0

foreign import ccall "qtc_QGraphicsSceneHoverEvent_delete" qtc_QGraphicsSceneHoverEvent_delete :: Ptr (TQGraphicsSceneHoverEvent a) -> IO ()


text:
require 'spec_helper'

describe 'ActiveMQ server' do
  it 'should be running the activemq server' do
    expect(service('activemq')).to be_running
    expect(service('activemq')).to be_enabled
  end
end


text:
using System.ComponentModel.Composition;
using BusinessEntities.Dictionaries;
using DependencyResolution.Interfaces;
using BLL.Dictionaries;
using BLL.Interfaces;
using BLL.Mapping;
using BusinessEntities.SystemEntities;
using DAL.UnitOfWork;

namespace BLL
{
	[Export(typeof(IComponent))]
	public class DependencyResolver : IComponent
	{
		public void SetUp(IRegisterComponent registerComponent)
		{
			MappingConfig.RegisterMapping();

			registerComponent.RegisterType(typeof(IService<SYS_DictionaryEntity>), typeof(DictionaryService));

			registerComponent.RegisterType(typeof(IUnitOfWork), typeof(UnitOfWork));
			registerComponent.RegisterType(typeof(IService<AnimalEntity>), typeof(AnimalService));
			registerComponent.RegisterType(typeof(IService<CountryEntity>), typeof(CountryService));
			registerComponent.RegisterType(typeof(IService<RegionEntity>), typeof(RegionService));
		}
	}
}


text:
package com.evolveum.midpoint.gui.impl.page.admin.configuration.component;

import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;

import com.evolveum.midpoint.gui.api.component.BasePanel;
import com.evolveum.midpoint.gui.api.prism.ItemWrapper;
import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.prism.ItemVisibility;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType;

/**
 * @author skublik
 */
public class SystemConfigPanel extends BasePanel<PrismObjectWrapper<SystemConfigurationType>> {

    private static final long serialVersionUID = 1L;

    private static final Trace LOGGER = TraceManager.getTrace(SystemConfigPanel.class);

    private static final String ID_SYSTEM_CONFIG = "basicSystemConfiguration";

    public SystemConfigPanel(String id, IModel<PrismObjectWrapper<SystemConfigurationType>> model) {
        super(id, model);

        setOutputMarkupId(true);

    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        initLayout();
    }

    protected void initLayout() {
        try {
            ItemPanelSettingsBuilder builder = new ItemPanelSettingsBuilder().visibilityHandler(itemWrapper -> getBasicTabVisibity(itemWrapper));
            Panel panel = getPageBase().initItemPanel(ID_SYSTEM_CONFIG, SystemConfigurationType.COMPLEX_TYPE, getModel(), builder.build());
            add(panel);
        } catch (SchemaException e) {
            LOGGER.error("Cannot create basic panel for system configuration.");
            getSession().error("Cannot create basic panel for system configuration.");
        }

    }

    private ItemVisibility getBasicTabVisibity(ItemWrapper<?, ?, ?, ?> itemWrapper) {
        if(itemWrapper.getPath().isSubPathOrEquivalent(ItemPath.create(ItemPath.EMPTY_PATH, SystemConfigurationType.F_DESCRIPTION)) || itemWrapper.getPath().isSubPathOrEquivalent(ItemPath.create(
                ItemPath.EMPTY_PATH, SystemConfigurationType.F_GLOBAL_SECURITY_POLICY_REF))) {
            return ItemVisibility.AUTO;
        }

        if(itemWrapper.getPath().isSuperPathOrEquivalent(ItemPath.create(ObjectType.F_EXTENSION))) {
            return ItemVisibility.AUTO;
        }

        return ItemVisibility.HIDDEN;
    }
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
    Partial Public Class FindReferencesTests
#Region "FAR on generic methods"
        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Sub TestMethodType_Parameter1()
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document><![CDATA[
        class C
        {
            void Foo<{|Definition:$$T|}>([|T|] x1, t x2)
            {
            }
        }]]></Document>
    </Project>
</Workspace>
            Test(input)
        End Sub

        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Sub TestMethodType_Parameter3()
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document><![CDATA[
        partial class C
        {
            void Foo<{|Definition:$$T|}>(X<[|T|]> t)
            {
            }

            void Bar<T>(T t)
            {
            }
        }]]></Document>
    </Project>
</Workspace>
            Test(input)
        End Sub

        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Sub TestMethodType_ParameterCaseSensitivity()
            Dim input =
<Workspace>
    <Project Language="Visual Basic" CommonReferences="true">
        <Document>
        partial class C
            sub Foo(of {|Definition:$$T|})(x as [|T|], x1 as [|t|])
            end sub
        end class</Document>
    </Project>
</Workspace>

            Test(input)
        End Sub

        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Sub TestMethodType_MethodCall()
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document><![CDATA[
        using System;
        interface GenericInterface<T>
        {
            void {|Definition:IntMethod|}<T>(T t);
        }
        class GenericClass<T> : GenericInterface<T>
        {
            public void {|Definition:IntMethod|}<T>(T t) { }
        }
        class M
        {
            public M()
            {
                GenericClass<string> GCObj = new GenericClass<string>();
                GCObj.[|$$IntMethod|]<string>("foo");
            }
        }]]>
        </Document>
    </Project>
</Workspace>
            Test(input)
        End Sub
#End Region

#Region "FAR on generic partial methods"

        <WorkItem(544436)>
        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Sub TestMethodType_GenericPartialParameter_CSharp1()
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document><![CDATA[
        partial class C
        {
            partial void Foo<{|Definition:$$T|}>([|T|] t)
            {
            }
        }]]></Document>
        <Document><![CDATA[
        partial class C
        {
            partial void Foo<{|Definition:T|}>([|T|] t);
        }]]></Document>
    </Project>
</Workspace>
            Test(input)
        End Sub

        <WorkItem(544436), WorkItem(544475)>
        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Sub TestMethodType_GenericPartialParameter_CSharp2()
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document><![CDATA[
        partial class C
        {
            partial void Foo<{|Definition:T|}>([|T|] t)
            {
            }
        }]]></Document>
        <Document><![CDATA[
        partial class C
        {
            partial void Foo<{|Definition:$$T|}>([|T|] t);
        }]]></Document>
    </Project>
</Workspace>
            Test(input)
        End Sub

        <WorkItem(544435)>
        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Sub TestMethodType_GenericPartialParameter_VB1()
            Dim input =
<Workspace>
    <Project Language="Visual Basic" CommonReferences="true">
        <Document><![CDATA[
            partial class C
                sub Foo(Of {|Definition:$$T|})(t as [|T|])
                end sub
            end class]]>
        </Document>
        <Document><![CDATA[
            partial class C
                partial sub Foo(Of {|Definition:T|})(t as [|T|])
                end sub
            end class]]>
        </Document>
    </Project>
</Workspace>
            Test(input)
        End Sub

        <WorkItem(544435)>
        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Sub TestMethodType_GenericPartialParameter_VB2()
            Dim input =
<Workspace>
    <Project Language="Visual Basic" CommonReferences="true">
        <Document><![CDATA[
            partial class C
                sub Foo(Of {|Definition:T|})(t as [|T|])
                end sub
            end class]]>
        </Document>
        <Document><![CDATA[
            partial class C
                partial sub Foo(Of {|Definition:$$T|})(t as [|T|])
                end sub
            end class]]>
        </Document>
    </Project>
</Workspace>
            Test(input)
        End Sub

#End Region
    End Class
End Namespace


text:
package soundgates.diagram.edit.parts;

import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tooling.runtime.edit.policies.reparent.CreationEditPolicyWithCustomReparent;

import soundgates.diagram.edit.policies.PatchCanonicalEditPolicy;
import soundgates.diagram.edit.policies.PatchItemSemanticEditPolicy;
import soundgates.diagram.part.SoundgatesVisualIDRegistry;

/**
 * @generated
 */
public class PatchEditPart extends DiagramEditPart {

	/**
	 * @generated
	 */
	public final static String MODEL_ID = "Soundgates"; //$NON-NLS-1$

	/**
	 * @generated
	 */
	public static final int VISUAL_ID = 1000;

	/**
	 * @generated
	 */
	public PatchEditPart(View view) {
		super(view);
	}

	/**
	 * @generated NOT
	 */
	protected void createDefaultEditPolicies() {
		super.createDefaultEditPolicies();
		installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
				new PatchItemSemanticEditPolicy());
		installEditPolicy(EditPolicyRoles.CANONICAL_ROLE,
				new PatchCanonicalEditPolicy());
		installEditPolicy(EditPolicyRoles.CREATION_ROLE,
				new CreationEditPolicyWithCustomReparent(
						SoundgatesVisualIDRegistry.TYPED_INSTANCE));
		removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.POPUPBAR_ROLE);
		removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.DRAG_DROP_ROLE);
	}
}


text:
package com.paloski.time.clock;

import java.io.Serializable;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * An abstract subclass of Clock that is backed by Date objects instead of being
 * tied to Instant or the System clock
 *

 * This class provides the time that's accessible via {@link #millis()} and
 * {@link #instant()} by interpreting the current time from {@link Date} objects
 * provided to it from {@link #getDate()}. As this Clock is directly linked to
 * the dates returned by {@code getDate} it can be made to act like any of the
 * Clocks provided by the {@link Clock} class.
 *

 * Note that the Date objects returned from {@link #getDate()} must be
 * convertible to an {@link Instant}, as such a {@link java.sql.Time} object is
 * not a valid return value.
 *

 * In a normal use case, this class can be used from an existing Date source in
 * the following way:
 *

 *

 * {@code
 * 	//Get the current date based time source...
 * 	ExistingTimeSource existingSource = getExistingTimeSource();
 * 	Clock dateClock = DateClock.ofSupplier(existingSource::getCurrentDate());
 * 	//Call into any of the Temporal implementations that take a Clock to their now() function
 * 	LocalDate date = LocalDate.now(dateClock);
 * }
 *

 *

 * Subclasses should ensure that they document immutability, Serializability and
 * thread safety, as described in {@link Clock}. Additionally, subclases must
 * never modify Date objects returned from {@link #getDate()}, and should clone it
 * before changing it.
 *
 * @author Adam Paloski
 */
public abstract class DateClock extends Clock {

	/**
	 * Constructor accessible by subclasses.
	 */
	protected DateClock() {
		// Do nothing
	}

	/**
	 * {@inheritDoc}
	 *
	 * @implNote The implementation of this method in DateClock will not
	 * modify the Date object returned by {@link #getDate()}
	 */
	@Override
	public final long millis() {
		return getDate().getTime();
	}

	/**
	 * {@inheritDoc}
	 *
	 * @implNote The implementation of this method in DateClock will not
	 * modify the Date object returned by {@link #getDate()}
	 */
	@Override
	public final Instant instant() {
		return getDate().toInstant();
	}

	/**
	 * Obtains a Date object representing the time of this clock. Note that the
	 * value return by this method must not be null and must not throw
	 * when {@link Date#toInstant()} is invoked, if it does, that exception will
	 * be propagated to the caller of {@link #instant()}. Due to this, a
	 * {@link java.sql.Time} object is not a suitable return type for this
	 * method.
	 *

	 * Any invokers of this method should take care not to alter the
	 * returned Date object, as it has no requirements of immutability and may
	 * be a single object returned repeatedly, such as in a fixed clock.
	 *
	 * @return A non-null Date object representing the current point on the
	 * clock.
	 */
	protected abstract Date getDate();

	/**
	 * Obtains a new DateClock that has its Date values supplied by a Supplier
	 * with a given ZoneId.
	 *

	 * The Supplier passed to this function must not return null when
	 * {@link Supplier#get()} is invoked and the returned values must not throw
	 * when {@link Date#toInstant()} is called. Doing either will result in a
	 * call to {@link #millis()} or {@link #instant()} propagating an exception
	 * up to the caller. Due to this fact, a Supplier returning a
	 * {@link java.sql.Time} object is not suitable for this method, as it
	 * cannot be converted to an Instant.
	 *

	 * The returned implementation is immutable, thread-safe and
	 * {@code Serializable} providing that the underlying Supplier is.
	 *
	 * @param dateSupplier
	 * 		A non-null Supplier that returns only non-null date objects. This
	 * 		Supplier must be thread safe to fulfill the contract of Clock
	 * @param zoneId
	 * 		A non-null ZoneId that this cloak is situated in.
	 *
	 * @return A non-null DateClock that will return Instants based upon the
	 * Dates returned by {@code dateSupplier}.
	 *
	 * @implNote The Date objects supplied to any Clock produced by this method
	 * will not be modified.
	 */
	public static DateClock ofSupplier(Supplier<Date> dateSupplier, ZoneId zoneId) {
		return new DateSupplierClock(dateSupplier, zoneId);
	}

	/**
	 * A Private Clock class used by {@link #ofSupplier(Supplier, ZoneId)}
	 *
	 * @author Adam Paloski
	 */
	private static class DateSupplierClock extends DateClock implements Serializable {

		private static final long serialVersionUID = 3513511693670455875L;

		private final Supplier<Date> mDateSupplier;
		private final ZoneId mZoneId;

		/* Package */DateSupplierClock(Supplier<Date> supplier, ZoneId zoneId) {
			mDateSupplier = Objects.requireNonNull(supplier, "The date supplier may not be null");
			mZoneId = Objects.requireNonNull(zoneId, "The zoneid may not be null");
		}

		@Override
		public Date getDate() {
			return Objects.requireNonNull(mDateSupplier.get(), "The date supplier, " + mDateSupplier + " may not supply a null value.");
		}

		@Override
		public ZoneId getZone() {
			return mZoneId;
		}

		@Override
		public Clock withZone(ZoneId zone) {
			// Intentionally cause an NPE here if zone is null
			if (zone.equals(mZoneId)) {
				return this;
			} else {
				return new DateSupplierClock(mDateSupplier, zone);
			}
		}

	}

}


text:
package org.projectfloodlight.openflow.protocol.ver13;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
import java.util.EnumSet;
import java.util.Set;
import com.google.common.collect.Sets;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.hamcrest.CoreMatchers;

public class OFGetConfigReplyVer13Test {
    OFFactory factory;

    final static byte[] GET_CONFIG_REPLY_SERIALIZED =
        new byte[] { 0x4, 0x8, 0x0, 0xc, 0x12, 0x34, 0x56, 0x78, 0x0, 0x2, (byte) 0xff, (byte) 0xff };

    @Before
    public void setup() {
        factory = OFFactoryVer13.INSTANCE;
    }

    @Test
    public void testWrite() {
        OFGetConfigReply.Builder builder = factory.buildGetConfigReply();
        builder.setXid(0x12345678)
    .setFlags(Sets.immutableEnumSet(OFConfigFlags.FRAG_REASM))
    .setMissSendLen(0xffff)
    .build();
        OFGetConfigReply getConfigReply = builder.build();
        ByteBuf bb = Unpooled.buffer();
        getConfigReply.writeTo(bb);
        byte[] written = new byte[bb.readableBytes()];
        bb.readBytes(written);

        assertThat(written, CoreMatchers.equalTo(GET_CONFIG_REPLY_SERIALIZED));
    }

    @Test
    public void testRead() throws Exception {
        OFGetConfigReply.Builder builder = factory.buildGetConfigReply();
        builder.setXid(0x12345678)
    .setFlags(Sets.immutableEnumSet(OFConfigFlags.FRAG_REASM))
    .setMissSendLen(0xffff)
    .build();
        OFGetConfigReply getConfigReplyBuilt = builder.build();

        ByteBuf input = Unpooled.copiedBuffer(GET_CONFIG_REPLY_SERIALIZED);

        // FIXME should invoke the overall reader once implemented
        OFGetConfigReply getConfigReplyRead = OFGetConfigReplyVer13.READER.readFrom(input);
        assertEquals(GET_CONFIG_REPLY_SERIALIZED.length, input.readerIndex());

        assertEquals(getConfigReplyBuilt, getConfigReplyRead);
   }

   @Test
   public void testReadWrite() throws Exception {
       ByteBuf input = Unpooled.copiedBuffer(GET_CONFIG_REPLY_SERIALIZED);

       // FIXME should invoke the overall reader once implemented
       OFGetConfigReply getConfigReply = OFGetConfigReplyVer13.READER.readFrom(input);
       assertEquals(GET_CONFIG_REPLY_SERIALIZED.length, input.readerIndex());

       // write message again
       ByteBuf bb = Unpooled.buffer();
       getConfigReply.writeTo(bb);
       byte[] written = new byte[bb.readableBytes()];
       bb.readBytes(written);

       assertThat(written, CoreMatchers.equalTo(GET_CONFIG_REPLY_SERIALIZED));
   }

}


text:
<?php

include_once('Controller.php');
include_once("model/DonanteModel.php");
include_once("repository/DonanteRepository.php");
include_once("repository/PDOrepository.php");
include_once("controller/RoleService.php");

class DonanteController extends Controller {

    private static $instance = null;

    protected function redirect() {
        parent::redirect("donantes");
    }

    public static function getInstance() {

        if (is_null(self::$instance)) {
            self::$instance = new static();
        }

        return self::$instance;
    }

    public function create($post) {
        /* $donante sin id de donante */
        if (parent::backendIsLogged()) {
            if (RoleService::getInstance()->hasRolePermission($_SESSION["roleID"], __CLASS__ . ":" . __FUNCTION__)) {
                $data = $post->getParams();
                $donantes = DonanteRepository::getInstance()->getByRazonSocial($data['razonSocial']);
                if (!$donantes) {
                    DonanteRepository::getInstance()->add(new DonanteModel(null, $data['razonSocial'], $data['apellido'], $data['nombre'], $data['telefono'], $data['email'], $data['domicilio']));
                    $_SESSION["message"] = new MessageService("createSuccess", ["donante con razón social " . $data['razonSocial']]);
                } else {
                    $_SESSION["message"] = new MessageService("createErrorExist", ["donante con razón social " . $data['razonSocial']]);
                }
                $this->redirect();
            }
        }
    }

    public function edit($post) {
        /* CUANDO SE LLEGA ACÀ SEGURO QUE SE TIENE UN ID CORRECTO? */
        $data = $post->getParams();
        if (parent::backendIsLogged() && RoleService::getInstance()->hasRolePermission($_SESSION["roleID"], __CLASS__ . ":" . __FUNCTION__)) {
            if (DonanteRepository::getInstance()->getByID($data['id'])) {
                $donanteModificadoID = $data['id'];
                $donanteActual = DonanteRepository::getInstance()->getByRazonSocial($data['razonSocial']);
                if (!$donanteActual) {
                    $donante = new DonanteModel($data['id'], $data['razonSocial'], $data['apellido'], $data['nombre'], $data['telefono'], $data['email'], $data['domicilio']);
                    DonanteRepository::getInstance()->edit($donante);
                    $_SESSION["message"] = new MessageService("modificationSuccess", ["donante con razón social " . $data['razonSocial']]);
                } elseif ($donanteActual->getId() === $donanteModificadoID) {
                    $donante = new DonanteModel($data['id'], $data['razonSocial'], $data['apellido'], $data['nombre'], $data['telefono'], $data['email'], $data['domicilio']);
                    DonanteRepository::getInstance()->edit($donante);
                    $_SESSION["message"] = new MessageService("modificationSuccess", ["donante con razón social " . $data['razonSocial']]);
                } else {
                    $_SESSION["message"] = new MessageService("modificationErrorExist", ["donante", "razon social (" . $data['razonSocial'] . ")"]);
                }
            } else {
                $_SESSION["message"] = new MessageService("modificationErrorNotExist", ["donante", "razon social (" . $data['razonSocial'] . ")"]);
            }
            $this->redirect();
        }
    }

    public function editView($id) {

        if (parent::backendIsLogged() && RoleService::getInstance()->hasRolePermission($_SESSION["roleID"], __CLASS__ . ":" . __FUNCTION__)) {
            $donanteInfo = DonanteRepository::getInstance()->getByID($id);
            if ($donanteInfo) {
                $view = new BackEndView();
                $view->editViewDonante($donanteInfo);
            } else {
                $_SESSION["message"] = new MessageService("modificationErrorNotExist", ["donante"]);
                $this->redirect();
            }
        }
    }

    public function remove($id) {
        /* onupdate y onremove estan en Restrict o en cascade?
          Preguntar que hacer!
         */
        if (parent::backendIsLogged() && RoleService::getInstance()->hasRolePermission($_SESSION["roleID"], __CLASS__ . ":" . __FUNCTION__)) {
            $donanteInfo = DonanteRepository::getInstance()->getByID($id);
            if ($donanteInfo) {
                DonanteRepository::getInstance()->remove($id);
                $_SESSION["message"] = new MessageService("removeSucess", ["donante"]);
            } else {
                $_SESSION["message"] = new MessageService("removeErrorNotExist", ["donante"]);
            }
            $this->redirect();
        }
    }

    public function index() {
        /* comproba si hay una sesion valida
          ese metodo deberia enviarte al inicio directamente.
         */

        if (parent::backendIsLogged() && RoleService::getInstance()->hasRolePermission($_SESSION["roleID"], __CLASS__ . ":" . __FUNCTION__)) {
            $donantes = DonanteRepository::getInstance()->getAll();
            $view = new BackEndView();
            $view->donantes($donantes);
        }
    }

}


text:
package ca.udes.android_projectweather.models.forecastdailymodel;

import android.support.annotation.Nullable;

import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

import ca.udes.android_projectweather.models.ModelConstants;

/**
 * A data temp object contains various properties, each representing the average (unless otherwise
 * specified) of a particular weather phenomenon.
 *
 * @version 1.0
 */
@SuppressWarnings("unused")
public class Temp implements Serializable {

    @Nullable
    @SerializedName(ModelConstants.FIELD_DAY)
    private Double mListTempDay;

    @Nullable
    @SerializedName(ModelConstants.FIELD_MIN)
    private Double mListTempMin;

    @Nullable
    @SerializedName(ModelConstants.FIELD_MAX)
    private Double mListTempMax;

    @Nullable
    @SerializedName(ModelConstants.FIELD_NIGHT)
    private Double mListTempNight;

    @Nullable
    @SerializedName(ModelConstants.FIELD_EVE)
    private Double mListTempEve;

    @Nullable
    @SerializedName(ModelConstants.FIELD_MORN)
    private Double mListTempMorn;

    /**
     * The day value of temperature during a given day (optional).
     *
     * @return      mListTempDay
     */
    @Nullable
    public Double getListTempDay() {
        return mListTempDay;
    }

    /**
     * The minimum value of temperature during a given day (optional).
     *
     * @return      mListTempMin
     */
    @Nullable
    public Double getListTempMin() {
        return mListTempMin;
    }

    /**
     * The maximum value of temperature during a given day (optional).
     *
     * @return      mListTempMax
     */
    @Nullable
    public Double getListTempMax() {
        return mListTempMax;
    }

    /**
     * The night value of temperature during a given day (optional).
     *
     * @return      mListTempNight
     */
    @Nullable
    public Double getListTempNight() {
        return mListTempNight;
    }

    /**
     * The evening value of temperature during a given day (optional).
     *
     * @return      mListTempEve
     */
    @Nullable
    public Double getListTempEve() {
        return mListTempEve;
    }

    /**
     * The morning value of temperature during a given day (optional).
     *
     * @return      mListTempMorn
     */
    @Nullable
    public Double getListTempMorn() {
        return mListTempMorn;
    }
}


text:
const leadImage = pcs.c1.Page.getLeadImage();
window.webkit.messageHandlers.{{messageHandlerName}}.postMessage({action: 'leadImage', data: {leadImage}});
const tableOfContents = pcs.c1.Page.getTableOfContents();
if (tableOfContents) {
    window.webkit.messageHandlers.{{messageHandlerName}}.postMessage({action: 'tableOfContents', data: {tableOfContents}});
}


text:
python_files =  __init__.py \
                abstract.py \
                store.py \
                dirstore.py \
                decorators.py

SUBDIRS =

all: default-subdirs default-all

install: all install-subdirs pyfiles-install default-install

dist: default-dist

clean: clean-subdirs default-clean

include ../../Make.rules
include ../../Make.defs


text:
package com.dubreuia.integration;

public class Class {

    public void method() {
        thisToAddMethod();
        noThisToAddMethod();
    }

    public void thisToAddMethod() {

    }

    public static void noThisToAddMethod() {

    }

}


text:
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Blake3;
using Lunet.Helpers;
using Lunet.Scripts;
using Scriban.Parsing;
using Scriban.Runtime;
using Zio;
using Zio.FileSystems;

namespace Lunet.Core;

public class ContentPlugin : SitePlugin
{
    /// <summary>
    /// The lock for tracking related dictionaries
    /// </summary>
    private readonly object _lockForTracking = new object();
    private readonly HashSet<UPath> _trackingPreviousOutputDirectories;
    private readonly HashSet<UPath> _trackingPreviousOutputFiles;
    private readonly Dictionary<UPath, UPath> _trackingFilesWritten;
    private Task _trackingPreviousTask;
    private const string SharedCacheContentKey = "content-cache-key";

    private readonly Dictionary<string, PageCollection> _mapTypeToPages;
    private bool _isInitialized;
    private readonly Stopwatch _totalDuration;

    public ContentPlugin(SiteObject site) : base(site)
    {
        _trackingPreviousOutputDirectories = new HashSet<UPath>();
        _trackingPreviousOutputFiles = new HashSet<UPath>();
        Scripts = Site.Scripts;
        _trackingFilesWritten = new Dictionary<UPath, UPath>();
        _mapTypeToPages = new Dictionary<string, PageCollection>();
        _totalDuration = new Stopwatch();

        // Setup layout types
        LayoutTypes = new ContentLayoutTypes();
        Site.SetValue(SiteVariables.LayoutTypes, LayoutTypes, true);

        BeforeInitializingProcessors = new OrderedList<ISiteProcessor>();
        BeforeLoadingProcessors = new OrderedList<ISiteProcessor>();
        BeforeLoadingContentProcessors = new OrderedList<TryProcessPreContentDelegate>();
        AfterLoadingProcessors = new OrderedList<ISiteProcessor>();
        AfterRunningProcessors = new OrderedList<IContentProcessor>();
        BeforeProcessingProcessors = new OrderedList<ISiteProcessor>();
        ContentProcessors = new OrderedList<IContentProcessor>();
        AfterProcessingProcessors = new OrderedList<ISiteProcessor>();

        Finder = new PageFinderProcessor(this);
        AfterLoadingProcessors.Add(Finder); // Make uid available before running Markdown content
    }

    private ScriptingPlugin Scripts { get; }

    public ContentLayoutTypes LayoutTypes { get; }

    public OrderedList<ISiteProcessor> BeforeInitializingProcessors { get; }

    public OrderedList<ISiteProcessor> BeforeLoadingProcessors { get; }

    public OrderedList<TryProcessPreContentDelegate> BeforeLoadingContentProcessors { get; }

    public OrderedList<ISiteProcessor> AfterLoadingProcessors { get; }

    public OrderedList<IContentProcessor> AfterRunningProcessors { get; }

    public OrderedList<ISiteProcessor> BeforeProcessingProcessors { get; }

    public OrderedList<IContentProcessor> ContentProcessors { get; }

    public OrderedList<ISiteProcessor> AfterProcessingProcessors { get; }

    public PageFinderProcessor Finder { get; }

    private int MaxDegreeOfParallelism => Site.Config.SingleThreaded ? 1 : DataflowBlockOptions.Unbounded;

    /// <summary>
    /// Determines whether if the layout type is a list layout.
    /// </summary>
    /// <param name="layoutType">Type of the layout.</param>
    /// <returns><c>true</c> if the specified layout type is a list layout; otherwise, <c>false</c>.</returns>
    public static bool IsListLayout(string layoutType)
    {
        // NOTE: this is not pluggable today, but it should be simple enough to avoid complicated setup
        return (layoutType != null && (layoutType.EndsWith("s") || layoutType.EndsWith("list")));
    }

    public void PreInitialize()
    {
        // Before loading content
        TryRunProcess(BeforeInitializingProcessors, ProcessingStage.BeforeInitializing);
    }

    public void Run()
    {
        _totalDuration.Restart();
        _trackingFilesWritten.Clear();
        Site.Statistics.Reset();

        try
        {
            // If we have any errors, early exit
            if (Site.HasErrors)
            {
                return;
            }

            // We collect all previous file entries in the output directory
            CollectPreviousFileEntries();

            // Make sure that all collections are cleared before building the content
            Site.StaticFiles.Clear();
            Site.Pages.Clear();
            Site.DynamicPages.Clear();

            // Before loading content
            Site.BeginEvent("BeforeLoadingProcessors");
            if (!TryRunProcess(BeforeLoadingProcessors, ProcessingStage.BeforeLoadingContent))
            {
                // If we have any errors during processing, early exit
                return;
            }
            Site.EndEvent();

            // Load content
            Site.BeginEvent("LoadAllContent");
            if (!LoadAllContent())
            {
                return;
            }
            Site.EndEvent();

            // Wait for collecting previous file entries concurrently
            Site.BeginEvent("WaitPreviousFiles");
            _trackingPreviousTask?.Wait();
            _trackingPreviousTask = null;
            Site.EndEvent();

            // Run all content
            Site.BeginEvent("RunAllContent");
            RunAllContent();
            Site.EndEvent();

            // Before processing content
            try
            {
                Site.BeginEvent("BeforeProcessingContent");
                if (!TryRunProcess(BeforeProcessingProcessors, ProcessingStage.BeforeProcessingContent))
                {
                    // If we have any errors during processing, early exit
                    return;
                }
            }
            finally
            {
                Site.EndEvent();
            }

            // Reset content to process
            ResetPagesPerLayoutType();

            // Collect all contents per layout type
            // Process static content files
            CollectPagesPerLayoutType(Site.StaticFiles);
            // Process pages content (files with front matter)
            CollectPagesPerLayoutType(Site.Pages);
            // Process dynamic pages content (files with front matter)
            CollectPagesPerLayoutType(Site.DynamicPages);

            // Process content per layout type
            Site.BeginEvent("LayoutContent");
            ProcessPagesPerLayoutType();
            Site.EndEvent();

            // End processing content
            Site.BeginEvent("AfterProcessingContent");
            TryRunProcess(AfterProcessingProcessors, ProcessingStage.AfterProcessingContent);
            Site.EndEvent();

            // Remove output files
            Site.BeginEvent("CleanupOutputFiles");
            CleanupOutputFiles();
            Site.EndEvent();
        }
        finally
        {
            // Update statistics
            _totalDuration.Stop();
            Site.Statistics.TotalTime = _totalDuration.Elapsed;
        }
    }

    // Used only to create a shared instance for hash
    private readonly ConcurrentDictionary<UPath, Blake3.Hash> _cacheHashInstance = new ConcurrentDictionary<UPath, Hash>();

    public bool TryCopyContentToOutput(ContentObject fromFile, UPath outputPath)
    {
        if (fromFile == null) throw new ArgumentNullException(nameof(fromFile));
        outputPath.AssertAbsolute();

        var clock = Stopwatch.StartNew();

        var outputFile = new FileEntry(Site.OutputFileSystem, outputPath);
        var outputDir = outputFile.Directory;
        if (outputDir == null)
        {
            throw new ArgumentException("Output directory cannot be empty", nameof(outputPath));
        }
        TrackDestination(outputPath, fromFile.SourceFile.Path);

        var stat = Site.Statistics.GetContentStat(fromFile);

        CreateDirectory(outputDir);

        try
        {
            // If the file has a content, we will use this instead
            if (fromFile.Content != null)
            {
                // Use a site wide cache for content hash
                if (!Site.Config.SharedCache.TryGetValue(SharedCacheContentKey, out var values) || !(values is ConcurrentDictionary<UPath, Blake3.Hash> mapPathToHash))
                {
                    mapPathToHash = (ConcurrentDictionary<UPath, Blake3.Hash>) Site.Config.SharedCache.GetOrAdd(SharedCacheContentKey, _cacheHashInstance);
                }

                // Don't output the file if the hash hasn't changed
                HashUtil.Blake3HashString(fromFile.Content, out var contentHash);
                if (!mapPathToHash.TryGetValue(outputPath, out var previousHash) || contentHash != previousHash)
                {
                    if (Site.CanTrace())
                    {
                        Site.Trace($"Write file [{outputFile}]");
                    }

                    using (var stream = outputFile.Open(FileMode.Create, FileAccess.Write))
                    {
                        stream.WriteStringOptimized(fromFile.Content, Encoding.Default);
                        stream.Flush();

                        // Update statistics
                        stat.Static = false;
                        stat.OutputBytes += stream.Length;
                    }

                    // Store the new content hash
                    mapPathToHash[outputPath] = contentHash;
                }
            }
            // If the source file is not newer than the destination file, don't overwrite it
            else if (!fromFile.SourceFile.IsEmpty && (!outputFile.Exists || (fromFile.ModifiedTime > outputFile.LastWriteTime)))
            {
                if (Site.CanTrace())
                {
                    Site.Trace($"Write file [{outputFile}]");
                }

                // If the output file is readonly, make sure that it is not readonly before overwriting
                if (outputFile.Exists && (outputFile.Attributes & FileAttributes.ReadOnly) != 0)
                {
                    outputFile.Attributes = outputFile.Attributes & ~FileAttributes.ReadOnly;
                }

                // TODO: optimize copy if source and output end-up to be PhysicalFileSystem
                fromFile.SourceFile.FileSystem.CopyFileCross(fromFile.SourceFile.Path, outputFile.FileSystem, outputFile.Path, true, false);

                // Update statistics
                stat.Static = true;
                stat.OutputBytes += fromFile.Length;
            }
        }
        catch (Exception ex)
        {
            Site.Error(ex, !fromFile.SourceFile.IsEmpty
                ? $"Unable to copy file [{fromFile.SourceFile}] to [{outputFile}]. Reason:{ex.GetReason()}"
                : $"Unable to copy file to [{outputFile}]. Reason:{ex.GetReason()}");
            return false;
        }
        finally
        {
            stat.OutputTime += clock.Elapsed;
        }

        return true;
    }

    public void TrackDestination(UPath outputFile, UPath sourceFile)
    {
        lock (_lockForTracking)
        {
            if (!sourceFile.IsEmpty)
            {
                UPath previousSourceFile;
                if (_trackingFilesWritten.TryGetValue(outputFile, out previousSourceFile))
                {
                    Site.Error($"The content [{previousSourceFile}] and [{sourceFile}] have the same Url output [{sourceFile}]");
                }
                else
                {
                    _trackingFilesWritten.Add(outputFile, sourceFile);
                }
            }

            // If the directory is used for a new file, remove it from the list of previous directories
            // Note that we remove even if things are not working after, so that previous files are kept
            // in case of an error
            var previousDir = outputFile.GetDirectory();
            while (previousDir != null)
            {
                _trackingPreviousOutputDirectories.Remove(previousDir);
                previousDir = previousDir.GetDirectory();
            }

            _trackingPreviousOutputFiles.Remove(outputFile);
        }
    }

    private bool TryRunProcess(IEnumerable<ISiteProcessor> processors, ProcessingStage stage)
    {
        var statistics = Site.Statistics;

        // Callback plugins once files have been initialized but not yet processed
        int i = 0;
        var clock = Stopwatch.StartNew();
        foreach (var processor in processors)
        {
            var stat = statistics.GetPluginStat(processor);
            stat.Order = i;

            clock.Restart();
            try
            {
                processor.Process(stage);
            }
            catch (Exception exception)
            {
                if (exception is LunetException)
                {
                    Site.Error(exception, $"Unexpected error in processor {processor.Name}. Reason: {exception.Message}");
                }
                else
                {
                    Site.Error(exception, $"Unexpected error in processor {processor.Name}. Reason: {exception.Message}");
                }
                return false;
            }
            finally
            {
                clock.Stop();
                stat.BeginProcessTime = clock.Elapsed;
            }
            i++;
        }

        return true;
    }

    private void RunPage(ContentObject page)
    {
        // Update statistics
        var evalClock = Stopwatch.StartNew();
        var contentStat = Site.Statistics.GetContentStat(page);

        if (page.Script != null && TryRunPageWithScript(page))
        {
            page.InitializeAfterRun();

            // If page is discarded, skip it
            if (page.Discard)
            {
                return;
            }
        }

        var pendingPageProcessors = new OrderedList<IContentProcessor>();
        TryProcessPage(page, ContentProcessingStage.Running, AfterRunningProcessors, pendingPageProcessors, false);

        contentStat.RunningTime += evalClock.Elapsed;
    }

    public void ProcessPages(PageCollection pages, bool copyOutput)
    {
        if (pages == null) throw new ArgumentNullException(nameof(pages));

        //foreach (var page in pages)
        //{
        //    var pendingPageProcessors = new OrderedList<IContentProcessor>();
        //    TryProcessPage(page, ContentProcessingStage.Processing, ContentProcessors, pendingPageProcessors, copyOutput);
        //}

        // Process the content of all pages
        var pageActionBlock = new ActionBlock<ContentObject>(page =>
            {
                var pendingPageProcessors = new OrderedList<IContentProcessor>();
                TryProcessPage(page, ContentProcessingStage.Processing, ContentProcessors, pendingPageProcessors, copyOutput);
            },
            new ExecutionDataflowBlockOptions()
            {
                EnsureOrdered = false,
                MaxDegreeOfParallelism = MaxDegreeOfParallelism
            }
        );

        // Process pages in order of their layout types
        foreach (var page in pages)
        {
            pageActionBlock.Post(page);
        }

        pageActionBlock.Complete();
        pageActionBlock.Completion.Wait();
    }

    private void ResetPagesPerLayoutType()
    {
        // Don't remove the PageCollection (to keep them allocated around)
        foreach (var mapTypeToPage in _mapTypeToPages)
        {
            mapTypeToPage.Value.Clear();
        }
    }

    private void CollectPagesPerLayoutType(PageCollection pages)
    {
        if (pages == null) throw new ArgumentNullException(nameof(pages));

        // Collect and group pages per their layout type
        foreach (var page in pages)
        {
            var layoutType = page.LayoutType ?? ContentLayoutTypes.Single;
            if (!_mapTypeToPages.TryGetValue(layoutType, out var subPages))
            {
                subPages = new PageCollection();
                _mapTypeToPages.Add(layoutType, subPages);
            }
            subPages.Add(page);
        }
    }

    private void ProcessPagesPerLayoutType()
    {
        var layoutTypes = _mapTypeToPages.Keys.OrderBy(x => LayoutTypes.GetSafeValue<int>(x)).ToList();
        foreach (var layoutType in layoutTypes)
        {
            var pages = _mapTypeToPages[layoutType];
            ProcessPages(pages, true);
        }
    }

    private bool LoadAllContent()
    {
        Site.StaticFiles.Clear();
        Site.Pages.Clear();

        // Load a content asynchronously
        var contentLoaderBlock = new TransformBlock<(FileSystemItem, int), ContentObject>(
            reference =>
            {
                var content = LoadContent(reference.Item1);
                // We transfer the weight to the content
                if (content[PageVariables.Weight] == null)
                {
                    content.Weight = reference.Item2;
                }
                return content;
            },
            new ExecutionDataflowBlockOptions()
            {
                EnsureOrdered = false,
                MaxDegreeOfParallelism = MaxDegreeOfParallelism
            });

        // Add the content loaded to the correct list (static vs pages)
        var contentAdderBlock = new ActionBlock<ContentObject>(content =>
        {
            // We don't need lock as this block has a MaxDegreeOfParallelism = 1
            var list = content.Script != null ? Site.Pages : Site.StaticFiles;
            list.Add(content);
        });

        // Link loader and adder
        contentLoaderBlock.LinkTo(contentAdderBlock, new DataflowLinkOptions() { PropagateCompletion = true });

        // We don't use a block for this part (annoying without struct tuples)

        // Compute the list of files that we will actually process
        var directories = new Queue<DirectoryEntry>();
        directories.Enqueue(new DirectoryEntry(Site.FileSystem, UPath.Root));
        while (directories.Count > 0)
        {
            var nextDirectory = directories.Dequeue();
            // The weight is the order in the directory by name
            int weight = 10;
            foreach (var contentReference in LoadDirectory(nextDirectory, directories).OrderBy(x => x.Path))
            {
                contentLoaderBlock.Post((contentReference, weight));
                weight += 10;
            }
        }

        // We are done loading content, wait for completion
        contentLoaderBlock.Complete();
        contentAdderBlock.Completion.Wait();

        // Right after we have been loading the content, we can iterate on all content
        if (!TryRunProcess(AfterLoadingProcessors, ProcessingStage.AfterLoadingContent))
        {
            // If we have any errors during processing, early exit
            return false;
        }

        return true;
    }

    private void RunAllContent()
    {
        // Uncomment to dispatch on multithread
        //const int MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded;
        //const int MaxDegreeOfParallelism = 1;

        // Run script content asynchronously
        var contentRunnerBlock = new ActionBlock<ContentObject>(
            RunPage,
            new ExecutionDataflowBlockOptions()
            {
                EnsureOrdered = false,
                MaxDegreeOfParallelism = MaxDegreeOfParallelism
            });

        foreach (var page in Site.Pages)
        {
            contentRunnerBlock.Post(page);
        }
        foreach (var page in Site.StaticFiles)
        {
            contentRunnerBlock.Post(page);
        }

        contentRunnerBlock.Complete();
        contentRunnerBlock.Completion.Wait();

        // Finally, we sort pages by natural order
        Site.Pages.Sort();
    }

    private IEnumerable<FileSystemItem> LoadDirectory(DirectoryEntry directory, Queue<DirectoryEntry> directoryQueue)
    {
        foreach (var item in directory.EnumerateItems())
        {
            if (!Site.IsHandlingPath(item.Path))
            {
                continue;
            }

            if (item.IsDirectory)
            {
                if (item.GetName() != SiteFileSystems.LunetFolder)
                {
                    directoryQueue.Enqueue(new DirectoryEntry(directory.FileSystem, item.Path));
                }
            }
            else
            {
                yield return item;
            }
        }
    }

    private ContentObject LoadContent(FileSystemItem item)
    {
        ContentObject page = null;
        Span<byte> buffer = stackalloc byte[16];

        var clock = Stopwatch.StartNew();

        var stream = item.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        try
        {
            var count = stream.Read(buffer);
            // Rewind to 0
            stream.Position = 0;

            bool hasFrontMatter = false;
            bool isBinary = false;

            int startFrontMatter = 0;

            // Does it start with UTF8 BOM? If yes, skip it
            // EF BB BF
            if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF)
            {
                startFrontMatter = 3;
            }

            var newBuffer = buffer.Slice(startFrontMatter);
            foreach (var frontParser in Scripts.FrontMatterParsers)
            {
                if (frontParser.CanHandle(newBuffer))
                {
                    for (int i = startFrontMatter + 3; i < count; i++)
                    {
                        if (buffer[i] == 0)
                        {
                            isBinary = true;
                            break;
                        }
                    }

                    if (!isBinary)
                    {
                        hasFrontMatter = true;
                    }

                    break;
                }
            }

            // Run pre-content (e.g AttributesPlugin)
            ScriptObject preContent = null;
            foreach (var preLoadingContentProcessor in BeforeLoadingContentProcessors)
            {
                preLoadingContentProcessor(item.Path, ref preContent);
            }

            if (hasFrontMatter)
            {
                page = LoadPageScript(Site, stream, item, preContent);
                stream = null;
            }
            else
            {

                page = new FileContentObject(Site, item, preContent: preContent);

                //// Run pre-processing on static content as well
                //var pendingPageProcessors = new OrderedList<IContentProcessor>();
                //TryProcessPage(page, ContentProcessingStage.AfterLoading, AfterLoadingProcessors, pendingPageProcessors, false);
            }

            // Initialize the page loaded
            page?.Initialize();
        }
        finally
        {
            // Dispose stream used
            stream?.Dispose();
        }

        clock.Stop();
        Site.Statistics.GetContentStat(page).LoadingParsingTime += clock.Elapsed;

        return page;
    }

    private static ContentObject LoadPageScript(SiteObject site, Stream stream, FileSystemItem file, ScriptObject preContent)
    {
        var evalClock = Stopwatch.StartNew();
        // Read the stream
        string content;
        {
            using var reader = new StreamReader(stream);
            content = reader.ReadToEnd();
        }

        ContentObject page = null;

        // Parse the page, using front-matter mode
        var scriptInstance = site.Scripts.ParseScript(content, file.Path.FullName, ScriptMode.FrontMatterAndContent);
        if (!scriptInstance.HasErrors)
        {
            page = new FileContentObject(site, file, scriptInstance, preContent: preContent);
        }
        evalClock.Stop();

        // Update statistics
        var contentStat = site.Statistics.GetContentStat(page);
        contentStat.LoadingTime += evalClock.Elapsed;

        return page;
    }

    private bool TryProcessPage(ContentObject page, ContentProcessingStage stage, IEnumerable<IContentProcessor> pageProcessors, OrderedList<IContentProcessor> pendingPageProcessors, bool copyOutput)
    {
        // If page is discarded, skip it
        if (page.Discard)
        {
            return false;
        }

        // By default working on all processors
        // Order is important!
        pendingPageProcessors.AddRange(pageProcessors);
        bool hasBeenProcessed = true;
        bool breakProcessing = false;

        // We process the page going through all IContentProcessor from the end of the list
        // (more priority) to the beginning of the list (less priority).
        // An IContentProcessor can transform the page to another type of content
        // that could then be processed by another IContentProcessor
        // But we make sure that a processor cannot process a page more than one time
        // to avoid an infinite loop
        var clock = Stopwatch.StartNew();
        while (hasBeenProcessed && !breakProcessing && !page.Discard)
        {
            hasBeenProcessed = false;
            for (int i = pendingPageProcessors.Count - 1; i >= 0; i--)
            {
                var processor = pendingPageProcessors[i];

                // Note that page.ContentType can be changed by a processor
                // while processing a page
                clock.Restart();
                try
                {
                    var result = processor.TryProcessContent(page, stage);

                    if (result != ContentResult.None)
                    {
                        // Update statistics per plugin
                        var statistics = Site.Statistics;
                        var stat = statistics.GetPluginStat(processor);
                        stat.PageCount++;
                        stat.ContentProcessTime += clock.Elapsed;

                        hasBeenProcessed = true;
                        pendingPageProcessors.RemoveAt(i);
                        breakProcessing = result == ContentResult.Break;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (ex is LunetException lunetEx)
                    {
                        Site.Error(ex, $"Error while processing {page.Path} by {processor.Name} processor. {lunetEx.Message}");
                    }
                    else
                    {
                        Site.Error(ex, $"Error while processing {page.Path} by {processor.Name} processor.");
                    }
                    breakProcessing = true;
                    hasBeenProcessed = true;
                    break;
                }
            }
        }
        pendingPageProcessors.Clear();

        // Copy only if the file are marked as include
        if (copyOutput && !breakProcessing && !page.Discard)
        {
            Site.Content.TryCopyContentToOutput(page, page.GetDestinationPath());
        }

        return true;
    }

    private bool TryRunPageWithScript(ContentObject page)
    {
        page.ScriptObjectLocal ??= new ScriptObject();
        return Site.Scripts.TryEvaluatePage(page, page.Script, page.SourceFile.Path, page);
    }

    public void CreateDirectory(DirectoryEntry directory)
    {
        if (!directory.Exists)
        {
            if (Site.CanTrace())
            {
                Site.Trace($"Create directory [{directory}]");
            }

            try
            {
                directory.Create();
            }
            catch (Exception ex)
            {
                Site.Error(ex, $"Unable to create directory [{directory}]. Reason:{ex.GetReason()}");
            }
        }
    }

    private void CleanupOutputFiles()
    {
        var outputFs = Site.OutputFileSystem;
        // Remove all previous files that have not been generated
        foreach (var outputFile in _trackingPreviousOutputFiles)
        {
            try
            {
                if (outputFs.FileExists(outputFile))
                {
                    if (Site.CanTrace())
                    {
                        Site.Trace($"Delete file [{outputFile}]");
                    }
                    outputFs.DeleteFile(outputFile);
                }
            }
            catch (Exception)
            {
                // ignore
            }
        }

        foreach (var outputDirectory in _trackingPreviousOutputDirectories)
        {
            try
            {
                if (outputFs.DirectoryExists(outputDirectory))
                {
                    if (Site.CanTrace())
                    {
                        Site.Trace($"Delete directory [{outputDirectory}]");
                    }
                    outputFs.DeleteDirectory(outputDirectory, true);
                }
            }
            catch (Exception)
            {
                // ignore
            }
        }
    }

    private void CollectPreviousFileEntries()
    {
        _trackingPreviousOutputDirectories.Clear();
        _trackingPreviousOutputFiles.Clear();

        var outputFs = Site.OutputFileSystem;
        _trackingPreviousTask = null;
        if (!outputFs.DirectoryExists(UPath.Root))
        {
            return;
        }

        _trackingPreviousTask = new Task(() =>
            {
                Site.BeginEvent("Collect Previous Files");
                foreach (var entry in outputFs.EnumerateItems(UPath.Root, SearchOption.AllDirectories))
                {
                    if (entry.IsDirectory)
                    {
                        _trackingPreviousOutputDirectories.Add(entry.Path);
                    }
                    else
                    {
                        _trackingPreviousOutputFiles.Add(entry.Path);
                    }
                }
                Site.EndEvent();
            }
        );
        _trackingPreviousTask.Start();
    }

    private readonly struct RawFileEntry : IEquatable<RawFileEntry>
    {
        public RawFileEntry(IFileSystem fileSystem, UPath absolutePath, UPath path)
        {
            FileSystem = fileSystem;
            Path = path;
            AbsolutePath = absolutePath;
        }

        public readonly IFileSystem FileSystem;

        public readonly UPath Path;

        public readonly UPath AbsolutePath;

        public bool Equals(RawFileEntry other)
        {
            return FileSystem.Equals(other.FileSystem) && Path.Equals(other.Path);
        }

        public override bool Equals(object obj)
        {
            return obj is RawFileEntry other && Equals(other);
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(FileSystem, Path);
        }

        public static bool operator ==(RawFileEntry left, RawFileEntry right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(RawFileEntry left, RawFileEntry right)
        {
            return !left.Equals(right);
        }
    }
}


text:
/*	$KAME: dhcp6_ctl.c,v 1.4 2004/09/07 05:03:03 jinmei Exp $	*/

/*
 * Copyright (C) 2004 WIDE Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
#include <sys/param.h>
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>

#include <netinet/in.h>

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <syslog.h>
#include <netdb.h>
#include <errno.h>

#include <dhcp6.h>
#include <config.h>
#include <common.h>
#include <auth.h>
#include <base64.h>
#include <control.h>
#include <dhcp6_ctl.h>

TAILQ_HEAD(dhcp6_commandqueue, dhcp6_commandctx);

static struct dhcp6_commandqueue commandqueue_head;
static int max_commands;
static int commands = 0;

struct dhcp6_commandctx {
	TAILQ_ENTRY(dhcp6_commandctx) link;

	int s;			/* communication socket */
	char inputbuf[1024];	/* input buffer */
	ssize_t input_len;
	ssize_t input_filled;
	int (*callback)(char *, ssize_t);
};

int
dhcp6_ctl_init(const char *addr, const char *port, int max, int *sockp)
{
	struct addrinfo hints, *res = NULL;
	int on;
	int error;
	int ctlsock = -1;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET6;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	error = getaddrinfo(addr, port, &hints, &res);
	if (error) {
		debugprintf(LOG_ERR, FNAME, "getaddrinfo: %s",
		    gai_strerror(error));
		return (-1);
	}
	ctlsock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
	if (ctlsock < 0) {
		debugprintf(LOG_ERR, FNAME, "socket(control sock): %s",
		    strerror(errno));
		goto fail;
	}
	on = 1;
	if (setsockopt(ctlsock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
	    < 0) {
		debugprintf(LOG_ERR, FNAME,
		    "setsockopt(control sock, SO_REUSEADDR: %s",
		    strerror(errno));
		goto fail;
	}
	if (bind(ctlsock, res->ai_addr, res->ai_addrlen) < 0) {
		debugprintf(LOG_ERR, FNAME, "bind(control sock): %s",
		    strerror(errno));
		goto fail;
	}
	freeaddrinfo(res);
	if (listen(ctlsock, 1)) {
		debugprintf(LOG_ERR, FNAME, "listen(control sock): %s",
		    strerror(errno));
		goto fail;
	}

	TAILQ_INIT(&commandqueue_head);

	if (max <= 0) {
		debugprintf(LOG_ERR, FNAME,
		    "invalid maximum number of commands (%d)", max_commands);
		goto fail;
	}
	max_commands = max;

	*sockp = ctlsock;
	return (0);

  fail:
	if (res != NULL)
		freeaddrinfo(res);
	if  (ctlsock >= 0)
		close(ctlsock);

	return (-1);
}

int
dhcp6_ctl_authinit(const char *keyfile, struct keyinfo **keyinfop,
    int *digestlenp)
{
	FILE *fp = NULL;
	struct keyinfo *ctlkey = NULL;
	char line[1024], secret[1024];
	int secretlen;

	/* Currently, we only support HMAC-MD5 for authentication. */
	*digestlenp = MD5_DIGESTLENGTH;

	if ((fp = fopen(keyfile, "r")) == NULL) {
		debugprintf(LOG_ERR, FNAME, "failed to open %s: %s", keyfile,
		    strerror(errno));
		return (-1);
	}
	if (fgets(line, sizeof(line), fp) == NULL && ferror(fp)) {
		debugprintf(LOG_ERR, FNAME, "failed to read key file: %s",
		    strerror(errno));
		goto fail;
	}
	if ((secretlen = base64_decodestring(line, secret, sizeof(secret)))
	    < 0) {
		debugprintf(LOG_ERR, FNAME, "failed to decode base64 string");
		goto fail;
	}
	if ((ctlkey = malloc(sizeof(*ctlkey))) == NULL) {
		debugprintf(LOG_WARNING, FNAME, "failed to allocate control key");
		goto fail;
	}
	memset(ctlkey, 0, sizeof(*ctlkey));
	if ((ctlkey->secret = malloc(secretlen)) == NULL) {
		debugprintf(LOG_WARNING, FNAME, "failed to allocate secret key");
		goto fail;
	}
	ctlkey->secretlen = (size_t)secretlen;
	memcpy(ctlkey->secret, secret, secretlen);

	fclose(fp);

	*keyinfop = ctlkey;
	return (0);

  fail:
	if (fp != NULL)
		fclose(fp);
	if (ctlkey != NULL && ctlkey->secret != NULL)
		free(ctlkey->secret);
	if (ctlkey != NULL)
		free(ctlkey);

	return (-1);
}

int
dhcp6_ctl_acceptcommand(int sl, int (*callback)(char *, ssize_t))
{
	int s;
	struct sockaddr_storage from_ss;
	struct sockaddr *from = (struct sockaddr *)&from_ss;
	socklen_t fromlen;
	struct dhcp6_commandctx *ctx, *new;

	fromlen = sizeof(from_ss);
	if ((s = accept(sl, from, &fromlen)) < 0) {
		debugprintf(LOG_WARNING, FNAME,
		    "failed to accept control connection: %s",
		    strerror(errno));
		return (-1);
	}

	debugprintf(LOG_DEBUG, FNAME, "accept control connection from %s",
	    addr2str(from));

	if (max_commands <= 0) {
		debugprintf(LOG_ERR, FNAME, "command queue is not initialized");
		close(s);
		return (-1);
	}

	new = malloc(sizeof(*new));
	if (new == NULL) {
		debugprintf(LOG_WARNING, FNAME,
		    "failed to allocate new command context");
		goto fail;
	}

	/* if the command queue is full, purge the oldest one */
	if (commands == max_commands) {
		ctx = TAILQ_FIRST(&commandqueue_head);

		debugprintf(LOG_INFO, FNAME, "command queue is full. "
		    "drop the oldest one (fd=%d)", ctx->s);

		TAILQ_REMOVE(&commandqueue_head, ctx, link);
		dhcp6_ctl_closecommand(ctx);
	}

	/* insert the next context to the queue */
	memset(new, 0, sizeof(*new));
	new->s = s;
	new->callback = callback;
	new->input_len = sizeof(struct dhcp6ctl);
	TAILQ_INSERT_TAIL(&commandqueue_head, new, link);
	commands++;

	return (0);

  fail:
	close(s);

	return (-1);
}

void
dhcp6_ctl_closecommand(struct dhcp6_commandctx *ctx)
{
	close(ctx->s);
	free(ctx);

	if (commands == 0) {
		debugprintf(LOG_ERR, FNAME, "assumption error: "
		    "command queue is empty?");
		exit(1);	/* XXX */
	}
	commands--;

	return;
}

int
dhcp6_ctl_readcommand(fd_set *read_fds)
{
	struct dhcp6_commandctx *ctx, *ctx_next;
	char *cp;
	int cc, resid, result;
	struct dhcp6ctl *ctlhead;

	for (ctx = TAILQ_FIRST(&commandqueue_head); ctx != NULL;
	    ctx = ctx_next) {
		ctx_next = TAILQ_NEXT(ctx, link);

		if (FD_ISSET(ctx->s, read_fds)) {
			cp = ctx->inputbuf + ctx->input_filled;
			resid = ctx->input_len - ctx->input_filled;

			cc = read(ctx->s, cp, resid);
			if (cc < 0) {
				debugprintf(LOG_WARNING, FNAME, "read failed: %s",
				    strerror(errno));
				goto closecommand;
			}
			if (cc == 0) {
				debugprintf(LOG_INFO, FNAME,
				    "control channel was reset by peer");
				goto closecommand;
			}

			ctx->input_filled += cc;
			if (ctx->input_filled < ctx->input_len)
				continue; /* we need more data */
			else if (ctx->input_filled == sizeof(*ctlhead)) {
				ctlhead = (struct dhcp6ctl *)ctx->inputbuf;
				ctx->input_len += ntohs(ctlhead->len);
			}

			if (ctx->input_filled == ctx->input_len) {
				/* we're done.  execute the command. */
				result = (ctx->callback)(ctx->inputbuf,
				    ctx->input_len);

				switch (result) {
				case DHCP6CTL_R_DONE:
				case DHCP6CTL_R_FAILURE:
					goto closecommand;
				default:
					break;
				}
			} else if (ctx->input_len > sizeof(ctx->inputbuf)) {
				debugprintf(LOG_INFO, FNAME,
				    "too large command (%ld bytes)",
				    ctx->input_len);
				goto closecommand;
			}

			continue;

		  closecommand:
			TAILQ_REMOVE(&commandqueue_head, ctx, link);
			dhcp6_ctl_closecommand(ctx);
		}
	}

	return (0);
}

int
dhcp6_ctl_setreadfds(fd_set *read_fds, int *maxfdp)
{
	int maxfd = *maxfdp;
	struct dhcp6_commandctx *ctx;

	for (ctx = TAILQ_FIRST(&commandqueue_head); ctx != NULL;
	    ctx = TAILQ_NEXT(ctx, link)) {
		FD_SET(ctx->s, read_fds);
		if (ctx->s > maxfd)
			maxfd = ctx->s;
	}

	*maxfdp = maxfd;

	return (0);
}