text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE690_NULL_Deref_From_Return__fopen_06.c
Label Definition File: CWE690_NULL_Deref_From_Return.fclose.label.xml
Template File: source-sinks-06.tmpl.c
*/
/*
 * @description
 * CWE: 690 Unchecked Return Value To NULL Pointer
 * BadSource: fopen Open data with fopen()
 * Sinks: 0
 *    GoodSink: Check data for NULL
 *    BadSink : Do not check data for NULL
 * Flow Variant: 06 Control flow: if(STATIC_CONST_FIVE==5) and if(STATIC_CONST_FIVE!=5)
 *
 * */

#include "std_testcase.h"

/* The variable below is declared "const", so a tool should be able
   to identify that reads of this will always give its initialized
   value. */
static const int STATIC_CONST_FIVE = 5;

#ifndef OMITBAD

void CWE690_NULL_Deref_From_Return__fopen_06_bad()
{
    FILE * data;
    /* Initialize data */
    data = NULL;
    /* POTENTIAL FLAW: Open a file without checking the return value for NULL */
    data = fopen("file.txt", "w+");
    if(STATIC_CONST_FIVE==5)
    {
        /* FLAW: if the fopen failed, data will be NULL here */
        fclose(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G1() - use badsource and goodsink by changing STATIC_CONST_FIVE==5 to STATIC_CONST_FIVE!=5 */
static void goodB2G1()
{
    FILE * data;
    /* Initialize data */
    data = NULL;
    /* POTENTIAL FLAW: Open a file without checking the return value for NULL */
    data = fopen("file.txt", "w+");
    if(STATIC_CONST_FIVE!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: check the return value */
        if (data != NULL)
        {
            fclose(data);
        }
    }
}

/* goodB2G2() - use badsource and goodsink by reversing statements in if  */
static void goodB2G2()
{
    FILE * data;
    /* Initialize data */
    data = NULL;
    /* POTENTIAL FLAW: Open a file without checking the return value for NULL */
    data = fopen("file.txt", "w+");
    if(STATIC_CONST_FIVE==5)
    {
        /* FIX: check the return value */
        if (data != NULL)
        {
            fclose(data);
        }
    }
}

void CWE690_NULL_Deref_From_Return__fopen_06_good()
{
    goodB2G1();
    goodB2G2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE690_NULL_Deref_From_Return__fopen_06_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE690_NULL_Deref_From_Return__fopen_06_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
/**
 * Created by Yuriy Stul 16 May 2018
 */
package com.stulsoft.poc.prometheus.pushapp1;

import java.io.IOException;
import java.util.Date;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.PushGateway;

/**
 * @author Yuriy Stul
 *
 */
public class Main {
	private static final Logger logger = LoggerFactory.getLogger(Main.class);

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		logger.info("Started Main");

		Random random = new Random(System.currentTimeMillis());

		CollectorRegistry registry = new CollectorRegistry();
		Counter counter = Counter
				.build("wp_pushapp1_counter1", "The counter # 1")
				.register(registry);
		Gauge gauge = Gauge
				.build("wp_pushapp1_gauge1", "The gauge # 1")
				.register(registry);
		Gauge duration = Gauge
				.build("wp_pushapp1_duration", "Duration of pushapp1 service")
				.register(registry);
		Gauge lastSuccess = Gauge
				.build("wp_pushapp1_last_success", "Last time of success for pushapp1 service")
				.register(registry);
		Gauge runningStatus = Gauge
				.build("wp_pushapp1_running", "Running status for pushapp1 service")
				.register(registry);
		Gauge executionTime = Gauge
				.build("wp_pushapp1_execution_time", "Execution time for pushapp1 service")
				.register(registry);

		logger.info("Set status to 1.0");
		runningStatus.set(1.0);
		PushGateway pushGateway = new PushGateway("localhost:9091");
		try {
			pushGateway.pushAdd(registry, "pushapp1_job");
			logger.info("Pushed metrics");
		} catch (IOException e) {
			logger.error("Failed during push. {}", e.getMessage());
		}

		executionTime.set(Utils.timeToMinutes(new Date(System.currentTimeMillis())));
		logger.info("executionTime = {}", executionTime.get());
		counter.inc();
		gauge.set(random.nextDouble());
		Gauge.Timer durationTimer = duration.startTimer();
		try {
			Thread.sleep((long) (20000 * random.nextDouble()));
			lastSuccess.setToCurrentTime();
			logger.info("lastSuccess = {}", lastSuccess.get());
		} catch (InterruptedException ignore) {
		} finally {
			durationTimer.setDuration();
		}

		try {
			Thread.sleep(15000);
			logger.info("Set status to 0.0");
			runningStatus.set(0.0);
		} catch (Exception ignore) {
		}

		try {
			pushGateway.pushAdd(registry, "pushapp1_job");
			logger.info("Pushed metrics");
		} catch (IOException e) {
			logger.error("Failed during push. {}", e.getMessage());
		}
		logger.info("Stopped Main");
	}
}

redpajama_set_name: RedPajamaGithub


text:
using ASPNETCoreIdentitySample.Common.IdentityToolkit;
using ASPNETCoreIdentitySample.Entities.Identity;
using ASPNETCoreIdentitySample.Services.Contracts.Identity;
using ASPNETCoreIdentitySample.Services.Identity;
using ASPNETCoreIdentitySample.ViewModels.Identity;
using ASPNETCoreIdentitySample.ViewModels.Identity.Emails;
using ASPNETCoreIdentitySample.ViewModels.Identity.Settings;
using DNTBreadCrumb.Core;
using DNTCommon.Web.Core;
using DNTPersianUtils.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace ASPNETCoreIdentitySample.Areas.Identity.Controllers;

[Authorize(Roles = ConstantRoles.Admin), Area(AreaConstants.IdentityArea),
 BreadCrumb(Title = "تغییر کلمه‌ی عبور كاربر توسط مدير سيستم", UseDefaultRouteUrl = true, Order = 0)]
public class ChangeUserPasswordController : Controller
{
    private readonly IEmailSender _emailSender;
    private readonly IPasswordValidator<User> _passwordValidator;
    private readonly IApplicationSignInManager _signInManager;
    private readonly IOptionsSnapshot<SiteSettings> _siteOptions;
    private readonly IUsedPasswordsService _usedPasswordsService;
    private readonly IApplicationUserManager _userManager;

    public ChangeUserPasswordController(
        IApplicationUserManager userManager,
        IApplicationSignInManager signInManager,
        IEmailSender emailSender,
        IPasswordValidator<User> passwordValidator,
        IUsedPasswordsService usedPasswordsService,
        IOptionsSnapshot<SiteSettings> siteOptions)
    {
        _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
        _signInManager = signInManager ?? throw new ArgumentNullException(nameof(signInManager));
        _passwordValidator = passwordValidator ?? throw new ArgumentNullException(nameof(passwordValidator));
        _usedPasswordsService = usedPasswordsService ?? throw new ArgumentNullException(nameof(usedPasswordsService));
        _emailSender = emailSender ?? throw new ArgumentNullException(nameof(emailSender));
        _siteOptions = siteOptions ?? throw new ArgumentNullException(nameof(siteOptions));
    }

    [BreadCrumb(Title = "ایندکس", Order = 1)]
    public async Task<IActionResult> Index(int? id)
    {
        if (!id.HasValue)
        {
            return View("NotFound");
        }

        var user = await _userManager.FindByIdAsync(id.Value.ToString(CultureInfo.InvariantCulture));
        if (user == null)
        {
            return View("NotFound");
        }

        return View(new ChangeUserPasswordViewModel
        {
            UserId = user.Id,
            Name = user.UserName
        });
    }

    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Index(ChangeUserPasswordViewModel model)
    {
        if (model is null)
        {
            return View("Error");
        }

        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var user = await _userManager.FindByIdAsync(model.UserId.ToString(CultureInfo.InvariantCulture));
        if (user == null)
        {
            return View("NotFound");
        }

        var result = await _userManager.UpdatePasswordHash(user, model.NewPassword, true);
        if (result.Succeeded)
        {
            await _userManager.UpdateSecurityStampAsync(user);

            // reflect the changes in the Identity cookie
            await _signInManager.RefreshSignInAsync(user);

            await _emailSender.SendEmailAsync(
                user.Email,
                "اطلاع رسانی تغییر کلمه‌ی عبور",
                "~/Areas/Identity/Views/EmailTemplates/_ChangePasswordNotification.cshtml",
                new ChangePasswordNotificationViewModel
                {
                    User = user,
                    EmailSignature = _siteOptions.Value.Smtp.FromName,
                    MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString()
                });

            return RedirectToAction(nameof(Index), "UserCard", new { id = user.Id });
        }

        foreach (var error in result.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }

        return View(model);
    }

    /// <summary>
    ///     For [Remote] validation
    /// </summary>
    [AjaxOnly, HttpPost, ValidateAntiForgeryToken, ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
    public async Task<IActionResult> ValidatePassword(string newPassword, int userId)
    {
        var user = await _userManager.FindByIdAsync(userId.ToString(CultureInfo.InvariantCulture));
        var result = await _passwordValidator.ValidateAsync(
            (UserManager<User>)_userManager, user, newPassword);
        return Json(result.Succeeded ? "true" : result.DumpErrors(true));
    }
}


text:
using System;

namespace PowerArgs
{
    /// <summary>
    /// An attribute that you can add to argument properties or parameters that lets you inject custom contextual assistant logic into the PowerArgs enhanced command line.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
    public class ArgContextualAssistant : Attribute, ICommandLineArgumentMetadata
    {
        /// <summary>
        /// Gets the type to be used for contexual assistance.  It must implement IContextAssistProvider.
        /// </summary>
        public Type ContextAssistProviderType { get; private set; }

        private IContextAssistProvider _cachedProvider;

        internal IContextAssistProvider GetContextAssistProvider(CommandLineArgumentsDefinition definition)
        {
            if (_cachedProvider == null)
            {
                try
                {
                    ContextAssistProviderType.TryCreate<IContextAssistProvider>(new object[] { definition }, out _cachedProvider);
                }
                catch (InvalidArgDefinitionException)
                {
                    ContextAssistProviderType.TryCreate<IContextAssistProvider>(out _cachedProvider);
                }
            }
            return _cachedProvider;
        }

        /// <summary>
        /// Initializes the metadata given the type that implements IContextAssistProvider.
        /// </summary>
        /// <param name="contextAssistProviderType">a type that implements IContextAssistProvider</param>
        public ArgContextualAssistant(Type contextAssistProviderType)
        {
            this.ContextAssistProviderType = contextAssistProviderType;
        }
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/content/base/public/nsISelectionController.idl
 */

#ifndef __gen_nsISelectionController_h__
#define __gen_nsISelectionController_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

#ifndef __gen_nsISelection_h__
#include "nsISelection.h"
#endif

#ifndef __gen_nsISelectionDisplay_h__
#include "nsISelectionDisplay.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
typedef short SelectionType;
typedef short SelectionRegion;
class nsIDOMNode; /* forward declaration */

class nsISelection; /* forward declaration */

class nsISelectionDisplay; /* forward declaration */

/* starting interface:    nsISelectionController */
#define NS_ISELECTIONCONTROLLER_IID_STR "ff11fa25-788f-444f-8f69-dcdf14348fb3"

#define NS_ISELECTIONCONTROLLER_IID \
  {0xff11fa25, 0x788f, 0x444f, \
    { 0x8f, 0x69, 0xdc, 0xdf, 0x14, 0x34, 0x8f, 0xb3 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsISelectionController : public nsISelectionDisplay {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISELECTIONCONTROLLER_IID)

  enum { SELECTION_NONE = 0 };

  enum { SELECTION_NORMAL = 1 };

  enum { SELECTION_SPELLCHECK = 2 };

  enum { SELECTION_IME_RAWINPUT = 4 };

  enum { SELECTION_IME_SELECTEDRAWTEXT = 8 };

  enum { SELECTION_IME_CONVERTEDTEXT = 16 };

  enum { SELECTION_IME_SELECTEDCONVERTEDTEXT = 32 };

  enum { SELECTION_ACCESSIBILITY = 64 };

  enum { SELECTION_FIND = 128 };

  enum { NUM_SELECTIONTYPES = 9 };

  enum { SELECTION_ANCHOR_REGION = 0 };

  enum { SELECTION_FOCUS_REGION = 1 };

  enum { SELECTION_WHOLE_SELECTION = 2 };

  enum { NUM_SELECTION_REGIONS = 3 };

  enum { SELECTION_OFF = 0 };

  enum { SELECTION_HIDDEN = 1 };

  enum { SELECTION_ON = 2 };

  enum { SELECTION_DISABLED = 3 };

  enum { SELECTION_ATTENTION = 4 };

  /**
   * SetDisplaySelection will set the display mode for the selection. OFF,ON,DISABLED
   */
  /* void setDisplaySelection (in short toggle); */
  NS_SCRIPTABLE NS_IMETHOD SetDisplaySelection(PRInt16 toggle) = 0;

  /**
   * GetDisplaySelection will get the display mode for the selection. OFF,ON,DISABLED
   */
  /* short getDisplaySelection (); */
  NS_SCRIPTABLE NS_IMETHOD GetDisplaySelection(PRInt16 *_retval NS_OUTPARAM) = 0;

  /**
   * GetSelection will return the selection that the presentation
   *  shell may implement.
   *
   * @param aType will hold the type of selection //SelectionType
   * @param _return will hold the return value
   */
  /* nsISelection getSelection (in short type); */
  NS_SCRIPTABLE NS_IMETHOD GetSelection(PRInt16 type, nsISelection **_retval NS_OUTPARAM) = 0;

  enum { SCROLL_SYNCHRONOUS = 2 };

  enum { SCROLL_FIRST_ANCESTOR_ONLY = 4 };

  /**
   * ScrollSelectionIntoView scrolls a region of the selection,
   * so that it is visible in the scrolled view.
   *
   * @param aType the selection to scroll into view. //SelectionType
   * @param aRegion the region inside the selection to scroll into view. //SelectionRegion
   * @param aFlags the scroll flags.  Valid bits include:
   * SCROLL_SYNCHRONOUS: when set, scrolls the selection into view
   * before returning. If not set, posts a request which is processed
   * at some point after the method returns.
   * SCROLL_FIRST_ANCESTOR_ONLY: if set, only the first ancestor will be scrolled
   * into view.
   *
   * Note that if isSynchronous is true, then this might flush the pending
   * reflow. It's dangerous for some objects. See bug 418470 comment 12.
   */
  /* void scrollSelectionIntoView (in short type, in short region, in short flags); */
  NS_SCRIPTABLE NS_IMETHOD ScrollSelectionIntoView(PRInt16 type, PRInt16 region, PRInt16 flags) = 0;

  /**
   * RepaintSelection repaints the selection specified by aType.
   *
   * @param aType specifies the selection to repaint.
   */
  /* void repaintSelection (in short type); */
  NS_SCRIPTABLE NS_IMETHOD RepaintSelection(PRInt16 type) = 0;

  /**
   * Set the caret as enabled or disabled. An enabled caret will
   * draw or blink when made visible. A disabled caret will never show up.
   * Can be called any time.
   * @param aEnable PR_TRUE to enable caret.  PR_FALSE to disable.
   * @return always NS_OK
   */
  /* void setCaretEnabled (in boolean enabled); */
  NS_SCRIPTABLE NS_IMETHOD SetCaretEnabled(PRBool enabled) = 0;

  /**
   * Set the caret readonly or not. An readonly caret will
   * draw but not blink when made visible.
   * @param aReadOnly PR_TRUE to enable caret.  PR_FALSE to disable.
   * @return always NS_OK
   */
  /* void setCaretReadOnly (in boolean readOnly); */
  NS_SCRIPTABLE NS_IMETHOD SetCaretReadOnly(PRBool readOnly) = 0;

  /**
   * Gets the current state of the caret.
   * @param aEnabled  [OUT] set to the current caret state, as set by SetCaretEnabled
   * @return   if aOutEnabled==null, returns NS_ERROR_INVALID_ARG
   *           else NS_OK
   */
  /* boolean getCaretEnabled (); */
  NS_SCRIPTABLE NS_IMETHOD GetCaretEnabled(PRBool *_retval NS_OUTPARAM) = 0;

  /**
    * This is true if the caret is enabled, visible, and currently blinking.
    * This is still true when the caret is enabled, visible, but in its "off"
    * blink cycle.
    */
  /* readonly attribute boolean caretVisible; */
  NS_SCRIPTABLE NS_IMETHOD GetCaretVisible(PRBool *aCaretVisible) = 0;

  /**
   * Show the caret even in selections. By default the caret is hidden unless the
   * selection is collapsed. Use this function to show the caret even in selections.
   * @param aVisibility PR_TRUE to show the caret in selections.  PR_FALSE to hide.
   * @return always NS_OK
   */
  /* void setCaretVisibilityDuringSelection (in boolean visibility); */
  NS_SCRIPTABLE NS_IMETHOD SetCaretVisibilityDuringSelection(PRBool visibility) = 0;

  /** CharacterMove will move the selection one character forward/backward in the document.
   *  this will also have the effect of collapsing the selection if the aExtend = PR_FALSE
   *  the "point" of selection that is extended is considered the "focus" point.
   *  or the last point adjusted by the selection.
   *  @param aForward forward or backward if PR_FALSE
   *  @param aExtend  should it collapse the selection of extend it?
   */
  /* void characterMove (in boolean forward, in boolean extend); */
  NS_SCRIPTABLE NS_IMETHOD CharacterMove(PRBool forward, PRBool extend) = 0;

  /**
    * CharacterExtendForDelete will extend the selection one character cell
    * forward in the document.
    * this method is used internally for handling del key.
    */
  /* [noscript] void characterExtendForDelete (); */
  NS_IMETHOD CharacterExtendForDelete(void) = 0;

  /**
    * CharacterExtendForBackspace will extend the selection one character cell
    * backward in the document.
    * this method is used internally for handling backspace key only when we're
    * after UTF-16 surrogates.
    */
  /* [noscript] void characterExtendForBackspace (); */
  NS_IMETHOD CharacterExtendForBackspace(void) = 0;

  /** WordMove will move the selection one word forward/backward in the document.
   *  this will also have the effect of collapsing the selection if the aExtend = PR_FALSE
   *  the "point" of selection that is extended is considered the "focus" point.
   *  or the last point adjusted by the selection.
   *  @param aForward forward or backward if PR_FALSE
   *  @param aExtend  should it collapse the selection of extend it?
   */
  /* void wordMove (in boolean forward, in boolean extend); */
  NS_SCRIPTABLE NS_IMETHOD WordMove(PRBool forward, PRBool extend) = 0;

  /** wordExtendForDelete will extend the selection one word forward/backward in the document.
   *  this method is used internally for handling ctrl[option]-backspace and ctrl[option]-del.
   *  @param aForward forward or backward if PR_FALSE
   */
  /* [noscript] void wordExtendForDelete (in boolean forward); */
  NS_IMETHOD WordExtendForDelete(PRBool forward) = 0;

  /** LineMove will move the selection one line forward/backward in the document.
   *  this will also have the effect of collapsing the selection if the aExtend = PR_FALSE
   *  the "point" of selection that is extended is considered the "focus" point.
   *  or the last point adjusted by the selection.
   *  @param aForward forward or backward if PR_FALSE
   *  @param aExtend  should it collapse the selection of extend it?
   */
  /* void lineMove (in boolean forward, in boolean extend); */
  NS_SCRIPTABLE NS_IMETHOD LineMove(PRBool forward, PRBool extend) = 0;

  /** IntraLineMove will move the selection to the front of the line or end of the line
   *  in the document.
   *  this will also have the effect of collapsing the selection if the aExtend = PR_FALSE
   *  the "point" of selection that is extended is considered the "focus" point.
   *  or the last point adjusted by the selection.
   *  @param aForward forward or backward if PR_FALSE
   *  @param aExtend  should it collapse the selection of extend it?
   */
  /* void intraLineMove (in boolean forward, in boolean extend); */
  NS_SCRIPTABLE NS_IMETHOD IntraLineMove(PRBool forward, PRBool extend) = 0;

  /** PageMove will move the selection one page forward/backward in the document.
   *  this will also have the effect of collapsing the selection if the aExtend = PR_FALSE
   *  the "point" of selection that is extended is considered the "focus" point.
   *  or the last point adjusted by the selection.
   *  @param aForward forward or backward if PR_FALSE
   *  @param aExtend  should it collapse the selection of extend it?
   */
  /* void pageMove (in boolean forward, in boolean extend); */
  NS_SCRIPTABLE NS_IMETHOD PageMove(PRBool forward, PRBool extend) = 0;

  /** CompleteScroll will move page view to the top or bottom of the document
   *  @param aForward forward or backward if PR_FALSE
   */
  /* void completeScroll (in boolean forward); */
  NS_SCRIPTABLE NS_IMETHOD CompleteScroll(PRBool forward) = 0;

  /** CompleteMove will move page view to the top or bottom of the document
   *  this will also have the effect of collapsing the selection if the aExtend = PR_FALSE
   *  the "point" of selection that is extended is considered the "focus" point.
   *  or the last point adjusted by the selection.
   *  @param aForward forward or backward if PR_FALSE
   *  @param aExtend  should it collapse the selection of extend it?
   */
  /* void completeMove (in boolean forward, in boolean extend); */
  NS_SCRIPTABLE NS_IMETHOD CompleteMove(PRBool forward, PRBool extend) = 0;

  /** ScrollPage will scroll the page without affecting the selection.
   *  @param aForward scroll forward or backwards in selection
   */
  /* void scrollPage (in boolean forward); */
  NS_SCRIPTABLE NS_IMETHOD ScrollPage(PRBool forward) = 0;

  /** ScrolLine will scroll line up or down dependent on the boolean
   *  @param aForward scroll forward or backwards in selection
   */
  /* void scrollLine (in boolean forward); */
  NS_SCRIPTABLE NS_IMETHOD ScrollLine(PRBool forward) = 0;

  /** ScrolHorizontal will scroll left or right dependent on the boolean
   *  @param aLeft if true will scroll left. if not will scroll right.
   */
  /* void scrollHorizontal (in boolean left); */
  NS_SCRIPTABLE NS_IMETHOD ScrollHorizontal(PRBool left) = 0;

  /** SelectAll will select the whole page
   */
  /* void selectAll (); */
  NS_SCRIPTABLE NS_IMETHOD SelectAll(void) = 0;

  /** CheckVisibility will return true if textnode and offsets are actually rendered
   *  in the current precontext.
   *  @param aNode textNode to test
   *  @param aStartOffset  offset in dom to first char of textnode to test
   *  @param aEndOffset    offset in dom to last char of textnode to test
   *  @param aReturnBool   boolean returned TRUE if visible FALSE if not
   */
  /* boolean checkVisibility (in nsIDOMNode node, in short startOffset, in short endOffset); */
  NS_SCRIPTABLE NS_IMETHOD CheckVisibility(nsIDOMNode *node, PRInt16 startOffset, PRInt16 endOffset, PRBool *_retval NS_OUTPARAM) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsISelectionController, NS_ISELECTIONCONTROLLER_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISELECTIONCONTROLLER \
  NS_SCRIPTABLE NS_IMETHOD SetDisplaySelection(PRInt16 toggle); \
  NS_SCRIPTABLE NS_IMETHOD GetDisplaySelection(PRInt16 *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD GetSelection(PRInt16 type, nsISelection **_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD ScrollSelectionIntoView(PRInt16 type, PRInt16 region, PRInt16 flags); \
  NS_SCRIPTABLE NS_IMETHOD RepaintSelection(PRInt16 type); \
  NS_SCRIPTABLE NS_IMETHOD SetCaretEnabled(PRBool enabled); \
  NS_SCRIPTABLE NS_IMETHOD SetCaretReadOnly(PRBool readOnly); \
  NS_SCRIPTABLE NS_IMETHOD GetCaretEnabled(PRBool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD GetCaretVisible(PRBool *aCaretVisible); \
  NS_SCRIPTABLE NS_IMETHOD SetCaretVisibilityDuringSelection(PRBool visibility); \
  NS_SCRIPTABLE NS_IMETHOD CharacterMove(PRBool forward, PRBool extend); \
  NS_IMETHOD CharacterExtendForDelete(void); \
  NS_IMETHOD CharacterExtendForBackspace(void); \
  NS_SCRIPTABLE NS_IMETHOD WordMove(PRBool forward, PRBool extend); \
  NS_IMETHOD WordExtendForDelete(PRBool forward); \
  NS_SCRIPTABLE NS_IMETHOD LineMove(PRBool forward, PRBool extend); \
  NS_SCRIPTABLE NS_IMETHOD IntraLineMove(PRBool forward, PRBool extend); \
  NS_SCRIPTABLE NS_IMETHOD PageMove(PRBool forward, PRBool extend); \
  NS_SCRIPTABLE NS_IMETHOD CompleteScroll(PRBool forward); \
  NS_SCRIPTABLE NS_IMETHOD CompleteMove(PRBool forward, PRBool extend); \
  NS_SCRIPTABLE NS_IMETHOD ScrollPage(PRBool forward); \
  NS_SCRIPTABLE NS_IMETHOD ScrollLine(PRBool forward); \
  NS_SCRIPTABLE NS_IMETHOD ScrollHorizontal(PRBool left); \
  NS_SCRIPTABLE NS_IMETHOD SelectAll(void); \
  NS_SCRIPTABLE NS_IMETHOD CheckVisibility(nsIDOMNode *node, PRInt16 startOffset, PRInt16 endOffset, PRBool *_retval NS_OUTPARAM);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISELECTIONCONTROLLER(_to) \
  NS_SCRIPTABLE NS_IMETHOD SetDisplaySelection(PRInt16 toggle) { return _to SetDisplaySelection(toggle); } \
  NS_SCRIPTABLE NS_IMETHOD GetDisplaySelection(PRInt16 *_retval NS_OUTPARAM) { return _to GetDisplaySelection(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetSelection(PRInt16 type, nsISelection **_retval NS_OUTPARAM) { return _to GetSelection(type, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD ScrollSelectionIntoView(PRInt16 type, PRInt16 region, PRInt16 flags) { return _to ScrollSelectionIntoView(type, region, flags); } \
  NS_SCRIPTABLE NS_IMETHOD RepaintSelection(PRInt16 type) { return _to RepaintSelection(type); } \
  NS_SCRIPTABLE NS_IMETHOD SetCaretEnabled(PRBool enabled) { return _to SetCaretEnabled(enabled); } \
  NS_SCRIPTABLE NS_IMETHOD SetCaretReadOnly(PRBool readOnly) { return _to SetCaretReadOnly(readOnly); } \
  NS_SCRIPTABLE NS_IMETHOD GetCaretEnabled(PRBool *_retval NS_OUTPARAM) { return _to GetCaretEnabled(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetCaretVisible(PRBool *aCaretVisible) { return _to GetCaretVisible(aCaretVisible); } \
  NS_SCRIPTABLE NS_IMETHOD SetCaretVisibilityDuringSelection(PRBool visibility) { return _to SetCaretVisibilityDuringSelection(visibility); } \
  NS_SCRIPTABLE NS_IMETHOD CharacterMove(PRBool forward, PRBool extend) { return _to CharacterMove(forward, extend); } \
  NS_IMETHOD CharacterExtendForDelete(void) { return _to CharacterExtendForDelete(); } \
  NS_IMETHOD CharacterExtendForBackspace(void) { return _to CharacterExtendForBackspace(); } \
  NS_SCRIPTABLE NS_IMETHOD WordMove(PRBool forward, PRBool extend) { return _to WordMove(forward, extend); } \
  NS_IMETHOD WordExtendForDelete(PRBool forward) { return _to WordExtendForDelete(forward); } \
  NS_SCRIPTABLE NS_IMETHOD LineMove(PRBool forward, PRBool extend) { return _to LineMove(forward, extend); } \
  NS_SCRIPTABLE NS_IMETHOD IntraLineMove(PRBool forward, PRBool extend) { return _to IntraLineMove(forward, extend); } \
  NS_SCRIPTABLE NS_IMETHOD PageMove(PRBool forward, PRBool extend) { return _to PageMove(forward, extend); } \
  NS_SCRIPTABLE NS_IMETHOD CompleteScroll(PRBool forward) { return _to CompleteScroll(forward); } \
  NS_SCRIPTABLE NS_IMETHOD CompleteMove(PRBool forward, PRBool extend) { return _to CompleteMove(forward, extend); } \
  NS_SCRIPTABLE NS_IMETHOD ScrollPage(PRBool forward) { return _to ScrollPage(forward); } \
  NS_SCRIPTABLE NS_IMETHOD ScrollLine(PRBool forward) { return _to ScrollLine(forward); } \
  NS_SCRIPTABLE NS_IMETHOD ScrollHorizontal(PRBool left) { return _to ScrollHorizontal(left); } \
  NS_SCRIPTABLE NS_IMETHOD SelectAll(void) { return _to SelectAll(); } \
  NS_SCRIPTABLE NS_IMETHOD CheckVisibility(nsIDOMNode *node, PRInt16 startOffset, PRInt16 endOffset, PRBool *_retval NS_OUTPARAM) { return _to CheckVisibility(node, startOffset, endOffset, _retval); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISELECTIONCONTROLLER(_to) \
  NS_SCRIPTABLE NS_IMETHOD SetDisplaySelection(PRInt16 toggle) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetDisplaySelection(toggle); } \
  NS_SCRIPTABLE NS_IMETHOD GetDisplaySelection(PRInt16 *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDisplaySelection(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetSelection(PRInt16 type, nsISelection **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSelection(type, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD ScrollSelectionIntoView(PRInt16 type, PRInt16 region, PRInt16 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->ScrollSelectionIntoView(type, region, flags); } \
  NS_SCRIPTABLE NS_IMETHOD RepaintSelection(PRInt16 type) { return !_to ? NS_ERROR_NULL_POINTER : _to->RepaintSelection(type); } \
  NS_SCRIPTABLE NS_IMETHOD SetCaretEnabled(PRBool enabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCaretEnabled(enabled); } \
  NS_SCRIPTABLE NS_IMETHOD SetCaretReadOnly(PRBool readOnly) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCaretReadOnly(readOnly); } \
  NS_SCRIPTABLE NS_IMETHOD GetCaretEnabled(PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCaretEnabled(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetCaretVisible(PRBool *aCaretVisible) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCaretVisible(aCaretVisible); } \
  NS_SCRIPTABLE NS_IMETHOD SetCaretVisibilityDuringSelection(PRBool visibility) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCaretVisibilityDuringSelection(visibility); } \
  NS_SCRIPTABLE NS_IMETHOD CharacterMove(PRBool forward, PRBool extend) { return !_to ? NS_ERROR_NULL_POINTER : _to->CharacterMove(forward, extend); } \
  NS_IMETHOD CharacterExtendForDelete(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->CharacterExtendForDelete(); } \
  NS_IMETHOD CharacterExtendForBackspace(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->CharacterExtendForBackspace(); } \
  NS_SCRIPTABLE NS_IMETHOD WordMove(PRBool forward, PRBool extend) { return !_to ? NS_ERROR_NULL_POINTER : _to->WordMove(forward, extend); } \
  NS_IMETHOD WordExtendForDelete(PRBool forward) { return !_to ? NS_ERROR_NULL_POINTER : _to->WordExtendForDelete(forward); } \
  NS_SCRIPTABLE NS_IMETHOD LineMove(PRBool forward, PRBool extend) { return !_to ? NS_ERROR_NULL_POINTER : _to->LineMove(forward, extend); } \
  NS_SCRIPTABLE NS_IMETHOD IntraLineMove(PRBool forward, PRBool extend) { return !_to ? NS_ERROR_NULL_POINTER : _to->IntraLineMove(forward, extend); } \
  NS_SCRIPTABLE NS_IMETHOD PageMove(PRBool forward, PRBool extend) { return !_to ? NS_ERROR_NULL_POINTER : _to->PageMove(forward, extend); } \
  NS_SCRIPTABLE NS_IMETHOD CompleteScroll(PRBool forward) { return !_to ? NS_ERROR_NULL_POINTER : _to->CompleteScroll(forward); } \
  NS_SCRIPTABLE NS_IMETHOD CompleteMove(PRBool forward, PRBool extend) { return !_to ? NS_ERROR_NULL_POINTER : _to->CompleteMove(forward, extend); } \
  NS_SCRIPTABLE NS_IMETHOD ScrollPage(PRBool forward) { return !_to ? NS_ERROR_NULL_POINTER : _to->ScrollPage(forward); } \
  NS_SCRIPTABLE NS_IMETHOD ScrollLine(PRBool forward) { return !_to ? NS_ERROR_NULL_POINTER : _to->ScrollLine(forward); } \
  NS_SCRIPTABLE NS_IMETHOD ScrollHorizontal(PRBool left) { return !_to ? NS_ERROR_NULL_POINTER : _to->ScrollHorizontal(left); } \
  NS_SCRIPTABLE NS_IMETHOD SelectAll(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->SelectAll(); } \
  NS_SCRIPTABLE NS_IMETHOD CheckVisibility(nsIDOMNode *node, PRInt16 startOffset, PRInt16 endOffset, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckVisibility(node, startOffset, endOffset, _retval); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsSelectionController : public nsISelectionController
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSISELECTIONCONTROLLER

  nsSelectionController();

private:
  ~nsSelectionController();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsSelectionController, nsISelectionController)

nsSelectionController::nsSelectionController()
{
  /* member initializers and constructor code */
}

nsSelectionController::~nsSelectionController()
{
  /* destructor code */
}

/* void setDisplaySelection (in short toggle); */
NS_IMETHODIMP nsSelectionController::SetDisplaySelection(PRInt16 toggle)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* short getDisplaySelection (); */
NS_IMETHODIMP nsSelectionController::GetDisplaySelection(PRInt16 *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsISelection getSelection (in short type); */
NS_IMETHODIMP nsSelectionController::GetSelection(PRInt16 type, nsISelection **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void scrollSelectionIntoView (in short type, in short region, in short flags); */
NS_IMETHODIMP nsSelectionController::ScrollSelectionIntoView(PRInt16 type, PRInt16 region, PRInt16 flags)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void repaintSelection (in short type); */
NS_IMETHODIMP nsSelectionController::RepaintSelection(PRInt16 type)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void setCaretEnabled (in boolean enabled); */
NS_IMETHODIMP nsSelectionController::SetCaretEnabled(PRBool enabled)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void setCaretReadOnly (in boolean readOnly); */
NS_IMETHODIMP nsSelectionController::SetCaretReadOnly(PRBool readOnly)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean getCaretEnabled (); */
NS_IMETHODIMP nsSelectionController::GetCaretEnabled(PRBool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* readonly attribute boolean caretVisible; */
NS_IMETHODIMP nsSelectionController::GetCaretVisible(PRBool *aCaretVisible)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void setCaretVisibilityDuringSelection (in boolean visibility); */
NS_IMETHODIMP nsSelectionController::SetCaretVisibilityDuringSelection(PRBool visibility)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void characterMove (in boolean forward, in boolean extend); */
NS_IMETHODIMP nsSelectionController::CharacterMove(PRBool forward, PRBool extend)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [noscript] void characterExtendForDelete (); */
NS_IMETHODIMP nsSelectionController::CharacterExtendForDelete()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [noscript] void characterExtendForBackspace (); */
NS_IMETHODIMP nsSelectionController::CharacterExtendForBackspace()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void wordMove (in boolean forward, in boolean extend); */
NS_IMETHODIMP nsSelectionController::WordMove(PRBool forward, PRBool extend)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [noscript] void wordExtendForDelete (in boolean forward); */
NS_IMETHODIMP nsSelectionController::WordExtendForDelete(PRBool forward)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void lineMove (in boolean forward, in boolean extend); */
NS_IMETHODIMP nsSelectionController::LineMove(PRBool forward, PRBool extend)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void intraLineMove (in boolean forward, in boolean extend); */
NS_IMETHODIMP nsSelectionController::IntraLineMove(PRBool forward, PRBool extend)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void pageMove (in boolean forward, in boolean extend); */
NS_IMETHODIMP nsSelectionController::PageMove(PRBool forward, PRBool extend)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void completeScroll (in boolean forward); */
NS_IMETHODIMP nsSelectionController::CompleteScroll(PRBool forward)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void completeMove (in boolean forward, in boolean extend); */
NS_IMETHODIMP nsSelectionController::CompleteMove(PRBool forward, PRBool extend)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void scrollPage (in boolean forward); */
NS_IMETHODIMP nsSelectionController::ScrollPage(PRBool forward)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void scrollLine (in boolean forward); */
NS_IMETHODIMP nsSelectionController::ScrollLine(PRBool forward)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void scrollHorizontal (in boolean left); */
NS_IMETHODIMP nsSelectionController::ScrollHorizontal(PRBool left)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void selectAll (); */
NS_IMETHODIMP nsSelectionController::SelectAll()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean checkVisibility (in nsIDOMNode node, in short startOffset, in short endOffset); */
NS_IMETHODIMP nsSelectionController::CheckVisibility(nsIDOMNode *node, PRInt16 startOffset, PRInt16 endOffset, PRBool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

   #define NS_ISELECTIONCONTROLLER_CID \
   { 0x513b9460, 0xd56a, 0x4c4e, \
   { 0xb6, 0xf9, 0x0b, 0x8a, 0xe4, 0x37, 0x2a, 0x3b }}

#endif /* __gen_nsISelectionController_h__ */


text:
package org.apache.jena.tdb.base.objectfile;

import java.nio.ByteBuffer ;
import java.util.Iterator ;

import org.apache.jena.atlas.lib.Pair ;
import org.apache.jena.tdb.base.block.Block ;
import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;

public class ObjectFileLogger implements ObjectFile
{
    protected final ObjectFile other ;
    private static Logger defaultLogger = LoggerFactory.getLogger(ObjectFile.class) ;
    private final Logger log ;
    private final String label  ;

    public ObjectFileLogger(String label, ObjectFile other)
    {
        this.other = other ;
        this.label = label ;
        log = defaultLogger ;
    }

    @Override
    public Block allocWrite(int maxBytes)
    {
        Block blk = other.allocWrite(maxBytes) ;
        info("allocWrite("+maxBytes+") -> "+blk.getId()) ;
        return blk ;
    }

    @Override
    public void completeWrite(Block buffer)
    {
        info("completeWrite("+buffer.getId()+")") ;
        other.completeWrite(buffer) ;
    }

    @Override
    public void abortWrite(Block buffer)
    {
        info("abortWrite("+buffer.getId()+")") ;
        other.abortWrite(buffer) ;
    }

    @Override
    public long write(ByteBuffer buffer)
    {
        info("write"+buffer) ;
        return other.write(buffer) ;
    }

    @Override
    public void reposition(long id)
    {
        info("reposition("+id+")") ;
        other.reposition(id) ;
    }

    @Override
    public ByteBuffer read(long id)
    {
        info("read("+id+")") ;
        return other.read(id) ;
    }

    @Override
    public Iterator<Pair<Long, ByteBuffer>> all()
    {
        info("all()") ;
        return other.all() ;
    }

    @Override
    public void truncate(long size)
    {
        info("truncate("+size+")") ;
        other.truncate(size) ;
    }

    @Override
    public void sync()
    {
        info("sync") ;
        other.sync() ;
    }

    @Override
    public void close()
    {
        info("close") ;
        other.close() ;
    }

    @Override
    public String getLabel()
    {
        return other.getLabel() ;
    }

    @Override
    public long length()
    {
        return other.length() ;
    }

    @Override
    public boolean isEmpty()
    {
        return other.isEmpty() ;
    }

    private void info(String string)
    {
        if ( label != null )
            string = label+": "+string ;
        log.info(string) ;
    }
}


text:
import _jsx from "@babel/runtime/helpers/builtin/jsx";
import React from 'react';
import PropTypes from 'prop-types';
import Button from "@material-ui/core/es/Button";

var SocialMediaLink = function SocialMediaLink(_ref) {
  var href = _ref.href,
      label = _ref.label,
      children = _ref.children;
  return _jsx("li", {
    className: "wlk-AboutPage-socialMedia"
  }, void 0, _jsx(Button, {
    target: "_blank",
    href: href
  }, void 0, _jsx("span", {
    className: "wlk-AboutPage-socialMediaIcon"
  }, void 0, children), label));
};

SocialMediaLink.propTypes = process.env.NODE_ENV !== "production" ? {
  href: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  children: PropTypes.element.isRequired
} : {};
export default SocialMediaLink;
//# sourceMappingURL=SocialMediaLink.js.map


text:
package com.google.gerrit.gpg;

import static com.google.gerrit.gpg.PublicKeyStore.keyToString;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyA;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyB;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyC;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyD;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyE;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyF;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyG;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyH;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyI;
import static com.google.gerrit.gpg.testutil.TestTrustKeys.keyJ;
import static org.junit.Assert.assertEquals;

import com.google.gerrit.gpg.testutil.TestKey;
import com.google.gerrit.gpg.testutil.TestKeys;

import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription;
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.RefUpdate;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PublicKeyCheckerTest {
  @Rule
  public ExpectedException thrown = ExpectedException.none();

  private InMemoryRepository repo;
  private PublicKeyStore store;

  @Before
  public void setUp() {
    repo = new InMemoryRepository(new DfsRepositoryDescription("repo"));
    store = new PublicKeyStore(repo);
  }

  @After
  public void tearDown() {
    if (store != null) {
      store.close();
      store = null;
    }
    if (repo != null) {
      repo.close();
      repo = null;
    }
  }

  @Test
  public void validKey() throws Exception {
    assertProblems(TestKeys.key1());
  }

  @Test
  public void keyExpiringInFuture() throws Exception {
    assertProblems(TestKeys.key2());
  }

  @Test
  public void expiredKey() throws Exception {
    assertProblems(TestKeys.key3(), "Key is expired");
  }

  @Test
  public void selfRevokedKey() throws Exception {
    assertProblems(TestKeys.key4(), "Key is revoked");
  }

  // Test keys specific to this test are at the bottom of this class. Each test
  // has a diagram of the trust network, where:
  //  - The notation M---N indicates N trusts M.
  //  - An 'x' indicates the key is expired.

  @Test
  public void trustValidPathLength2() throws Exception {
    // A---Bx
    //  \
    //   \---C---D
    //        \
    //         \---Ex
    //
    // D and E trust C to be a valid introducer of depth 2.
    TestKey ka = add(keyA());
    TestKey kb = add(keyB());
    TestKey kc = add(keyC());
    TestKey kd = add(keyD());
    TestKey ke = add(keyE());
    save();

    PublicKeyChecker checker = newChecker(2, kb, kd);
    assertProblems(checker, ka);
    assertProblems(checker, kb, "Key is expired");
    assertProblems(checker, kc);
    assertProblems(checker, kd);
    assertProblems(checker, ke, "Key is expired", "No path to a trusted key");
  }

  @Test
  public void trustValidPathLength1() throws Exception {
    // A---Bx
    //  \
    //   \---C---D
    //        \
    //         \---Ex
    //
    // D and E trust C to be a valid introducer of depth 2.
    TestKey ka = add(keyA());
    TestKey kb = add(keyB());
    TestKey kc = add(keyC());
    TestKey kd = add(keyD());
    add(keyE());
    save();

    PublicKeyChecker checker = newChecker(1, kd);
    assertProblems(checker, ka,
        "No path to a trusted key", notTrusted(kb), notTrusted(kc));
  }

  @Test
  public void trustCycle() throws Exception {
    // F---G---F, in a cycle.
    TestKey kf = add(keyF());
    TestKey kg = add(keyG());
    save();

    PublicKeyChecker checker = newChecker(10, keyA());
    assertProblems(checker, kf,
        "No path to a trusted key", notTrusted(kg));
    assertProblems(checker, kg,
        "No path to a trusted key", notTrusted(kf));
  }

  @Test
  public void trustInsufficientDepthInSignature() throws Exception {
    // H---I---J, but J is only trusted to length 1.
    TestKey kh = add(keyH());
    TestKey ki = add(keyI());
    add(keyJ());
    save();

    PublicKeyChecker checker = newChecker(10, keyJ());

    // J trusts I to a depth of 1, so I itself is valid, but I's certification
    // of K is not valid.
    assertProblems(checker, ki);
    assertProblems(checker, kh,
        "No path to a trusted key", notTrusted(ki));
  }

  private PublicKeyChecker newChecker(int maxTrustDepth, TestKey... trusted) {
    List<Fingerprint> fps = new ArrayList<>(trusted.length);
    for (TestKey k : trusted) {
      fps.add(new Fingerprint(k.getPublicKey().getFingerprint()));
    }
    return new PublicKeyChecker(maxTrustDepth, fps);
  }

  private TestKey add(TestKey k) {
    store.add(k.getPublicKeyRing());
    return k;
  }

  private void save() throws Exception {
    PersonIdent ident = new PersonIdent("A U Thor", "author@example.com");
    CommitBuilder cb = new CommitBuilder();
    cb.setAuthor(ident);
    cb.setCommitter(ident);
    RefUpdate.Result result = store.save(cb);
    switch (result) {
      case NEW:
      case FAST_FORWARD:
      case FORCED:
        break;
      default:
        throw new AssertionError(result);
    }
  }

  private void assertProblems(PublicKeyChecker checker, TestKey k,
      String... expected) {
    CheckResult result = checker.check(k.getPublicKey(), store);
    assertEquals(Arrays.asList(expected), result.getProblems());
  }

  private void assertProblems(TestKey tk, String... expected) throws Exception {
    CheckResult result = new PublicKeyChecker().check(tk.getPublicKey(), store);
    assertEquals(Arrays.asList(expected), result.getProblems());
  }

  private static String notTrusted(TestKey k) {
    return "Certification by " + keyToString(k.getPublicKey())
        + " is valid, but key is not trusted";
  }
}


text:
Invocation
==========

The scripts can generally just be run. Options can be set on the
command line or by exporting variables to override those present in
lib/img-defaults. -h to get help.

The image building scripts expect to be able to invoke commands with
sudo, so if you want them to run non-interactively, you should either
run them as root, with sudo -E, or allow your build user to run any
sudo command without password.

Using the variable ``ELEMENTS_PATH`` will allow to specify multiple
elements locations.  It is a colon (:) separated path list, and it
will work in a first path/element found, first served approach. The
included elements tree is used when no path is supplied, and is added
to the end of the path if a path is supplied.

By default, the image building scripts will not overwrite existing
disk images, allowing you to compare the newly built image with the
existing one. To change that behaviour, set the variable
``OVERWRITE_OLD_IMAGE`` to any value that isn't ``0``. If this value is
zero then any existing image will be moved before the new image is
written to the destination.

Setting the variable ``DIB_SHOW_IMAGE_USAGE`` will print out a
summarised disk-usage report for the final image of files and
directories over 10MiB in size.  Setting ``DIB_SHOW_IMAGE_USAGE_FULL``
will show all files and directories.  These settings can be useful
additions to the logs in automated build situations where debugging
image-growth may be important.


text:
class EducationHistory < ActiveRecord::Base
  delegate :user, :to=> :user, :allow_nil=>false
  belongs_to :resume
  validates :school_name, :from, :until, :education, presence: true
  resourcify
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.baremetalsolution.v2.model;

/**
 * A GCP vlan attachment.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Bare Metal Solution API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class IntakeVlanAttachment extends com.google.api.client.json.GenericJson {

  /**
   * Identifier of the VLAN attachment.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String id;

  /**
   * Attachment pairing key.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String pairingKey;

  /**
   * Identifier of the VLAN attachment.
   * @return value or {@code null} for none
   */
  public java.lang.String getId() {
    return id;
  }

  /**
   * Identifier of the VLAN attachment.
   * @param id id or {@code null} for none
   */
  public IntakeVlanAttachment setId(java.lang.String id) {
    this.id = id;
    return this;
  }

  /**
   * Attachment pairing key.
   * @return value or {@code null} for none
   */
  public java.lang.String getPairingKey() {
    return pairingKey;
  }

  /**
   * Attachment pairing key.
   * @param pairingKey pairingKey or {@code null} for none
   */
  public IntakeVlanAttachment setPairingKey(java.lang.String pairingKey) {
    this.pairingKey = pairingKey;
    return this;
  }

  @Override
  public IntakeVlanAttachment set(String fieldName, Object value) {
    return (IntakeVlanAttachment) super.set(fieldName, value);
  }

  @Override
  public IntakeVlanAttachment clone() {
    return (IntakeVlanAttachment) super.clone();
  }

}


text:
<?php

namespace Lesson15;

class NumberSolitaire
{
}


text:
using Pliant.Captures;
using Pliant.Diagnostics;
using Pliant.Utilities;

namespace Pliant.Languages.Pdl
{
    public class PdlQualifiedIdentifier : PdlNode
    {
        private readonly int _hashCode;

        public ICapture<char> Identifier { get; private set; }

        public PdlQualifiedIdentifier(string identifier)
            : this(identifier.AsCapture())
        {
        }

        public PdlQualifiedIdentifier(ICapture<char> identifier)
        {
            Assert.IsNotNull(identifier, nameof(identifier));
            Identifier = identifier;
            _hashCode = ComputeHashCode();
        }

        public override PdlNodeType NodeType => PdlNodeType.PdlQualifiedIdentifier;

        public override bool Equals(object obj)
        {
            if (obj is null)
                return false;
            if (!(obj is PdlQualifiedIdentifier qualifiedIdentifier))
                return false;
            return qualifiedIdentifier.NodeType == NodeType
                && qualifiedIdentifier.Identifier.Equals(Identifier);
        }

        int ComputeHashCode()
        {
            return HashCode.Compute(((int)NodeType).GetHashCode(), Identifier.GetHashCode());
        }

        public override int GetHashCode() => _hashCode;

        public override string ToString() => Identifier.ToString();
    }

    public class PdlQualifiedIdentifierConcatenation : PdlQualifiedIdentifier
    {
        private readonly int _hashCode;

        public PdlQualifiedIdentifier QualifiedIdentifier { get; private set; }

        public PdlQualifiedIdentifierConcatenation(
            string identifier,
            PdlQualifiedIdentifier qualifiedIdentifier)
            : this(identifier.AsCapture(),
                  qualifiedIdentifier)
        { }

        public PdlQualifiedIdentifierConcatenation(
            ICapture<char> identifier,
            PdlQualifiedIdentifier qualifiedIdentifier)
            : base(identifier)
        {
            QualifiedIdentifier = qualifiedIdentifier;
            _hashCode = ComputeHashCode();
        }

        public override PdlNodeType NodeType => PdlNodeType.PdlQualifiedIdentifierConcatenation;

        public override bool Equals(object obj)
        {
            if (obj is null)
                return false;
            if (!(obj is PdlQualifiedIdentifierConcatenation qualifiedIdentifier))
                return false;
            return qualifiedIdentifier.NodeType == NodeType
                && qualifiedIdentifier.Identifier.Equals(Identifier)
                && qualifiedIdentifier.QualifiedIdentifier.Equals(QualifiedIdentifier);
        }

        int ComputeHashCode()
        {
            return HashCode.Compute(
                ((int)NodeType).GetHashCode(),
                Identifier.GetHashCode(),
                QualifiedIdentifier.GetHashCode());
        }

        public override int GetHashCode() => _hashCode;

        public override string ToString() => $"{QualifiedIdentifier}.{Identifier}";
    }
}


text:
package com.imojiapp.imoji.sdk.ui.utils;

import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;

/**
 * Created by sajjadtabib on 10/1/15.
 */
public class DisplayUtils {

    public static float getAspectRatio(Point point) {
        return point.x / point.y;
    }

    public static float getWindowAspectRatio(Context context) {
        Point p = getWindowSize(context);
        return getAspectRatio(p);
    }

    public static Point getWindowSize(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point windowDisplaySize = new Point();
        display.getSize(windowDisplaySize);
        return windowDisplaySize;
    }

}


text:
using System;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Authentication;
using Finbuckle.MultiTenant.AspNetCore;
using Finbuckle.MultiTenant.Strategies;
using Finbuckle.MultiTenant;
using Microsoft.AspNetCore.Routing;
using System.Linq;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using System.Security.Claims;
using Finbuckle.MultiTenant.Internal;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// Provides builder methods for Finbuckle.MultiTenant services and configuration.
    /// </summary>
    public static class FinbuckleMultiTenantBuilderExtensions
    {
        /// <summary>
        /// Configures authentication options to enable per-tenant behavior.
        /// </summary>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithPerTenantAuthentication<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder)
            where TTenantInfo : class, ITenantInfo, new()
        {
            builder.Services.ConfigureAll<CookieAuthenticationOptions>(options =>
            {
                // Validate that claimed tenant matches current tenant.
                var origOnValidatePrincipal = options.Events.OnValidatePrincipal;
                options.Events.OnValidatePrincipal = async context =>
                {
                    await origOnValidatePrincipal(context);

                    if(context.Principal == null)
                        return;

                    var currentTenant = context.HttpContext.GetMultiTenantContext<TTenantInfo>()?.TenantInfo?.Identifier;

                    // If no current tenant and no tenant claim then OK
                    if(currentTenant == null && !context.Principal.Claims.Any(c => c.Type == Constants.TenantToken))
                        return;

                    // Does a tenant claim for the principle match the current tenant?
                    if(!context.Principal.Claims.Where(c => c.Type == Constants.TenantToken && String.Equals(c.Value, currentTenant, StringComparison.OrdinalIgnoreCase)).Any())
                        context.RejectPrincipal();
                };

                // Set the tenant claim when signing in.
                var origOnSigningIn = options.Events.OnSigningIn;
                options.Events.OnSigningIn = async context =>
                {
                    await origOnSigningIn(context);

                    if(context.Principal == null)
                        return;

                    var identity = (ClaimsIdentity)context.Principal.Identity;
                    var currentTenant = context.HttpContext.GetMultiTenantContext<TTenantInfo>()?.TenantInfo?.Identifier;

                    if(currentTenant != null)
                        identity.AddClaim(new Claim(Constants.TenantToken, currentTenant));
                };
            });

            // Set per-tenant cookie options by convention.
            builder.WithPerTenantOptions<CookieAuthenticationOptions>((options, tc) =>
            {
                var d = (dynamic)tc;
                try { options.LoginPath = ((string)d.CookieLoginPath).Replace(Constants.TenantToken, tc.Identifier); } catch { }
                try { options.LogoutPath = ((string)d.CookieLogoutPath).Replace(Constants.TenantToken, tc.Identifier); } catch { }
                try { options.AccessDeniedPath = ((string)d.CookieAccessDeniedPath).Replace(Constants.TenantToken, tc.Identifier); } catch { }
            });

            builder.WithRemoteAuthenticationCallbackStrategy();

            // We need to "decorate" IAuthenticationService so callbacks so that
            // remote authentication can get the tenant from the authentication
            // properties in the state parameter.
            if (!builder.Services.Where(s => s.ServiceType == typeof(IAuthenticationService)).Any())
                throw new MultiTenantException("WithRemoteAuthenticationCallbackStrategy() must be called after AddAutheorization() in ConfigureServices.");
            builder.Services.DecorateService<IAuthenticationService, MultiTenantAuthenticationService<TTenantInfo>>();

            // Set per-tenant OpenIdConnect options by convention.
            builder.WithPerTenantOptions<OpenIdConnectOptions>((options, tc) =>
            {
                var d = (dynamic)tc;
                try { options.Authority = d.OpenIdConnectAuthority; } catch { }
                try { options.ClientId = d.OpenIdConnectClientId; } catch { }
                try { options.ClientSecret = d.OpenIdConnectClientSecret; } catch { }
            });

            // Replace IAuthenticationSchemeProvider so that the options aren't
            // cached and can be used per-tenant.
            builder.Services.Replace(ServiceDescriptor.Singleton<IAuthenticationSchemeProvider, MultiTenantAuthenticationSchemeProvider>());
            var challengeSchemeProp = typeof(TTenantInfo).GetProperty("ChallengeScheme");
            if (challengeSchemeProp != null && challengeSchemeProp.PropertyType == typeof(string))
            {
                builder.WithPerTenantOptions<AuthenticationOptions>((options, tc)
                    => options.DefaultChallengeScheme = (string)challengeSchemeProp.GetValue(tc) ?? options.DefaultChallengeScheme);
            }

            return builder;
        }

        /// <summary>
        /// Adds and configures a SessionStrategy to the application.
        /// </summary>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithSessionStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder)
            where TTenantInfo : class, ITenantInfo, new()
            => builder.WithStrategy<SessionStrategy>(ServiceLifetime.Singleton, Constants.TenantToken);

        /// <summary>
        /// Adds and configures a SessionStrategy to the application.
        /// </summary>
        /// <param name="tenantLey">The session key to use.</param>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithSessionStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder, string tenantKey)
            where TTenantInfo : class, ITenantInfo, new()
            => builder.WithStrategy<SessionStrategy>(ServiceLifetime.Singleton, tenantKey);

        /// <summary>
        /// Adds and configures a RemoteAuthenticationCallbackStrategy to the application.
        /// </summary>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        private static FinbuckleMultiTenantBuilder<TTenantInfo> WithRemoteAuthenticationCallbackStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder)
            where TTenantInfo : class, ITenantInfo, new()
        {
            return builder.WithStrategy<RemoteAuthenticationCallbackStrategy>(ServiceLifetime.Singleton);
        }

        /// <summary>
        /// Adds and configures a BasePathStrategy to the application.
        /// </summary>
        /// <returns>The same MultiTenantBuilder passed into the method.></returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithBasePathStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder)
            where TTenantInfo : class, ITenantInfo, new()
            => builder.WithStrategy<BasePathStrategy>(ServiceLifetime.Singleton);

#if NETCOREAPP2_1
        /// <summary>
        /// Adds and configures a RouteStrategy with a route parameter Constants.TenantToken to the application.
        /// </summary>
        /// <param name="configRoutes">Delegate to configure the routes.</param>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithRouteStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder,
                                                                    Action<IRouteBuilder> configRoutes)
                where TTenantInfo : class, ITenantInfo, new()
            => builder.WithRouteStrategy(Constants.TenantToken, configRoutes);

        /// <summary>
        /// Adds and configures a RouteStrategy to the application.
        /// </summary>
        /// <param name="tenantParam">The name of the route parameter used to determine the tenant identifier.</param>
        /// <param name="configRoutes">Delegate to configure the routes.</param>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithRouteStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder,
                                                                    string tenantParam,
                                                                    Action<IRouteBuilder> configRoutes)
            where TTenantInfo : class, ITenantInfo, new()
        {
            if (string.IsNullOrWhiteSpace(tenantParam))
            {
                throw new ArgumentException("Invalud value for \"tenantParam\"", nameof(tenantParam));
            }

            if (configRoutes == null)
            {
                throw new ArgumentNullException(nameof(configRoutes));
            }

            return builder.WithStrategy<RouteStrategy>(ServiceLifetime.Singleton, new object[] { tenantParam, configRoutes });
        }
#else
        /// <summary>
        /// Adds and configures a RouteStrategy with a route parameter Constants.TenantToken to the application.
        /// </summary>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithRouteStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder)
            where TTenantInfo : class, ITenantInfo, new()
            => builder.WithRouteStrategy(Constants.TenantToken);

        /// <summary>
        /// Adds and configures a RouteStrategy to the application.
        /// </summary>
        /// <param name="tenantParam">The name of the route parameter used to determine the tenant identifier.</param>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithRouteStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder, string tenantParam)
            where TTenantInfo : class, ITenantInfo, new()
        {
            if (string.IsNullOrWhiteSpace(tenantParam))
            {
                throw new ArgumentException("Invalud value for \"tenantParam\"", nameof(tenantParam));
            }

            return builder.WithStrategy<RouteStrategy>(ServiceLifetime.Singleton, new object[] { tenantParam });
        }
#endif

        /// <summary>
        /// Adds and configures a HostStrategy with template "__tenant__.*" to the application.
        /// </summary>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithHostStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder)
            where TTenantInfo : class, ITenantInfo, new()
            => builder.WithHostStrategy($"{Constants.TenantToken}.*");

        /// <summary>
        /// Adds and configures a HostStrategy to the application.
        /// </summary>
        /// <param name="template">The template for determining the tenant identifier in the host.</param>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithHostStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder, string template)
            where TTenantInfo : class, ITenantInfo, new()
        {
            if (string.IsNullOrWhiteSpace(template))
            {
                throw new ArgumentException("Invalid value for \"template\"", nameof(template));
            }

            return builder.WithStrategy<HostStrategy>(ServiceLifetime.Singleton, new object[] { template });
        }

        /// <summary>
        /// Adds and configures a ClaimStrategy with tenantKey "__tenant__" to the application.
        /// </summary>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithClaimStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder) where TTenantInfo : class, ITenantInfo, new()
        {
            return builder.WithStrategy<ClaimStrategy>(ServiceLifetime.Singleton, Constants.TenantToken);
        }

        /// <summary>
        /// Adds and configures a HostStrategy to the application.
        /// </summary>
        /// <param name="tenantKey">The template for determining the tenant identifier in the host.</param>
        /// <returns>The same MultiTenantBuilder passed into the method.</returns>
        public static FinbuckleMultiTenantBuilder<TTenantInfo> WithClaimStrategy<TTenantInfo>(this FinbuckleMultiTenantBuilder<TTenantInfo> builder, string tenantKey) where TTenantInfo : class, ITenantInfo, new()
        {
            return builder.WithStrategy<ClaimStrategy>(ServiceLifetime.Singleton, tenantKey);
        }
    }
}


text:
An NSURL extension for showing preview info of webpages.

You may want to use it if you want to mimick Facebook app's behavior when you post a link on your status.

![Screenshot](https://raw.githubusercontent.com/itsmeichigo/URLPreview/master/ScreenShot.png)

## Requirements

- Swift 5 & Xcode 10.2
- This library depends on [Kanna](https://github.com/tid-kijyun/Kanna)

## Usage

Pretty simple, all you need is a block:

```Swift
if let url = NSURL(string: urlTextField.text!) {
    url.fetchPageInfo({ (title, description, previewImage) -> Void in
      // do whatever you want here
    }, failure: { (errorMessage) -> Void in
      print(errorMessage)
    })
} else {
  print("Invalid URL!")
}
```

## Contributing

Contributions for bug fixing or improvements are welcome. Feel free to submit a pull request.

## Licence

URLPreview is available under the MIT license. See the LICENSE file for more info.


text:
First of all, thank you for taking time to contribute to Concuerror!

If you don't know where to start, here are some ["help wanted"][help wanted] issues.

## I want to ask a question.

Use the [mailing list][mailing list] and take a look at the [FAQ][faq] if you haven't already!

## I want to report a bug.

* Ensure that you can reproduce the bug on the [latest version of the `master` branch][latest].

* Take a moment to check whether the bug has already been reported by searching Github's [Issues][Issues]. If you find a relevant one, leave a comment there.

* If you cannot find an existing relevant Issue, [open a new bug Issue][open a new bug Issue].

## I want to write a patch that fixes a bug.

* Find/write at least one small test that fails without the patch.

* Fork Concuerror's repository and push a new branch for your patch, using a suitably descriptive name.

* Make sure to also commit the tests that need the patch. You can find out how test suites are organized in the README files of the [test][test], [tests][tests] and [tests-real][tests-real] directories.

* Make a [Pull Request][pull request].

## I want to suggest a feature.

* **Take a moment to check whether a similar feature has already been requested** by searching Github's [Issues][Issues]. If you find a relevant Issue, leave a comment there.

* Apart from the main repository, take a look at the Issues page of the developer's own fork: [@aronisstav Issues][aronisstav Issues]

* If you cannot find an existing relevant Issue, [open a new feature Issue][open a new feature Issue].

## Code of Conduct

This project and everyone participating in it is governed by the [Contributor Covenant Code of Conduct][Contributor Covenant Code of Conduct]. By participating, you are expected to uphold this code. Please report unacceptable behavior to info@concuerror.com.

Thanks! :heart:

[@aronisstav](https://github.com/aronisstav)

<!-- Links -->
[aronisstav Issues]: https://github.com/aronisstav/Concuerror/issues
[Contributor Covenant Code of Conduct]: ./CODE_OF_CONDUCT.md
[faq]: http://parapluu.github.io/Concuerror/faq
[help wanted]: https://github.com/parapluu/Concuerror/labels/help%20wanted
[Issues]: https://github.com/parapluu/Concuerror/issues
[latest]: https://github.com/parapluu/Concuerror/
[mailing list]: http://parapluu.github.io/Concuerror/contact
[open a new bug Issue]: https://github.com/parapluu/Concuerror/issues/new?template=issue_template_bug.md&labels=bug
[open a new feature Issue]: https://github.com/parapluu/Concuerror/issues/new?template=issue_template_feature.md&labels=feature
[pull request]: https://github.com/parapluu/Concuerror/compare
[test]: ./test
[tests]: ./tests
[tests-real]: ./tests-real


text:
package galileo.util;

public class Math {
	public static Float getFloat(String number) {
		try {
			return Float.parseFloat(number);
		} catch (Exception e) {
			return Float.NaN;
		}
	}

	public static Integer getInteger(String number){
		try {
			return Integer.parseInt(number);
		} catch (Exception e) {
			return 0;
		}
	}

	public static Long getLong(String number){
		try {
			return Long.parseLong(number);
		} catch (Exception e) {
			return 0l;
		}
	}

	public static Double getDouble(String number){
		try {
			return Double.parseDouble(number);
		} catch (Exception e) {
			return Double.NaN;
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
        <item
        android:drawable="@drawable/upomp_lthj_button_blue_noselect"
        android:top="0dip"
        android:right="0dip"
        android:bottom="0dip"
        android:left="0dip" />
        <item
        android:drawable="@drawable/upomp_lthj_button_select"
        android:top="0dip"
        android:right="0dip"
        android:bottom="0dip"
        android:left="0dip" />
</layer-list>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CaveStory
{
    public interface IDamageable
    {
        GameUnit CenterX { get; }
        GameUnit CenterY { get; }
        FloatingNumber DamageText { get; }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__CWE839_negative_84_goodG2B.cpp
Label Definition File: CWE124_Buffer_Underwrite__CWE839.label.xml
Template File: sources-sinks-84_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 124 Buffer Underwrite
 * BadSource: negative Negative index value
 * GoodSource: Non-negative but less than 10
 * Sinks:
 *    GoodSink: Ensure the array index is valid
 *    BadSink : Improperly check the array index by not checking the lower bound
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE124_Buffer_Underwrite__CWE839_negative_84.h"

namespace CWE124_Buffer_Underwrite__CWE839_negative_84
{
CWE124_Buffer_Underwrite__CWE839_negative_84_goodG2B::CWE124_Buffer_Underwrite__CWE839_negative_84_goodG2B(int dataCopy)
{
    data = dataCopy;
    /* FIX: Use a value greater than 0, but less than 10 to avoid attempting to
    * access an index of the array in the sink that is out-of-bounds */
    data = 7;
}

CWE124_Buffer_Underwrite__CWE839_negative_84_goodG2B::~CWE124_Buffer_Underwrite__CWE839_negative_84_goodG2B()
{
    {
        int i;
        int buffer[10] = { 0 };
        /* POTENTIAL FLAW: Attempt to access a negative index of the array
        * This code does not check to see if the array index is negative */
        if (data < 10)
        {
            buffer[data] = 1;
            /* Print the array values */
            for(i = 0; i < 10; i++)
            {
                printIntLine(buffer[i]);
            }
        }
        else
        {
            printLine("ERROR: Array index is negative.");
        }
    }
}
}
#endif /* OMITGOOD */


text:
class AnnouncementNotificationService;
class Profile;

// Factory to create FastTrackNotificationService.
class AnnouncementNotificationServiceFactory
    : public BrowserContextKeyedServiceFactory {
 public:
  static AnnouncementNotificationServiceFactory* GetInstance();
  static AnnouncementNotificationService* GetForProfile(Profile* profile);

  AnnouncementNotificationServiceFactory(
      const AnnouncementNotificationServiceFactory&) = delete;
  AnnouncementNotificationServiceFactory& operator=(
      const AnnouncementNotificationServiceFactory&) = delete;

 private:
  friend class base::NoDestructor<AnnouncementNotificationServiceFactory>;

  // BrowserContextKeyedServiceFactory implementation.
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;
  content::BrowserContext* GetBrowserContextToUse(
      content::BrowserContext* context) const override;

  AnnouncementNotificationServiceFactory();
  ~AnnouncementNotificationServiceFactory() override;
};

#endif  // CHROME_BROWSER_UPDATES_ANNOUNCEMENT_NOTIFICATION_ANNOUNCEMENT_NOTIFICATION_SERVICE_FACTORY_H_


text:
package com.almasb.easyio.manual;

import com.almasb.easyio.FS;
import com.almasb.easyio.IOTask;
import com.almasb.easyio.UIDialogHandler;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Almas Baimagambetov (almaslvl@gmail.com)
 */
public class ReadAppTest extends Application {

    private Parent createContent() {

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setContentText("Reading from ...");

        ExecutorService executor = Executors.newSingleThreadExecutor();

        Text text = new Text();

        Button btn = new Button("Say Hi");
        btn.setOnAction(e -> {
            System.out.println("Hi");
        });

        Button btn2 = new Button("READ");
        btn2.setOnAction(e -> {

            FS.loadDirectoryNamesTask("./", false)
                    .onSuccess(names -> System.out.println(names))
                    .onFailure(error -> System.out.println(error))
                    .executeAsync(executor);

//            new IOTask<String>() {
//
//                @Override
//                protected String onExecute() throws Exception {
//                    System.out.println(Thread.currentThread().getName());
//
//                    return Files.readAllLines(Paths.get("reading.txt")).get(0);
//                }
//            }
//                    .onSuccess(line -> {
//                        text.setText(line);
//                        executor.shutdownNow();
//                    })
//                    .onFailure(System.out::println)
//                    //.execute();
//                    //.executeAsync(executor);
//                    .executeAsyncWithDialog(executor, new UIDialogHandler() {
//
//                        @Override
//                        public void show() {
//                            Platform.runLater(alert::show);
//                        }
//
//                        @Override
//                        public void dismiss() {
//                            Platform.runLater(alert::close);
//                        }
//                    });
        });

        VBox vbox = new VBox(btn, btn2, text);
        vbox.setAlignment(Pos.CENTER);
        vbox.setPrefSize(400, 400);
        return vbox;
    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setScene(new Scene(createContent()));
        stage.show();
    }
}


text:
<?php namespace Permit\Token;

use Permit\Random\GeneratorInterface;

trait GeneratesTokens
{

    /**
     * Set the length of the tokens
     *
     * @var array
     **/
    protected $tokenLengths = [
        RepositoryInterface::REMEMBER          => 60,
        RepositoryInterface::ACTIVATION        => 60,
        RepositoryInterface::PASSWORD_RESET    => 60,
        RepositoryInterface::OAUTH             => 60
    ];

    /**
     * @var \Permit\Random\GeneratorInterface
     **/
    protected $randomGenerator;

    /**
     * Checks the token (by its length)
     *
     * @param string
     * @return bool
     **/
    public function isValid($token, $type)
    {
        return (strlen($token) == $this->getTokenLength($type));
    }

    /**
     * Return the token length for tokens of type $type
     *
     * @param int $type (see \Permit\Token\RepositoryInterface::REMEMBER...)
     * @return int
     **/
    public function getTokenLength($type)
    {
        return $this->tokenLengths[$type];
    }

    /**
     * Set the token length for token of type $type. If you dont pass the
     * type, all lengths will be set
     *
     * @param int $length
     * @param int $type (see \Permit\Token\RepositoryInterface::REMEMBER...)
     * @return self
     **/
    public function setTokenLength($length, $type=null)
    {
        if ($type) {
            $this->tokenLengths[$type] = $length;
            return $this;
        }

        foreach ($this->tokenLengths as $type=>$oldLength) {
            $this->tokenLengths[$type] = $length;
        }

        return $this;
    }

    /**
     * @return \Permit\Random\GeneratorInterface
     **/
    public function getRandomGenerator()
    {
        return $this->randomGenerator;
    }

    /**
     * Set a random generator
     *
     * @param \Permit\Random\GeneratorInterface $generator
     * @return self
     **/
    public function setRandomGenerator(GeneratorInterface $generator)
    {
        $this->randomGenerator = $generator;
        return $this;
    }

    /**
     * Generates a token of type $type
     *
     * @param int $type (see \Permit\Token\RepositoryInterface::REMEMBER...)
     * @return string
     **/
    protected function generateToken($type)
    {
        return $this->randomGenerator->generate($this->getTokenLength($type));
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>ENPM808_Final: /home/viki/Documents/ENPM808X/Final/catkin_ws/src/ENPM808_Final/test/vehicleTest.cpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

ENPM808_Final

Final project for ENPM 808X

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

 All Classes Files Functions

test

Functions

vehicleTest.cpp File Reference

Unit tests for the Vehicle class.
More...

#include <ros/ros.h>

#include <gtest/gtest.h>

#include <vehicle.hpp>

Functions

 	TEST (TestSuite, drive_command_published)

 	Test that verifies that the vehicle is publishing velocity commands.  More...

Detailed Description

Unit tests for the Vehicle class.

This file is used to run all unit tests for the Vehicle ROS node

Author

Patrick Nolan (patnolan33)

Copyright

MIT License.

Function Documentation

          TEST
          (
          TestSuite
          ,

          drive_command_published

          )

Test that verifies that the vehicle is publishing velocity commands.

<address class="footer">
Generated on Tue May 9 2017 15:20:59 for ENPM808_Final by

 1.8.6
</address>


text:
@interface RNNReactComponentRegistry () {
	id<RNNRootViewCreator> _creator;
	NSMutableDictionary* _componentStore;
}

@end

@implementation RNNReactComponentRegistry

- (instancetype)initWithCreator:(id<RNNRootViewCreator>)creator {
	self = [super init];
	_creator = creator;
	_componentStore = [NSMutableDictionary new];
	return self;
}

- (RNNReactView *)createComponentIfNotExists:(RNNComponentOptions *)component parentComponentId:(NSString *)parentComponentId reactViewReadyBlock:(RNNReactViewReadyCompletionBlock)reactViewReadyBlock {
	NSMutableDictionary* parentComponentDict = [self componentsForParentId:parentComponentId];

	RNNReactView* reactView = [parentComponentDict objectForKey:component.componentId.get];
	if (!reactView) {
		reactView = (RNNReactView *)[_creator createRootViewFromComponentOptions:component reactViewReadyBlock:reactViewReadyBlock];
		[parentComponentDict setObject:reactView forKey:component.componentId.get];
	} else if (reactViewReadyBlock) {
		reactViewReadyBlock();
	}

	return reactView;
}

- (NSMutableDictionary *)componentsForParentId:(NSString *)parentComponentId {
	if (!_componentStore[parentComponentId]) {
		[_componentStore setObject:[NSMutableDictionary new] forKey:parentComponentId];;
	}

	return [_componentStore objectForKey:parentComponentId];;
}

- (void)removeComponent:(NSString *)componentId {
	if ([_componentStore objectForKey:componentId]) {
		[_componentStore removeObjectForKey:componentId];
	}
}

- (void)clean {
	[_componentStore removeAllObjects];
}

@end


text:
namespace quic {
namespace test {

QuicReferenceCountedPointer<QuicCryptoServerConfig::Config>
QuicCryptoServerConfigPeer::GetPrimaryConfig() {
  QuicReaderMutexLock locked(&server_config_->configs_lock_);
  return QuicReferenceCountedPointer<QuicCryptoServerConfig::Config>(
      server_config_->primary_config_);
}

QuicReferenceCountedPointer<QuicCryptoServerConfig::Config>
QuicCryptoServerConfigPeer::GetConfig(std::string config_id) {
  QuicReaderMutexLock locked(&server_config_->configs_lock_);
  if (config_id == "<primary>") {
    return QuicReferenceCountedPointer<QuicCryptoServerConfig::Config>(
        server_config_->primary_config_);
  } else {
    return server_config_->GetConfigWithScid(config_id);
  }
}

ProofSource* QuicCryptoServerConfigPeer::GetProofSource() const {
  return server_config_->proof_source_.get();
}

void QuicCryptoServerConfigPeer::ResetProofSource(
    std::unique_ptr<ProofSource> proof_source) {
  server_config_->proof_source_ = std::move(proof_source);
}

std::string QuicCryptoServerConfigPeer::NewSourceAddressToken(
    std::string config_id,
    SourceAddressTokens previous_tokens,
    const QuicIpAddress& ip,
    QuicRandom* rand,
    QuicWallTime now,
    CachedNetworkParameters* cached_network_params) {
  return server_config_->NewSourceAddressToken(*GetConfig(config_id),
                                               previous_tokens, ip, rand, now,
                                               cached_network_params);
}

HandshakeFailureReason QuicCryptoServerConfigPeer::ValidateSourceAddressTokens(
    std::string config_id,
    quiche::QuicheStringPiece srct,
    const QuicIpAddress& ip,
    QuicWallTime now,
    CachedNetworkParameters* cached_network_params) {
  SourceAddressTokens tokens;
  HandshakeFailureReason reason = server_config_->ParseSourceAddressToken(
      *GetConfig(config_id), srct, &tokens);
  if (reason != HANDSHAKE_OK) {
    return reason;
  }

  return server_config_->ValidateSourceAddressTokens(tokens, ip, now,
                                                     cached_network_params);
}

HandshakeFailureReason
QuicCryptoServerConfigPeer::ValidateSingleSourceAddressToken(
    quiche::QuicheStringPiece token,
    const QuicIpAddress& ip,
    QuicWallTime now) {
  SourceAddressTokens tokens;
  HandshakeFailureReason parse_status = server_config_->ParseSourceAddressToken(
      *GetPrimaryConfig(), token, &tokens);
  if (HANDSHAKE_OK != parse_status) {
    return parse_status;
  }
  EXPECT_EQ(1, tokens.tokens_size());
  return server_config_->ValidateSingleSourceAddressToken(tokens.tokens(0), ip,
                                                          now);
}

void QuicCryptoServerConfigPeer::CheckConfigs(
    std::vector<std::pair<std::string, bool>> expected_ids_and_status) {
  QuicReaderMutexLock locked(&server_config_->configs_lock_);

  ASSERT_EQ(expected_ids_and_status.size(), server_config_->configs_.size())
      << ConfigsDebug();

  for (const std::pair<
           const ServerConfigID,
           QuicReferenceCountedPointer<QuicCryptoServerConfig::Config>>& i :
       server_config_->configs_) {
    bool found = false;
    for (std::pair<ServerConfigID, bool>& j : expected_ids_and_status) {
      if (i.first == j.first && i.second->is_primary == j.second) {
        found = true;
        j.first.clear();
        break;
      }
    }

    ASSERT_TRUE(found) << "Failed to find match for " << i.first
                       << " in configs:\n"
                       << ConfigsDebug();
  }
}

// ConfigsDebug returns a std::string that contains debugging information about
// the set of Configs loaded in |server_config_| and their status.
std::string QuicCryptoServerConfigPeer::ConfigsDebug() {
  if (server_config_->configs_.empty()) {
    return "No Configs in QuicCryptoServerConfig";
  }

  std::string s;

  for (const auto& i : server_config_->configs_) {
    const QuicReferenceCountedPointer<QuicCryptoServerConfig::Config> config =
        i.second;
    if (config->is_primary) {
      s += "(primary) ";
    } else {
      s += "          ";
    }
    s += config->id;
    s += "\n";
  }

  return s;
}

void QuicCryptoServerConfigPeer::SelectNewPrimaryConfig(int seconds) {
  QuicWriterMutexLock locked(&server_config_->configs_lock_);
  server_config_->SelectNewPrimaryConfig(
      QuicWallTime::FromUNIXSeconds(seconds));
}

std::string QuicCryptoServerConfigPeer::CompressChain(
    QuicCompressedCertsCache* compressed_certs_cache,
    const QuicReferenceCountedPointer<ProofSource::Chain>& chain,
    const std::string& client_common_set_hashes,
    const std::string& client_cached_cert_hashes,
    const CommonCertSets* common_sets) {
  return QuicCryptoServerConfig::CompressChain(
      compressed_certs_cache, chain, client_common_set_hashes,
      client_cached_cert_hashes, common_sets);
}

uint32_t QuicCryptoServerConfigPeer::source_address_token_future_secs() {
  return server_config_->source_address_token_future_secs_;
}

uint32_t QuicCryptoServerConfigPeer::source_address_token_lifetime_secs() {
  return server_config_->source_address_token_lifetime_secs_;
}

}  // namespace test
}  // namespace quic


text:
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell       #-}

module Lexer
    ( lexString
    , tests
    , Token (..)
    ) where

import           Control.Applicative                  ((<$>))
import           Data.DeriveTH
import           Text.Parsec

import           Test.Framework                       (testGroup)
import           Test.Framework.Providers.QuickCheck2 (testProperty)
import           Test.Framework.TH
import           Test.HUnit
import           Test.QuickCheck
import           Test.QuickCheck.Modifiers

data Calculation = Invalid String | Valid Integer deriving (Eq, Show)

data Token = IntegerToken (Positive Integer) | Minus | Plus | LeftParen | RightParen | Divide | Times deriving (Eq, Show)

$( derive makeArbitrary ''Token )

integer :: Stream s m Char => ParsecT s u m (Positive Integer)
integer = Positive <$> read <$> lexeme (many1 digit)

lexString :: String -> Either ParseError [Token]
lexString = parse lexer "string"

lexer :: Stream s m Char => ParsecT s u m [Token]
lexer = many1 tokenP

tokenP :: Stream s m Char => ParsecT s u m Token
tokenP = (IntegerToken <$> integer) <|> minus <|> plus <|> leftParen <|> rightParen <|> divide <|> times

minus, plus, leftParen, rightParen, divide, times :: Stream s m Char => ParsecT s u m Token
minus = symbolc '-' >> return Minus
plus = symbolc '+' >> return Plus
leftParen = symbolc '(' >> return LeftParen
rightParen = symbolc ')' >> return RightParen
divide = symbolc '/' >> return Divide
times = symbolc '*' >> return Times

symbolc :: Stream s m Char => Char -> ParsecT s u m Char
symbolc c = lexeme (char c)

lexeme p = do
    val <- p
    spaces
    return val

prop_tokenize :: NonEmptyList Token -> Bool
prop_tokenize (NonEmpty tokens) = tokens == either (error . show) id (lexString (printToken tokens))

printToken :: [Token] -> String
printToken [] = ""
printToken (IntegerToken (Positive i) : t@(IntegerToken (Positive j)) : ts) = show i ++ " " ++ printToken (t:ts)
printToken (IntegerToken (Positive i) : ts) = show i  ++ printToken ts
printToken (Minus : ts) = "-" ++ printToken ts
printToken (Plus : ts) = "+" ++ printToken ts
printToken (LeftParen : ts) = "(" ++ printToken ts
printToken (RightParen : ts) = ")" ++ printToken ts
printToken (Divide : ts) = "/" ++ printToken ts
printToken (Times : ts) = "*" ++ printToken ts

tests = $(testGroupGenerator)


text:
package org.sagebionetworks.repo.model.dbo.dao;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Date;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.sagebionetworks.ids.IdGenerator;
import org.sagebionetworks.ids.IdType;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.UserGroup;
import org.sagebionetworks.repo.model.dbo.DBOBasicDao;
import org.sagebionetworks.repo.model.dbo.DatabaseObject;
import org.sagebionetworks.repo.model.dbo.persistence.DBOUserGroup;
import org.sagebionetworks.repo.model.message.ChangeType;
import org.sagebionetworks.repo.model.message.TransactionalMessenger;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.test.util.ReflectionTestUtils;

public class DBOUserGroupDAOImplUnitTest {

	@Mock
	private TransactionalMessenger mockTransactionalMessenger;
	@Mock
	private IdGenerator mockIdGenerator;
	@Mock
	private DBOBasicDao mockBasicDAO;
	@Mock
	private NamedParameterJdbcTemplate mockNamedJdbcTemplate;
	private DBOUserGroupDAOImpl userGroupDAO;
	private UserGroup ug;
	private Long id = 1L;

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);
		userGroupDAO = new DBOUserGroupDAOImpl();
		ReflectionTestUtils.setField(userGroupDAO, "basicDao", mockBasicDAO);
		ReflectionTestUtils.setField(userGroupDAO, "idGenerator", mockIdGenerator);
		ReflectionTestUtils.setField(userGroupDAO, "transactionalMessenger", mockTransactionalMessenger);
		ReflectionTestUtils.setField(userGroupDAO, "namedJdbcTemplate", mockNamedJdbcTemplate);

		ug = new UserGroup();
		ug.setCreationDate(new Date());
		ug.setEtag("etag");
		ug.setId(id.toString());
		ug.setIsIndividual(false);

		Mockito.when(mockIdGenerator.generateNewId(IdType.PRINCIPAL_ID)).thenReturn(id);
		doAnswer(new Answer<DBOUserGroup>(){
			@Override
			public DBOUserGroup answer(InvocationOnMock invocation) throws Throwable {
				return (DBOUserGroup) invocation.getArguments()[0];
			}}).when(mockBasicDAO).createNew(any(DBOUserGroup.class));
		DBOUserGroup dbo = new DBOUserGroup();
		dbo.setId(Long.parseLong(ug.getId()));
		dbo.setEtag(ug.getEtag());
		UserGroupUtils.copyDtoToDbo(ug, dbo);
		when(mockNamedJdbcTemplate.queryForObject(anyString(), any(SqlParameterSource.class), any(RowMapper.class))).thenReturn(dbo);
		when(mockBasicDAO.update(any(DatabaseObject.class))).thenReturn(true);
	}

	@Test
	public void createSendMessageTest() {
		userGroupDAO.create(ug);
		ArgumentCaptor<Long> idCapture = ArgumentCaptor.forClass(Long.class);
		ArgumentCaptor<ObjectType> objectTypeCapture = ArgumentCaptor.forClass(ObjectType.class);
		ArgumentCaptor<ChangeType> typeCapture = ArgumentCaptor.forClass(ChangeType.class);
		verify(mockTransactionalMessenger).sendMessageAfterCommit(idCapture.capture().toString(), objectTypeCapture.capture(), typeCapture.capture());
		assertEquals(idCapture.getValue(), id.toString());
		assertEquals(ObjectType.PRINCIPAL, objectTypeCapture.getValue());
		assertEquals(ChangeType.CREATE, typeCapture.getValue());
	}

	@Test
	public void updateSendMessageTest() {
		userGroupDAO.update(ug);
		ArgumentCaptor<Long> idCapture = ArgumentCaptor.forClass(Long.class);
		ArgumentCaptor<ObjectType> objectTypeCapture = ArgumentCaptor.forClass(ObjectType.class);
		ArgumentCaptor<ChangeType> typeCapture = ArgumentCaptor.forClass(ChangeType.class);
		verify(mockTransactionalMessenger).sendMessageAfterCommit(idCapture.capture().toString(), objectTypeCapture.capture(), typeCapture.capture());
		assertEquals(idCapture.getValue(), id.toString());
		assertEquals(ObjectType.PRINCIPAL, objectTypeCapture.getValue());
		assertEquals(ChangeType.UPDATE, typeCapture.getValue());
	}

}


text:
#include "precomp.h"
#include "Debug.h"

ULONG g_debugLevel = LOG_INFO;

NDIS_STRING g_extensionFriendlyName;
NDIS_STRING g_extensionGuid;