text:
.. _nugroup:

nugroup
===========================================

.. class:: nugroup.NUGroup(bambou.nurest_object.NUMetaRESTObject,):

Identifies a group within an enterprise

Attributes
----------

- ``ldap_group_dn``: The LDAP distinguished name (DN) for the group.

- ``name`` (**Mandatory**): A unique name of the group

- ``management_mode``: Management mode of the user object - allows for override of external authorization and syncup

- ``last_updated_by``: ID of the user who last updated the object.

- ``account_restrictions``: Determines whether group is disabled or not.

- ``description``: Description of the group

- ``restriction_date``: When the group was disabled.

- ``entity_scope``: Specify if scope of entity is Data center or Enterprise level

- ``role``: The role associated with this group.

- ``private``: A private group is visible only by the owner of the group. Public groups are visible by all users in the enterprise

- ``external_id``: External object ID. Used for integration with third party systems

Children
--------

================================================================================================================================================               ==========================================================================================
**class**                                                                                **fetcher**

:ref:`numetadata.NUMetadata<numetadata>`                                                                                ``metadatas``
:ref:`nuglobalmetadata.NUGlobalMetadata<nuglobalmetadata>`                                                                                ``global_metadatas``
:ref:`nuuser.NUUser<nuuser>`                                                                                ``users``
:ref:`nueventlog.NUEventLog<nueventlog>`                                                                                ``event_logs``
================================================================================================================================================               ==========================================================================================

Parents
--------

- :ref:`nuenterprise.NUEnterprise<nuenterprise>`

- :ref:`nuzone.NUZone<nuzone>`

- :ref:`nul2domaintemplate.NUL2DomainTemplate<nul2domaintemplate>`

- :ref:`nudomain.NUDomain<nudomain>`

- :ref:`nul2domain.NUL2Domain<nul2domain>`

- :ref:`nudomaintemplate.NUDomainTemplate<nudomaintemplate>`

- :ref:`nuuser.NUUser<nuuser>`


text:
<!--
id: 1709098032
link: http://tumblr.atmos.org/post/1709098032/national-geographics-photography-contest-2010
slug: national-geographics-photography-contest-2010
date: Sat Nov 27 2010 18:57:21 GMT-0800 (PST)
publish: 2010-11-027
tags:
title: National Geographic’s Photography Contest 2010 - The Big Picture - Boston.com
-->

National Geographic’s Photography Contest 2010 - The Big Picture - Boston.com
===================================================================================

![](http://www.tumblr.com/photo/1280/atmos/1709098032/1/tumblr_lckqvl7YP61qz4sng)

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geronimo.kernel.basic;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.reflect.FastClass;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.kernel.ClassLoading;
import org.apache.geronimo.kernel.GBeanNotFoundException;
import org.apache.geronimo.kernel.Kernel;
import org.apache.geronimo.kernel.classloader.DelegatingClassLoader;
import org.apache.geronimo.kernel.proxy.ProxyCreationException;
import org.apache.geronimo.kernel.proxy.ProxyFactory;
import org.apache.geronimo.kernel.proxy.ProxyManager;

/**
 * Creates proxies that communicate directly with a Kernel located in the same
 * JVM as the client.
 *
 * @version $Rev:386515 $ $Date$
 */
public class BasicProxyManager implements ProxyManager {
    private final static String MANAGED_BEAN_NAME = "org.apache.geronimo.kernel.proxy.GeronimoManagedBean";
    private final static Logger log = LoggerFactory.getLogger(BasicProxyManager.class);
    private final Kernel kernel;

    private final Map interceptors = Collections.synchronizedMap(new BasicProxyMap());

    public BasicProxyManager(Kernel kernel) {
        this.kernel = kernel;
    }

    public ProxyFactory createProxyFactory(Class[] types, ClassLoader classLoader) {
        if (types == null) throw new NullPointerException("type is null");
        if (types.length == 0) throw new IllegalArgumentException("interface list is empty");
        if (classLoader == null) throw new NullPointerException("classLoader is null");

        Class managedBean = null;
        try {
            managedBean = classLoader.loadClass(MANAGED_BEAN_NAME);
        } catch (ClassNotFoundException e) {
            // Can't load GeronimoManagedBean if the incoming type doesn't have a ClassLoader set
            log.debug("Unable to add GeronimoManagedBean to proxy (specified class loader does not have class)");
        }

        if(managedBean != null) {
            Class[] adjusted = new Class[types.length+1];
            System.arraycopy(types, 0, adjusted, 0, types.length);
            adjusted[types.length] = managedBean;
            types = adjusted;
        }

        return new ManagedProxyFactory(types, classLoader);
    }

    public <T> T createProxy(AbstractName target, Class<T> type) {
        if (target == null) throw new NullPointerException("target is null");
        if (type == null) throw new NullPointerException("type is null");

        try {
            // if the type is visible from the target's classloader use it
            // otherwise use the type's classloader
            ClassLoader classLoader = type.getClassLoader();

            // add any interface exposed by the gbean that is visible from the selected class loader
            List<Class> types = getVisibleInterfaces(target, classLoader, true);
            if (types == null) {
                types = new ArrayList<Class>();
            }
            types.add(type);

            DelegatingClassLoader proxyClassLoader = new DelegatingClassLoader();
            proxyClassLoader.addLoader(classLoader);
            proxyClassLoader.addLoader(getClass()); // to be able to load GeronimoManagedBean

            return (T) createProxyFactory((Class[]) types.toArray(new Class[types.size()]), proxyClassLoader).createProxy(target);
        } catch (GBeanNotFoundException e) {
            throw new IllegalArgumentException("Could not get GBeanInfo for target object: " + target, e);
        }
    }

    public Object createProxy(AbstractName target, ClassLoader classLoader) {
        if (target == null) throw new NullPointerException("target is null");
        if (classLoader == null) throw new NullPointerException("classLoader is null");

        try {
            List<Class> types = getVisibleInterfaces(target, classLoader, true);
            if (types == null) {
                return null;
            }

            DelegatingClassLoader proxyClassLoader = new DelegatingClassLoader();
            proxyClassLoader.addLoader(classLoader);
            proxyClassLoader.addLoader(getClass()); // to be able to load GeronimoManagedBean

            return createProxyFactory((Class[]) types.toArray(new Class[types.size()]), proxyClassLoader).createProxy(target);
        } catch (GBeanNotFoundException e) {
            throw new IllegalArgumentException("Could not get GBeanInfo for target object: " + target, e);
        }
    }

    private List<Class> getVisibleInterfaces(AbstractName target, ClassLoader classLoader, boolean shouldLog) throws GBeanNotFoundException {
        GBeanInfo info = kernel.getGBeanInfo(target);
        Set<String> interfaces = info.getInterfaces();
        if(interfaces.size() == 0) {
            if (shouldLog) {
                log.warn("No interfaces found for " + target + " ("+target+")");
            }
            return null;
        }
        String[] names = (String[]) interfaces.toArray(new String[0]);
        List<Class> types = new ArrayList<Class>();
        for (int i = 0; i < names.length; i++) {
            try {
                Class<?> type = classLoader.loadClass(names[i]);
                if (type.isInterface()) {
                    types.add(type);
                }
            } catch (ClassNotFoundException e) {
                if (shouldLog) {
                    log.warn("Could not load interface "+names[i]+" in provided ClassLoader for "+target);
                }
            }
        }
        return types;
    }

    public void destroyProxy(Object proxy) {
        if (proxy == null) {
            return;
        }

        MethodInterceptor methodInterceptor = (MethodInterceptor) interceptors.remove(proxy);
        if (methodInterceptor != null) {
            doDestroy(methodInterceptor);
        }
    }

    public boolean isProxy(Object proxy) {
        return interceptors.containsKey(proxy);
    }

    public AbstractName getProxyTarget(Object proxy) {
        MethodInterceptor methodInterceptor = (MethodInterceptor) interceptors.get(proxy);
        if (methodInterceptor == null) {
            return null;
        }
        return getAbstractName(methodInterceptor);
    }

    private class ManagedProxyFactory implements ProxyFactory {
        private final Class proxyType;
        private final FastClass fastClass;

        public ManagedProxyFactory(Class type, ClassLoader classLoader) {
            this(new Class[]{type}, classLoader);
        }

        public ManagedProxyFactory(Class[] type, ClassLoader classLoader) {
            Enhancer enhancer = new Enhancer();
            if(type.length > 1) { // shrink first -- may reduce from many to one
                type = ClassLoading.reduceInterfaces(type);
            }
            if(type.length == 0) {
                throw new IllegalArgumentException("Cannot generate proxy for 0 interfaces!");
            } else if(type.length == 1) { // Unlikely (as a result of GeronimoManagedBean)
                enhancer.setSuperclass(type[0]);
            } else {
                if(type[0].isInterface()) {
                    enhancer.setSuperclass(Object.class);
                    enhancer.setInterfaces(type);
                } else { // there's a class and reduceInterfaces put the class in the first spot
                    Class[] intfs = new Class[type.length-1];
                    System.arraycopy(type, 1, intfs, 0, intfs.length);
                    enhancer.setSuperclass(type[0]);
                    enhancer.setInterfaces(intfs);
                }
            }
            enhancer.setClassLoader(classLoader);
            enhancer.setCallbackType(MethodInterceptor.class);
            enhancer.setUseFactory(false);
            proxyType = enhancer.createClass();
            fastClass = FastClass.create(proxyType);
        }

        public Object createProxy(AbstractName target) {
            assert target != null: "target is null";

            Callback callback = getMethodInterceptor(proxyType, kernel, target);

            try {
                Enhancer.registerCallbacks(proxyType, new Callback[]{callback});
                Object proxy = fastClass.newInstance();
                interceptors.put(proxy, callback);
                return proxy;
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                } else  if (cause instanceof Error) {
                    throw (Error) cause;
                } else if (cause != null) {
                    throw new ProxyCreationException(cause);
                } else {
                    throw new ProxyCreationException(e);
                }
            } finally {
                Enhancer.registerCallbacks(proxyType, null);
            }
        }
    }

    protected Callback getMethodInterceptor(Class proxyType, Kernel kernel, AbstractName target) {
        return new ProxyMethodInterceptor(proxyType, kernel, target);
    }

    protected void doDestroy(MethodInterceptor methodInterceptor) {
         ((ProxyMethodInterceptor)methodInterceptor).destroy();
    }

    protected AbstractName getAbstractName(MethodInterceptor methodInterceptor) {
        return ((ProxyMethodInterceptor)methodInterceptor).getAbstractName();
    }
}


text: An ASP.NET Web app,, containerized with an ASP.NET Core WebAPI


text:
var fs = require('fs');
var webpack = require('webpack');
var path = require('path');
var CopyFilesPlugin = require('copy-webpack-plugin');
var UglifyJsPlugin = require('webpack-uglify-js-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    devtool: 'source-map',
    entry: {
        index: path.join(__dirname, 'js/index.js'),
        login: path.join(__dirname, 'js/login.js'),
        createnewone: path.join(__dirname, 'js/createnewone.js'),
        projectDetail: path.join(__dirname, 'js/projectDetail.js'),
        profile: path.join(__dirname, 'js/profile.js')
        //Server
        //database: path.join(__dirname, 'js/server/database.js'),
        //server: path.join(__dirname, 'js/server/server.js')
    },
    output: {
        path: path.join(__dirname, 'dist/public/'),
        filename: '[name].js'
    },

    module: {
        rules: [
            {
                test: /\.less$/,
                exclude: /node_modules/,
                loader: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader!less-loader"
                })
            },
            {
                test: /\.css$/,
                loader: 'css-loader'
            },
            {
                test: /\.ts$/,
                exclude: /node_modules/,
                loader: 'ts-loader'
            },
            {
                test: /\.(jpeg|jpg|png|woff|woff2|eot|ttf|svg)$/,
                exclude: /node_modules/,
                loader: 'url-loader',
                options: {
                    limit: 100000
                }
            }
        ]
    },

    resolve: {
        extensions: ['.js', '.es6', 'json: false', 'ts', 'less'],
        alias: {
         'vue$': 'vue/dist/vue.common.js'
        },
        enforceExtension: false
    },

    plugins: [
        new CopyFilesPlugin([
            { from: 'img', to: path.resolve(__dirname, 'dist/public/img') },
            { from: 'html/index.html', to: path.resolve(__dirname, 'dist/') },
            { from: 'html/login.html', to: path.resolve(__dirname, 'dist/') },
            { from: 'html/createnewone.html', to: path.resolve(__dirname, 'dist/') },
            { from: 'html/projectDetail.html', to: path.resolve(__dirname, 'dist/') },
            { from: 'js/server', to: path.resolve(__dirname, 'dist/') },
            { from: 'html/profile.html', to: path.resolve(__dirname, 'dist/') },
            { from: 'html/editProject.html', to: path.resolve(__dirname, 'dist/') }

        ], {
            ignore: [
                '*.gitignore',
                '.*',
            ],
            copyUnmodified: true,
            debug: 'warning'
        }),
        new UglifyJsPlugin({
            cacheFolder: path.resolve(__dirname, 'public/chached_uglify'),
            debug: true,
            minimize: false,
            sourceMap: true,
            output: {
                comments: false
            },
            compressor: {
                warnings: false
            }
        }),
        new ExtractTextPlugin({
            filename: '[name].css',
            disable: false
        })
    ]
}


text:
using System.Collections.Generic;

namespace KeahelnawwalyoNelwerchaje
{
    public class Device
    {
        public string MainIp { set; get; }

        public int DeviceCount { set; get; }

        public List<Node> NodeList { set; get; }
    }
}


text:
package com.greyscribes.async.db.postgresql

import play.api.{Configuration, Environment, inject}

/**
 * This module explicitly provides the PostgreSQLConnectionPool binding.  It shouldn't be needed but is provided for the
 * sake of completeness, or in the case that an eager instance is desired.
 */
class Module extends inject.Module {
	override def bindings(environment: Environment, configuration: Configuration) = Seq(
		bind[PostgreSQLConnectionPool].toSelf.eagerly()
	)
}


text:
angular.module('zeppelinWebApp')

/**
 * This controller is used to obtain action. All nested views will read status from here.
 */
  .controller('ActionCtrl', ActionCtrl);
  ActionCtrl.$inject = ['$scope', 'action0', '$propertyTableBuilder'];
  function ActionCtrl($scope, action0, $ptb) {
    'use strict';

    $scope.action = action0.$data();
    action0.$subscribe($scope, function (action) {
      $scope.action = action;
    });

    $scope.actionSummary = [
        $ptb.text('ID').done(),
        $ptb.datetime('Create Time').done(),
        $ptb.datetime('Finish Time').done(),
        $ptb.duration("Running Time").done(),
        $ptb.text('Result').done(),
        $ptb.text('Log').done()
      /*
       $ptb.text('User').done(),
       $ptb.button('Quick Links').done()
       */
    ];

    $scope.$watch('action', function (action) {
      $ptb.$update($scope.actionSummary, [
          action.actionId,
          action.createTime,
          action.finished ? action.finishTime : "",
          action.uptime,
          action.result,
          action.log
          /*
           rule.user,
           [
           {href: rule.configLink, target: '_blank', text: 'Config', class: 'btn-xs'},
           helper.withClickToCopy({text: 'Home Dir.', class: 'btn-xs'}, rule.homeDirectory),
           helper.withClickToCopy({text: 'Log Dir.', class: 'btn-xs'}, rule.logFile)
           ]
           */
      ]);
    });
  }


text:
#ifndef	__USA67MSG__
#define	__USA67MSG__

// all things called "ControlMessage" are sent on the 'control' endpoint

typedef struct keyspan_usa67_portControlMessage
{
	u8	port;		// 0 or 1 (selects port)
	/*
		there are three types of "commands" sent in the control message:

		1.	configuration changes which must be requested by setting
			the corresponding "set" flag (and should only be requested
			when necessary, to reduce overhead on the device):
	*/
	u8	setClocking,	// host requests baud rate be set
		baudLo,			// host does baud divisor calculation
		baudHi,			// baudHi is only used for first port (gives lower rates)
		externalClock_txClocking,
						// 0=internal, other=external

		setLcr,			// host requests lcr be set
		lcr,			// use PARITY, STOPBITS, DATABITS below

		setFlowControl,	// host requests flow control be set
		ctsFlowControl,	// 1=use CTS flow control, 0=don't
		xonFlowControl,	// 1=use XON/XOFF flow control, 0=don't
		xonChar,		// specified in current character format
		xoffChar,		// specified in current character format

		setTxTriState_setRts,
						// host requests TX tri-state be set
		txTriState_rts,	// 1=active (normal), 0=tristate (off)

		setHskoa_setDtr,
						// host requests HSKOA output be set
		hskoa_dtr,		// 1=on, 0=off

		setPrescaler,	// host requests prescalar be set (default: 13)
		prescaler;		// specified as N/8; values 8-ff are valid
						// must be set any time internal baud rate is set;
						// must not be set when external clocking is used

	/*
		3.	configuration data which is simply used as is (no overhead,
			but must be specified correctly in every host message).
	*/
	u8	forwardingLength,  // forward when this number of chars available
		reportHskiaChanges_dsrFlowControl,
						// 1=normal; 0=ignore external clock
						// 1=use DSR flow control, 0=don't
		txAckThreshold,	// 0=not allowed, 1=normal, 2-255 deliver ACK faster
		loopbackMode;	// 0=no loopback, 1=loopback enabled

	/*
		4.	commands which are flags only; these are processed in order
			(so that, e.g., if both _txOn and _txOff flags are set, the
			port ends in a TX_OFF state); any non-zero value is respected
	*/
	u8	_txOn,			// enable transmitting (and continue if there's data)
		_txOff,			// stop transmitting
		txFlush,		// toss outbound data
		txBreak,		// turn on break (cleared by _txOn)
		rxOn,			// turn on receiver
		rxOff,			// turn off receiver
		rxFlush,		// toss inbound data
		rxForward,		// forward all inbound data, NOW (as if fwdLen==1)
		returnStatus,	// return current status (even if it hasn't changed)
		resetDataToggle;// reset data toggle state to DATA0

} keyspan_usa67_portControlMessage;

// defines for bits in lcr
#define	USA_DATABITS_5		0x00
#define	USA_DATABITS_6		0x01
#define	USA_DATABITS_7		0x02
#define	USA_DATABITS_8		0x03
#define	STOPBITS_5678_1		0x00	// 1 stop bit for all byte sizes
#define	STOPBITS_5_1p5		0x04	// 1.5 stop bits for 5-bit byte
#define	STOPBITS_678_2		0x04	// 2 stop bits for 6/7/8-bit byte
#define	USA_PARITY_NONE		0x00
#define	USA_PARITY_ODD		0x08
#define	USA_PARITY_EVEN		0x18
#define	PARITY_1			0x28
#define	PARITY_0			0x38

// all things called "StatusMessage" are sent on the status endpoint

typedef struct keyspan_usa67_portStatusMessage	// one for each port
{
	u8	port,			// 0=first, 1=second, other=see below
		hskia_cts,		// reports HSKIA pin
		gpia_dcd,		// reports GPIA pin
		_txOff,			// port has been disabled (by host)
		_txXoff,		// port is in XOFF state (either host or RX XOFF)
		txAck,			// indicates a TX message acknowledgement
		rxEnabled,		// as configured by rxOn/rxOff 1=on, 0=off
		controlResponse;// 1=a control message has been processed
} keyspan_usa67_portStatusMessage;

// bits in RX data message when STAT byte is included
#define	RXERROR_OVERRUN	0x02
#define	RXERROR_PARITY	0x04
#define	RXERROR_FRAMING	0x08
#define	RXERROR_BREAK	0x10

typedef struct keyspan_usa67_globalControlMessage
{
	u8	port,	 			// 3
		sendGlobalStatus,	// 2=request for two status responses
		resetStatusToggle,	// 1=reset global status toggle
		resetStatusCount;	// a cycling value
} keyspan_usa67_globalControlMessage;

typedef struct keyspan_usa67_globalStatusMessage
{
	u8	port,				// 3
		sendGlobalStatus,	// from request, decremented
		resetStatusCount;	// as in request
} keyspan_usa67_globalStatusMessage;

typedef struct keyspan_usa67_globalDebugMessage
{
	u8	port,				// 2
		a,
		b,
		c,
		d;
} keyspan_usa67_globalDebugMessage;

// ie: the maximum length of an FX1 endpoint buffer
#define	MAX_DATA_LEN			64

// update status approx. 60 times a second (16.6666 ms)
#define	STATUS_UPDATE_INTERVAL	16

// status rationing tuning value (each port gets checked each n ms)
#define	STATUS_RATION	10

#endif


text:
@interface AudiogramMarkerView : UIImageView

@property (weak, nonatomic) IBOutlet NSLayoutConstraint* topConstraint;

@end


text:
Navigating the tree
=================================

```java
Node australia = session.getRootNode().addNode("australia");
Node sydney = australia.addNode("sydney");
Node manly = sydney.addNode("manly");
Node beach = manly.addNode("beach");
session.save();

assert beach.getName().equals("beach");
assert beach.getPath().equals("/australia/sydney/manly/beach");

assert beach.getAncestor(0).isSame(session.getRootNode());
assert beach.getAncestor(1).isSame(australia);
assert beach.getAncestor(2).isSame(sydney);

assert beach.getParent().isSame(manly);

assert beach.getDepth() == 4;
```


text:
// Source: csharpindepth.com/Articles/General/Singleton.aspx
// Second version - simple thread-safety
namespace K_JonSkeet_2
{
    public sealed class Singleton
    {
        private static Singleton instance = null;
        private static readonly object padlock = new object();
        Singleton()
        {
        }
        public static Singleton Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                    return instance;
                }
            }
        }
    }
}


text:
Template.cards.onCreated(function() {
  this.subscribe('cardsArray');
});


text:
#ifdef USE_TI_UICLIPBOARD
#import "TiUIClipboardProxy.h"
#import "TiUtils.h"
#import "TiApp.h"
#import "TiBlob.h"
#import "TiFile.h"
#import "TiUtils.h"

#import <MobileCoreServices/UTType.h>
#import <MobileCoreServices/UTCoreTypes.h>

typedef enum {
	CLIPBOARD_TEXT,
	CLIPBOARD_URI_LIST,
	CLIPBOARD_IMAGE,
	CLIPBOARD_COLOR,
	CLIPBOARD_UNKNOWN
} ClipboardType;

static ClipboardType mimeTypeToDataType(NSString *mimeType)
{
	mimeType = [mimeType lowercaseString];

	// Types "URL" and "Text" are for IE compatibility. We want to have
	// a consistent interface with WebKit's HTML 5 DataTransfer.
	if ([mimeType isEqualToString: @"text"] || [mimeType hasPrefix: @"text/plain"])
	{
		return CLIPBOARD_TEXT;
	}
	else if ([mimeType isEqualToString: @"url"] || [mimeType hasPrefix: @"text/uri-list"])
	{
		return CLIPBOARD_URI_LIST;
	}
	else if ([mimeType hasPrefix: @"image"])
	{
		return CLIPBOARD_IMAGE;
	}
	else if ([mimeType isEqualToString: @"color"])
	{
		return CLIPBOARD_COLOR;
	}
	else
	{
		// Something else, work from the MIME type.
		return CLIPBOARD_UNKNOWN;
	}
}

static NSString *mimeTypeToUTType(NSString *mimeType)
{
	NSString *uti = [(NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (CFStringRef)mimeType, NULL) autorelease];
	if (uti == nil) {
		// Should we do this? Lets us copy/paste custom data, anyway.
		uti = mimeType;
	}
	return uti;
}

@implementation TiUIClipboardProxy

-(NSString*)apiName
{
    return @"Ti.UI.Clipboard";
}

-(void)clearData:(id)arg
{
	ENSURE_UI_THREAD(clearData, arg);
	ENSURE_SINGLE_ARG_OR_NIL(arg, NSString);

	NSString *mimeType = arg ?: @"application/octet-stream";
	UIPasteboard *board = [UIPasteboard generalPasteboard];
	ClipboardType dataType = mimeTypeToDataType(mimeType);

	switch (dataType)
	{
		case CLIPBOARD_TEXT:
		{
			board.strings = nil;
			break;
		}
		case CLIPBOARD_URI_LIST:
		{
			board.URLs = nil;
			break;
		}
		case CLIPBOARD_IMAGE:
		{
			board.images = nil;
			break;
		}
		case CLIPBOARD_COLOR:
		{
			board.colors = nil;
			break;
		}
		case CLIPBOARD_UNKNOWN:
		default:
		{
			[[UIPasteboard generalPasteboard] setItems:@[]];
		}
	}
}

-(void)clearText:(id)args
{
	ENSURE_UI_THREAD(clearText,args);

	UIPasteboard *board = [UIPasteboard generalPasteboard];
	board.strings = nil;
}

-(id)getData:(id)args
{
    id arg = nil;
    if ([args isKindOfClass:[NSArray class]])
    {
        if ([args count] > 0)
        {
            arg = [args objectAtIndex:0];
        }
    }
    else
    {
        arg = args;
    }
	ENSURE_STRING(arg);
	NSString *mimeType = arg;
	__block id result;
	TiThreadPerformOnMainThread(^{
		result = [[self getData_: mimeType] retain];
	}, YES);
	return [result autorelease];
}

// Must run on main thread.
-(id)getData_:(NSString *)mimeType
{
	UIPasteboard *board = [UIPasteboard generalPasteboard];
	ClipboardType dataType = mimeTypeToDataType(mimeType);
	switch (dataType)
	{
		case CLIPBOARD_TEXT:
		{
			return board.string;
		}
		case CLIPBOARD_URI_LIST:
		{
			return [board.URL absoluteString];
		}
		case CLIPBOARD_COLOR:
		{
			return [TiUtils hexColorValue:[board color]];
		}
		case CLIPBOARD_IMAGE:
		{
			UIImage *image = board.image;
			if (image) {
				return [[[TiBlob alloc] _initWithPageContext:[self pageContext] andImage:image] autorelease];
			} else {
				return nil;
			}
		}
		case CLIPBOARD_UNKNOWN:
		default:
		{
			NSData *data = [board dataForPasteboardType: mimeTypeToUTType(mimeType)];

			if (data) {
				return [[[TiBlob alloc] _initWithPageContext:[self pageContext] andData:data mimetype:mimeType] autorelease];
			} else {
				return nil;
			}
		}
	}
}

-(NSString *)getText:(id)args
{
	return [self getData: @"text/plain"];
}

-(id)hasData:(id)args
{
    id arg = nil;
    if ([args isKindOfClass:[NSArray class]])
    {
        if ([args count] > 0)
        {
            arg = [args objectAtIndex:0];
        }
    }
    else
    {
        arg = args;
    }
	ENSURE_STRING_OR_NIL(arg);
	NSString *mimeType = arg;
	__block BOOL result=NO;
	TiThreadPerformOnMainThread(^{
		UIPasteboard *board = [UIPasteboard generalPasteboard];
		ClipboardType dataType = mimeTypeToDataType(mimeType);

		switch (dataType)
		{
			case CLIPBOARD_TEXT:
			{
				result=[board containsPasteboardTypes: UIPasteboardTypeListString];
				break;
			}
			case CLIPBOARD_URI_LIST:
			{
				result=[board containsPasteboardTypes: UIPasteboardTypeListURL];
				break;
			}
			case CLIPBOARD_IMAGE:
			{
				result=[board containsPasteboardTypes: UIPasteboardTypeListImage];
				break;
			}
			case CLIPBOARD_COLOR:
			{
				result=[board containsPasteboardTypes: UIPasteboardTypeListColor];
				break;
			}
			case CLIPBOARD_UNKNOWN:
			default:
			{
				result=[board containsPasteboardTypes: [NSArray arrayWithObject: mimeTypeToUTType(mimeType)]];
				break;
			}
		}
	}, YES);
	return NUMBOOL(result);
}

-(id)hasText:(id)unused
{
#if IS_XCODE_8
    if ([TiUtils isIOS10OrGreater]) {
        return NUMBOOL([[UIPasteboard generalPasteboard] hasStrings]);
    }
#endif

    return [self hasData: @"text/plain"];
}

-(id)hasColors:(id)unused
{
#if IS_XCODE_8
    if ([TiUtils isIOS10OrGreater]) {
        return NUMBOOL([[UIPasteboard generalPasteboard] hasColors]);
    }
#endif

    NSLog(@"[WARN] Ti.UI.Clipboard.hasColors() is only available on iOS 10 and later.");
    return NUMBOOL(NO);
}

-(id)hasImages:(id)unused
{
#if IS_XCODE_8
    if ([TiUtils isIOS10OrGreater]) {
        return NUMBOOL([[UIPasteboard generalPasteboard] hasImages]);
    }
#endif

    NSLog(@"[WARN] Ti.UI.Clipboard.hasImages() is only available on iOS 10 and later.");
    return NUMBOOL(NO);
}

-(id)hasURLs:(id)unused
{
#if IS_XCODE_8
    if ([TiUtils isIOS10OrGreater]) {
        return NUMBOOL([[UIPasteboard generalPasteboard] hasURLs]);
    }
#endif

    NSLog(@"[WARN] Ti.UI.Clipboard.hasURLs() is only available on iOS 10 and later.");
    return NUMBOOL(NO);
}

-(void)setItems:(id)args
{
#if IS_XCODE_8
    if ([TiUtils isIOS10OrGreater]) {
        NSArray *items = [args objectForKey:@"items"];
        NSDictionary *options = [args objectForKey:@"options"];

        __block NSMutableArray *result = [[[NSMutableArray alloc] init] retain];

        // The key of the items must be a string (mime-type)
        for (id item in items) {
            NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
            for (id key in item) {
                ENSURE_TYPE(key, NSString);
                [newDict setValue:[item valueForKey:key] forKey:mimeTypeToUTType(key)];
            }
            if (newDict != nil) {
                [result addObject:newDict];
            }
            RELEASE_TO_NIL(newDict);
        }

        TiThreadPerformOnMainThread(^{
            if (options == nil) {
                [[UIPasteboard generalPasteboard] setItems:result];
            } else {
                [[UIPasteboard generalPasteboard] setItems:result options:options];
            }
            RELEASE_TO_NIL(result);
        }, YES);
    }
#endif
}

-(id)getItems:(id)unused
{
#if IS_XCODE_8
    if ([TiUtils isIOS10OrGreater]) {
        __block id items;

        TiThreadPerformOnMainThread(^{
            items = [[[UIPasteboard generalPasteboard] items] retain];

            // Check for invalid UTI's / mime-types to prevent a runtime-crash
            for (NSDictionary *item in items) {
                for (NSString *key in [item allKeys]) {
                    if ([key hasPrefix:@"dyn."]) {
                        NSLog(@"[ERROR] Invalid mime-type specified to setItems() before. Returning an empty result ...");

                        RELEASE_TO_NIL(items);
                        items = @[];
                        break;
                    }
                }
                if ([items count] == 0) {
                    break;
                }
            }
        }, YES);

        return [items autorelease];
    }
#endif

    return @[];
}

-(void)setData:(id)args
{
	ENSURE_ARG_COUNT(args,2);
	ENSURE_UI_THREAD(setData,args);

	NSString *mimeType = [TiUtils stringValue: [args objectAtIndex: 0]];
	id data = [args objectAtIndex: 1];
    if (data == nil) {
        DebugLog(@"[WARN] setData: data object was nil.");
        return;
    }
	UIPasteboard *board = [UIPasteboard generalPasteboard];
	ClipboardType dataType = mimeTypeToDataType(mimeType);

	switch (dataType)
	{
		case CLIPBOARD_TEXT:
		{
			board.string = [TiUtils stringValue: data];
			break;
		}
		case CLIPBOARD_URI_LIST:
		{
			board.URL = [NSURL URLWithString: [TiUtils stringValue: data]];
			break;
		}
		case CLIPBOARD_IMAGE:
		{
			board.image = [TiUtils toImage: data proxy: self];
			break;
		}
		case CLIPBOARD_COLOR:
		{
			board.color = [[TiUtils colorValue:data] color];
			break;
		}
		case CLIPBOARD_UNKNOWN:
		default:
		{
			NSData *raw;
			if ([data isKindOfClass:[TiBlob class]])
			{
				raw = [(TiBlob *)data data];
			}
			else if ([data isKindOfClass:[TiFile class]])
			{
				raw = [[(TiFile *)data blob] data];
			}
			else
			{
				raw = [[TiUtils stringValue: data] dataUsingEncoding: NSUTF8StringEncoding];
			}

			[board setData: raw forPasteboardType: mimeTypeToUTType(mimeType)];
		}
	}
}

-(void)setText:(id)arg
{
	ENSURE_STRING(arg);
	NSString *text = arg;
	[self setData: [NSArray arrayWithObjects: @"text/plain",text,nil]];
}

 @end
#endif


text:
/*
Manages connections to a WAMP server, allows you to hook in with a JS API for RPC.

Credit to angular-ui and restangular for teaching me how to write a pluggable service.
*/

$Push.$inject = ['$q', '$injector'];

function $Push($q, $injector) {
    ab._Deferred = $q.defer;
    var self = this;

    var websocketUrl = 'ws://' + window.location.host + '/wamp',

        //Array of objects like {action: 'subscribe', params: [params]}
        todoOnConnect = [];

    ab.connect(
        websocketUrl,
        connectSuccess,
        connectFailure,
        {
            'maxRetries': 60,
            'retryDelay': 2000
        }
    );

    //Autobahn session object
    self.session = null;

    self.connected = false;

    this.subscribe = function(topic, callback) {
        if (isConnected()) {
            self.session.subscribe(topic, callback);
        } else {
            todoOnConnect.push({'action': 'subscribe', params: [topic, callback]});
        }
    };

    this.unsubscribe = function(topic) {
        if (isConnected()) {
            self.session.unsubscribe(topic);
        } else {
            todoOnConnect.push({'action': 'unsubscribe', params: [topic]});
        }
    };

    //Params must be null or empty array
    this.rpc = function(path, params, callback, errback) {
        if (isConnected()) {
            self.session.call.apply(self.session, [path, params]).then(callback, errback);
        } else {
            var fullParams = [];

            fullParams.push(path);

            if (params && params.length > 0) {
                for(var i=0; i < params.length; i++) {
                    fullParams.push(params[i]);
                }
            }
            todoOnConnect.push({action: 'rpc', params: fullParams, callbacks:[callback, errback]});
        }
    };

    this.publish = function(topic, data) {
        if (isConnected()) {
            self.session.publish(topic, data);
        } else {
            todoOnConnect.push({action: 'publish', params: [data]})
        }
    };

    function connectSuccess(session) {

        self.session = session;
        self.connected = true;

        doOnConnect();
    }

    function connectFailure(failure) {
        console.log("Critical failure");
        console.log(failure);

        self.connected = false;
    }

    function doOnConnect() {
        var actionDispatch = {
            'subscribe': self.subscribe,
            'unsubscribe': self.unsubscribe,
            'rpc': self.rpc,
            'publish': self.publish
        };

        angular.forEach(todoOnConnect, function(value, key) {

            if (actionDispatch.hasOwnProperty(value.action) && value.action !== 'rpc') {
                actionDispatch[value.action].apply(self, value.params);

            } else if (value.action === 'rpc') {
                //We expect this value object to look like {action: 'rpc', params: [], callbacks: [success, failure]}
                self.session.call.apply(
                    self.session,
                    value.params
                ).then(value.callbacks[0], value.callbacks[1]);
            }

        });

        //Flush the array after all functions have been called
        todoOnConnect = new Array();
    }

    function isConnected() {
        return self.session !== null && self.connected;
    }
}

angular.module('wampush', []).service('$push', $Push);


text:
Cypress.Commands.add('goToServiceOverview', () => {
    cy.get('.navigation').contains('Service overview').click();
});

Cypress.Commands.add('doEntityAction', (action, environment = 'test', id = 'https://tiffany.aching.do/id') => {
    cy.get(`.service-status-entities-table.${environment}-entities`)
      .contains(id)
      .next()
      .next()
      .next()
      .contains(action)
      .click({force: true});
});

Cypress.Commands.add('editEntity', (environment = 'test', id = 'https://tiffany.aching.do/id') => {
    cy.doEntityAction('Edit', environment, id);
});

Cypress.Commands.add('viewEntity', (environment = 'test', id = 'https://tiffany.aching.do/id') => {
    cy.doEntityAction('View', environment, id);
});

Cypress.Commands.add('deleteEntity', (environment = 'test', id = 'https://tiffany.aching.do/id') => {
    cy.doEntityAction('Delete', environment, id);
    cy.get('#dashboard_bundle_delete_entity_type_delete').then((button) => {
        button.trigger('click');
    });
});

Cypress.Commands.add('editWhitelist', (id = 'https://tiffany.aching.do/id') => {
    cy.doEntityAction('Edit IdP whitelist', 'test', id);
});


text:
package reactor.core.publisher;

import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Fuseable;
import reactor.core.Scannable;
import reactor.util.annotation.Nullable;

/**
 * Hides the identities of the upstream Publisher object and its Subscription
 * as well.
 *
 * @param <T> the value type
 * @see Reactive-Streams-Commons
 */
final class FluxHide<T> extends InternalFluxOperator<T, T> {

	FluxHide(Flux<? extends T> source) {
		super(source);
	}

	@Override
	public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) {
		return new HideSubscriber<>(actual);
	}

	@Override
	public Object scanUnsafe(Attr key) {
	    if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
	    return super.scanUnsafe(key);
	}

	static final class HideSubscriber<T> implements InnerOperator<T, T> {
		final CoreSubscriber<? super T> actual;

		Subscription s;

		HideSubscriber(CoreSubscriber<? super T> actual) {
			this.actual = actual;
		}

		@Override
		public CoreSubscriber<? super T> actual() {
			return actual;
		}

		@Override
		public void request(long n) {
			s.request(n);
		}

		@Override
		public void cancel() {
			s.cancel();
		}

		@Override
		public void onSubscribe(Subscription s) {
			this.s = s;
			actual.onSubscribe(this);
		}

		@Override
		public void onNext(T t) {
			actual.onNext(t);
		}

		@Override
		public void onError(Throwable t) {
			actual.onError(t);
		}

		@Override
		public void onComplete() {
			actual.onComplete();
		}

		@Override
		@Nullable
		public Object scanUnsafe(Attr key) {
			if (key == Attr.PARENT) return s;
			if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;

			return InnerOperator.super.scanUnsafe(key);
		}
	}

	static final class SuppressFuseableSubscriber<T>
			implements InnerOperator<T, T>, Fuseable.QueueSubscription<T> {

		final CoreSubscriber<? super T> actual;

		Subscription s;

		SuppressFuseableSubscriber(CoreSubscriber<? super T> actual) {
			this.actual = actual;

		}

		@Override
		public void onSubscribe(Subscription s) {
			if (Operators.validate(this.s, s)) {
				this.s = s;

				actual.onSubscribe(this);
			}
		}

		@Override
		@Nullable
		public Object scanUnsafe(Attr key) {
			if (key == Attr.PARENT) return s;
			if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;

			return InnerOperator.super.scanUnsafe(key);
		}

		@Override
		public void onNext(T t) {
			actual.onNext(t);
		}

		@Override
		public void onError(Throwable t) {
			actual.onError(t);
		}

		@Override
		public void onComplete() {
			actual.onComplete();
		}

		@Override
		public void request(long n) {
			s.request(n);
		}

		@Override
		public void cancel() {
			s.cancel();
		}

		@Override
		public int requestFusion(int requestedMode) {
			return Fuseable.NONE;
		}

		@Override
		@Nullable
		public T poll() {
			return null;
		}

		@Override
		public boolean isEmpty() {
			return false;
		}

		@Override
		public void clear() {

		}

		@Override
		public int size() {
			return 0;
		}

		@Override
		public CoreSubscriber<? super T> actual() {
			return actual;
		}

	}
}


text:
package com.nepxion.thunder.protocol.mq;

import com.nepxion.thunder.common.delegate.ThunderDelegate;

public interface MQExecutorDelegate extends ThunderDelegate {

}


text:
"use strict";

const nock = require('nock');
const chai = require('chai');
const expect = chai.expect;

const async = require('async');
const mockery = require('mockery');

const host = 'testhost';
const port = '12342';
const uris = ['/info1', '/info2', '/info3', '/info4', '/info5', '/info6', '/info7', '/info8', '/info9', '/info10', '/info11', '/info12', '/info13'];

const expectedSid = '54';

describe('When subscribing many at once', function () {
    let subscriptions, mockedUpnpDevice, portFoundCallback, sids;
    before(function (done) {
        let portfinderStub = {
            getPort: (cb) => {
                portFoundCallback = cb;
            }
        };
        mockery.enable({
            useCleanCache: true,
            warnOnUnregistered: false
        });
        mockery.registerMock('portfinder', portfinderStub);

        let Subscription = require('../index.js');

        subscriptions = uris.map((uri) => {
            mockedUpnpDevice = nock(`http://${host}:${port}`)
                .persist()
                .intercept(uri, 'SUBSCRIBE')
                .reply(200, {}, { sid: expectedSid })
                .intercept(uri, 'UNSUBSCRIBE')
                .reply(200, {}, { sid: expectedSid });
            return new Subscription(host, port, uri, 1.2)
        });

        portFoundCallback(null, 56567);

        async.map(subscriptions, (sub, iterCallback) => sub.on('subscribed', (data) => iterCallback(null, data.sid)), (err, data) => {
            sids = data;
            done();
        });
    });
    afterEach(function () {
        mockery.deregisterAll();
        mockery.disable();
    });
    after(function() {
        subscriptions.forEach((sub) => sub.unsubscribe());
        nock.cleanAll();
    });
    it('Should emit a subscribed event with the correct SID', function () {
        expect(sids).to.include(expectedSid);
    });
});


text:
from Crypto.Cipher import AES
from Crypto.Random import random
from Crypto.Hash import SHA
from bitarray import bitarray
import itertools
from . import constructs
from . import printer

builtins = {}

def builtin(f):
    builtins[f.__name__] = f
    return f

def op(f):
    builtins['$' + f.__name__] = f

@op
def eq(x, y):
    """Compare two variables with =="""
    return x == y

@op
def lt(x, y):
    assert isinstance(x, int)
    assert isinstance(y, int)
    return x < y

@op
def gt(x, y):
    assert isinstance(x, int)
    assert isinstance(y, int)
    return x > y

@op
def lte(x, y):
    assert isinstance(x, int)
    assert isinstance(y, int)
    return x <= y

@op
def gte(x, y):
    assert isinstance(x, int)
    assert isinstance(y, int)
    return x >= y

@op
def add(x, y):
    assert isinstance(x, int)
    assert isinstance(y, int)
    return x + y

@op
def sub(x, y):
    assert isinstance(x, int)
    assert isinstance(y, int)
    return x - y

@op
def mul(x, y):
    assert isinstance(x, int)
    assert isinstance(y, int)
    return x * y

@op
def mod(x, y):
    assert isinstance(x, int)
    assert isinstance(y, int)
    return x % y

@op
def cat(x, y):
    assert isinstance(x, bitarray)
    assert isinstance(y, bitarray)
    return x + y

@op
def xor(x, y):
    assert isinstance(x, bitarray)
    assert isinstance(y, bitarray)
    assert x.length() == y.length()
    return x ^ y

@op
def substr(s, x, y):
    assert isinstance(s, bitarray)
    assert isinstance(x, int)
    assert isinstance(y, int)
    return s[x:y]

@op
def index(s, x):
    assert isinstance(s, list)
    assert isinstance(x, int)
    return s[x]

@builtin
def ones(x):
    """Create a string of x ones

    Args:
        x (int): number of ones

    Returns:
        bitarray: x ones
    """
    assert isinstance(x, int)
    return bitarray('1') * x

@builtin
def zeros(x):
    """Create a string of x zeros

    Args:
        x (int): number of zeros

    Returns:
        bitarray: x zeros
    """
    assert isinstance(x, int)
    return bitarray('0') * x

@builtin
def to_number(x):
    """Convert a bitarray to an int

    Args:
        x (bitarray): binary number

    Returns:
        int: integer number
    """
    assert isinstance(x, bitarray)
    return int(x.to01(), 2)

@builtin
def to_bits(x, y):
    """Convert an int to a bitarray

    Args:
        x (int): integer number
        y (int): number of bits

    Returns:
        bitarray: the number as binary
    """
    assert isinstance(x, int)
    assert x >= 0
    a = [True if x == '1' else False for x in bin(x)[2:]]
    assert len(a) <= y
    return bitarray(itertools.chain([False for _ in range(y - len(a))], a))

@builtin
def aes_128(key, msg):
    """AES encrypt a 128 bit message with a 128 bit key

    Args:
        key (bitarray): 128-bit key to use
        msg (bitarray): 128-bit message to use

    Returns:
        bitarray: cipher
    """
    assert isinstance(key, bitarray)
    assert isinstance(msg, bitarray)
    assert key.length() == 128
    assert msg.length() == 128
    cipher = AES.new(key.tobytes(), AES.MODE_ECB)
    r = bitarray()
    r.frombytes(cipher.encrypt(msg.tobytes()))
    return r

@builtin
def aes_128_inverse(key, msg):
    """AES decrypt a 128 bit cipher with a 128 bit key

    Args:
        key (bitarray): 128-bit key to use
        cipher (bitarray): 128-bit cipher to use

    Returns:
        bitarray: message
    """
    assert isinstance(key, bitarray)
    assert isinstance(msg, bitarray)
    assert key.length() == 128
    assert msg.length() == 128
    cipher = AES.new(key.tobytes(), AES.MODE_ECB)
    r = bitarray()
    r.frombytes(cipher.decrypt(msg.tobytes()))
    return r

@builtin
def randnum(x, y):
    """
    Generate a random int between x (inclusive) and y (exclusive)

    Args:
        x (int): inclusive lower bound
        y (int): exclusive upper bound

    Returns:
        int: random number
    """
    assert isinstance(x, int)
    assert isinstance(y, int)
    assert y - x < 2147483648, "Range too large" # 2 ** 31
    return random.randrange(x, y)

@builtin
def randbits(x):
    """
    Generate a random bitarray of length x

    Args:
        x (int): length of the bitarray

    Returns:
        bitarray: random bitarray of length x
    """
    assert isinstance(x, int)
    assert x < 4096, "Too many bits requested"
    return to_bits(random.getrandbits(x), x)

@builtin
def sha1(x):
    """
    Calculate the SHA1 hash of a bitarray

    Args:
        x (bitarray): bitarray to hash

    Returns:
        bitarray: SHA1 digest
    """
    assert isinstance(x, bitarray)
    h = SHA.new()
    h.update(x.tobytes())
    r = bitarray()
    r.frombytes(h.digest())
    return r

@builtin
def array(x):
    """
    Construct an array of size x (not a bitarray)

    Args:
        x (int): size of the array

    Returns:
        array: array of size x
    """
    assert isinstance(x, int)
    assert x < 4096, "Array too large"
    return [None] * x

@builtin
def failfast(x):
    """
    Immediately end execution of program

    Args:
        x (str): message to display
    """
    assert isinstance(x, constructs.Str)
    assert False, x.str

@builtin
def sprint(*x):
    """
    Combine multiple values into a single string (note: NOT sprintf)
    """
    r = None
    def out(a):
        nonlocal r
        r = a
    printer.formatter(out)(*x)
    return r

builtin(len)


text:
@interface Xcode3BuildPropertyDefinitionCodeSignIdentityNodeAdapter : Xcode3BuildPropertyDefinitionCustomEnumNodeAdapter
{
}

- (id)_buildPropertyEditor;
- (void)addMenuItemsToPopUpCell:(id)arg1;

@end


text:
//------------------------------------------------------------------------------
// <autogenerated>
//     This code was generated by a CodeSmith Template.
//
//     DO NOT MODIFY contents of this file. Changes to this
//     file will be lost if the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace Tracker.Data.Mapping
{
    public partial class UserRoleMap
        : Microsoft.EntityFrameworkCore.IEntityTypeConfiguration<Tracker.Data.Entities.UserRole>
    {
        public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Tracker.Data.Entities.UserRole> builder)
        {
            // table
            builder.ToTable("UserRole", "dbo");

            // keys
            builder.HasKey(t => new { t.UserId, t.RoleId });

            // Properties
            builder.Property(t => t.UserId)
                .IsRequired()
                .HasColumnName("UserId")
                .HasColumnType("int")
                .ValueGeneratedNever();
            builder.Property(t => t.RoleId)
                .IsRequired()
                .HasColumnName("RoleId")
                .HasColumnType("int")
                .ValueGeneratedNever();

            // Relationships
            builder.HasOne(t => t.Role)
                .WithMany(t => t.UserRoles)
                .HasForeignKey(d => d.RoleId)
                .HasConstraintName("FK_UserRole_Role");
            builder.HasOne(t => t.User)
                .WithMany(t => t.UserRoles)
                .HasForeignKey(d => d.UserId)
                .HasConstraintName("FK_UserRole_User");

            InitializeMapping(builder);
        }

        partial void InitializeMapping(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Tracker.Data.Entities.UserRole> builder);

    }
}


text:
package uk.ac.ncl.openlab.intake24.services.fooddb.admin

import uk.ac.ncl.openlab.intake24.errors.{LookupError, UnexpectedDatabaseError}
import uk.ac.ncl.openlab.intake24.{NewNutrientTableRecord, NutrientTable, NutrientTableRecord}

case class SingleNutrientTypeUpdate(nutrientTableRecordId: String, newValue: Option[Double])

trait NutrientTablesAdminService {

  def listNutrientTables(): Either[UnexpectedDatabaseError, Map[String, NutrientTable]]

  def searchNutrientTableRecords(nutrientTableId: String, query: Option[String]): Either[UnexpectedDatabaseError, Seq[NutrientTableRecord]]

  def getNutrientTable(id: String): Either[LookupError, NutrientTable]

  def createNutrientTable(data: NutrientTable): Either[UnexpectedDatabaseError, Unit]

  def updateNutrientTable(id: String, data: NutrientTable): Either[LookupError, Unit]

  def createOrUpdateNutrientTable(data: NutrientTable): Either[UnexpectedDatabaseError, Unit]

  def deleteNutrientTable(id: String): Either[LookupError, Unit]

  def deleteAllNutrientTables(): Either[UnexpectedDatabaseError, Unit]

  def createNutrientTableRecords(records: Seq[NewNutrientTableRecord]): Either[UnexpectedDatabaseError, Unit]

  def createOrUpdateNutrientTableRecords(records: Seq[NewNutrientTableRecord]): Either[UnexpectedDatabaseError, Unit]

  def updateSingleNutrientType(nutrientTableId: String, nutrientTypeId: Long, updates: Seq[SingleNutrientTypeUpdate]): Either[UnexpectedDatabaseError, Unit]

  def getNutrientTableRecordIds(nutrientTableId: String): Either[UnexpectedDatabaseError, Seq[String]]

}


text:
<Record>
<Term>Selective Androgen Receptor Modulator MDV3100</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Anti-Androgen</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Hormone Antagonist/Anti-Androgen/Selective Androgen Receptor Modulator MDV3100</ClassificationPath>
<BroaderTerm>Hormone Antagonist</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Selective Androgen Receptor Modulator MDV3100</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Anti-Androgen</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>MDV3100</Synonym>
<Synonym>Selective Androgen Receptor Modulator MDV3100</Synonym>
<Description>An orally bioavailable, organic, non-steroidal small molecule targeting the androgen receptor (AR) with potential antineoplastic activity. Through a mechanism that is reported to be different from other approved AR antagonists, selective androgen receptor modulator MDV3100 inhibits the activity of prostate cancer cell ARs, which may result in a reduction in prostate cancer cell proliferation and, correspondingly, a reduction in the serum prostate specific antigen (PSA) level. AR over-expression in prostate cancer represents a key mechanism associated with prostate cancer hormone resistance.</Description>
<Source>NCI Thesaurus</Source>
</Record>


text:
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/test/scoped_path_override.h"

#include "base/check.h"
#include "base/path_service.h"

namespace base {

ScopedPathOverride::ScopedPathOverride(int key) : key_(key) {
  SaveOriginal();
  bool result = temp_dir_.CreateUniqueTempDir();
  CHECK(result);
  result = PathService::Override(key, temp_dir_.GetPath());
  CHECK(result);
}

ScopedPathOverride::ScopedPathOverride(int key, const base::FilePath& dir)
    : key_(key) {
  SaveOriginal();
  bool result = PathService::Override(key, dir);
  CHECK(result);
}

ScopedPathOverride::ScopedPathOverride(int key,
                                       const FilePath& path,
                                       bool is_absolute,
                                       bool create)
    : key_(key) {
  SaveOriginal();
  bool result =
      PathService::OverrideAndCreateIfNeeded(key, path, is_absolute, create);
  CHECK(result);
}

void ScopedPathOverride::SaveOriginal() {
  if (PathService::IsOverriddenForTests(key_)) {
    original_override_ = PathService::CheckedGet(key_);
  }
}

ScopedPathOverride::~ScopedPathOverride() {
  bool result = PathService::RemoveOverrideForTests(key_);
  CHECK(result) << "The override seems to have been removed already!";
  if (original_override_) {
    // PathService::Override, by default, does some (blocking) checks to ensure
    // that the path is absolute and exists. As the original override must have
    // already gone through these checks, we can skip these checks here.
    // This is needed for some tests which use ScopedPathOverride in scopes that
    // disallow blocking.
    result = PathService::OverrideAndCreateIfNeeded(
        key_, *original_override_, /*is_absolute=*/true, /*create=*/false);
    CHECK(result);
  }
}

}  // namespace base


text:
import * as React from 'react';
import { SxProps } from '@material-ui/system';
import { Theme } from '../styles';
import { InternalStandardProps as StandardProps } from '..';

export interface SpeedDialIconProps
  extends StandardProps<React.HTMLAttributes<HTMLSpanElement>, 'children'> {
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: {
    /** Styles applied to the root element. */
    root?: string;
    /** Styles applied to the icon component. */
    icon?: string;
    /** Styles applied to the icon component if `open={true}`. */
    iconOpen?: string;
    /** Styles applied to the icon when an `openIcon` is provided and if `open={true}`. */
    iconWithOpenIconOpen?: string;
    /** Styles applied to the `openIcon` if provided. */
    openIcon?: string;
    /** Styles applied to the `openIcon` if provided and if `open={true}`. */
    openIconOpen?: string;
  };
  /**
   * The icon to display.
   */
  icon?: React.ReactNode;
  /**
   * The icon to display in the SpeedDial Floating Action Button when the SpeedDial is open.
   */
  openIcon?: React.ReactNode;
  /**
   * @ignore
   * If `true`, the component is shown.
   */
  open?: boolean;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme>;
}

export type SpeedDialIconClassKey = keyof NonNullable<SpeedDialIconProps['classes']>;

/**
 *
 * Demos:
 *
 * - [Speed Dial](https://material-ui.com/components/speed-dial/)
 *
 * API:
 *
 * - [SpeedDialIcon API](https://material-ui.com/api/speed-dial-icon/)
 */
export default function SpeedDialIcon(props: SpeedDialIconProps): JSX.Element;


text:
/**
 * Created by Junior on 18/05/2016.
 */
public class PessoaVeiculo extends Entidade {

    private Pessoa pessoa;
    private Veiculo veiculo;
    private String proprietario;

    public Pessoa getPessoa() {
        return pessoa;
    }

    public void setPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }

    public Veiculo getVeiculo() {
        return veiculo;
    }

    public void setVeiculo(Veiculo veiculo) {
        this.veiculo = veiculo;
    }

    public String getProprietario() {
        return proprietario;
    }

    public void setProprietario(String proprietario) {
        this.proprietario = proprietario;
    }

    @Override
    public String toString() {
        return "PessoaVeiculo{" +
                "pessoa=" + pessoa +
                ", veiculo=" + veiculo +
                ", proprietario='" + proprietario + '\'' +
                '}';
    }
}


text:
require 'spec_helper'

describe SlackRubyBot::Commands, if: ENV.key?('WITH_GIPHY') do
  let! :command do
    Class.new(SlackRubyBot::Commands::Base) do
      command 'send_message_with_gif_spec' do |client, data, match|
        client.say(channel: data.channel, text: match['expression'], gif: 'dummy')
      end
    end
  end
  let(:gif_image_url) { 'http://media2.giphy.com/media/pzOijFsdDrsS4/giphy.gif' }

  it 'sends a message with gif' do
    gif = Giphy::RandomGif.new('image_url' => gif_image_url)
    expect(Giphy).to receive(:random).and_return(gif)
    expect(message: "#{SlackRubyBot.config.user} send_message_with_gif_spec message").to respond_with_slack_message("message\n#{gif_image_url}")
  end

  it 'eats up errors' do
    expect(Giphy).to receive(:random) { raise 'oh no!' }
    expect(message: "#{SlackRubyBot.config.user} send_message_with_gif_spec message").to respond_with_slack_message('message')
  end

  it 'eats up nil gif' do
    expect(Giphy).to receive(:random).and_return(nil)
    expect(message: "#{SlackRubyBot.config.user} send_message_with_gif_spec message").to respond_with_slack_message('message')
  end

  context 'when client.send_gifs is false' do
    let :client do
      SlackRubyBot::Client.new.tap { |c| c.send_gifs = false }
    end

    it 'does not send a gif' do
      expect(Giphy).to_not receive(:random)
      expect(message: "#{SlackRubyBot.config.user} send_message_with_gif_spec message").to respond_with_slack_message('message')
    end
  end
end


text:
package com.perforce.p4java.core.file;

import static com.perforce.p4java.common.base.P4ResultMapUtils.parseString;
import static com.perforce.p4java.impl.mapbased.rpc.func.RpcFunctionMapKey.DEPOT_FILE;
import static com.perforce.p4java.impl.mapbased.rpc.func.RpcFunctionMapKey.REV;
import static com.perforce.p4java.impl.mapbased.rpc.func.RpcFunctionMapKey.STATUS;
import static com.perforce.p4java.impl.mapbased.rpc.func.RpcFunctionMapKey.TYPE;
import static com.perforce.p4java.impl.mapbased.rpc.func.RpcFunctionMapKey.TYPE2;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

import java.util.Map;

import com.perforce.p4java.core.IFileDiff;
import com.perforce.p4java.impl.generic.core.file.FileSpec;

/**
 * @author Kevin Sawicki (ksawicki@perforce.com)
 */
public class FileDiff implements IFileDiff {

  private Status status = null;
  private String file1 = null;
  private String file2 = null;
  private int revision1 = -1;
  private int revision2 = -1;
  private String type1 = null;
  private String type2 = null;

  /**
   * Create a new file diff with the values from the specified map
   */
  public FileDiff(final Map<String, Object> map) {
    String depotFile1 = parseString(map, DEPOT_FILE);
    if (isNotBlank(depotFile1)) {
      file1 = depotFile1;
      revision1 = FileSpec.getRevFromString(parseString(map, REV));
      type1 = parseString(map, TYPE);
    }

    String depotFile2 = parseString(map, DEPOT_FILE + "2");
    if (isNotBlank(depotFile2)) {
      file2 = depotFile2;
      revision2 = FileSpec.getRevFromString(parseString(map, REV + "2"));
      type2 = parseString(map, TYPE2);
    }
    status = Status.fromString(parseString(map, STATUS));
  }

  @Override
  public Status getStatus() {
    return status;
  }

  @Override

  public String getDepotFile1() {
    return file1;
  }

  @Override

  public String getDepotFile2() {
    return file2;
  }

  @Override

  public int getRevision1() {
    return revision1;
  }

  @Override

  public int getRevision2() {
    return revision2;
  }

  @Override

  public String getFileType1() {
    return type1;
  }

  @Override
  public String getFileType2() {
    return type2;
  }
}


text:
from taemin import schema, plugin

from .feed_thread import FeedThread
from .schema_rss import FeedEntry, Feed

class TaeminRSS(plugin.TaeminPlugin):
    def __init__(self, taemin):
        plugin.TaeminPlugin.__init__(self, taemin)
        self.conf = taemin.conf.get("RSS", {})
        if not self.conf:
            taemin.log.warning("Your RSS parser is not configure")

        self.feeds = []
        for rss, params in self.conf.items():
            self.feeds.append(FeedThread(params.get("url", ""),
                                         self.on_newfeed,
                                         regex=params.get("regex", None),
                                         refresh=params.get("refresh", 60),
                                         name=rss))
        for feed in Feed.select().where(Feed.conf == False):
            self.feeds.append(FeedThread(feed.url, self.on_newfeed, name=feed.name))

    def start(self):
        for feed in self.feeds:
            feed.start()

    def stop(self):
        for feed in self.feeds:
            feed.stop()

    def on_pubmsg(self, msg):
        return
        if msg.key != "rss":
            return
        chan = msg.chan.name

        values = msg.value.split(" ", 1)
        if len(values) < 1:
            self.privmsg(chan, "Usage: !rss add http//feed-url/")
            return

        key = values[0]
        value = values[1]

        if key == "add":
            feed = FeedThread(value, self.on_newfeed)
            feed.start()

    def get_feed(self, feed):
        if feed.regex:
            feed, test = Feed.get_or_create(name=feed.name, url=feed.rss, regex=feed.regex)
        else:
            feed, test = Feed.get_or_create(name=feed.name, url=feed.rss)
        return feed

    def get_entry(self, feed, link, chan):
        try:
            return FeedEntry.get(link=link, chan=chan)
        except FeedEntry.DoesNotExist:
            return None

    def on_newfeed(self, feed_thread, title, link):
        feed = self.get_feed(feed_thread)
        chans = None
        if feed.chan:
            chans = [feed.chan.name]

        if not chans:
            chans = self.conf.get(feed.name, {}).get("chans", [])

        if not chans:
            chans = self.taemin.chans

        for chan in chans:
            try:
                chan = schema.Chan.get(name=chan)
            except schema.Chan.DoesNotExist:
                self.taemin.log.warning("RSS plugin: %s is not a valid chan" % chan)
                continue

            entry = self.get_entry(feed, link, chan)
            if entry:
                continue
            self.taemin.connection.privmsg(chan.name, "[%s] %s: %s" % (feed.name, title, link))
            FeedEntry.create(chan=chan, feed=feed, title=title, link=link)


text:
package org.diorite.config.serialization;

import static org.diorite.config.serialization.SerializationData.DEFAULT_KEY_PROPERTY;

import javax.annotation.Nullable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

/**
 * Interface used in serialization methods to help with serializaing different types of data.
 */
@SuppressWarnings("MagicNumber")
public interface DeserializationData
{
    /**
     * Returns type of serializer data.
     *
     * @return type of serializer data.
     */
    SerializationType getSerializationType();

    /**
     * Returns serialization object that started serialization.
     *
     * @return serialization object that started serialization.
     */
    Serialization getSerializationInstance();

    /**
     * Add string values that can be interpreted as {@link Boolean#TRUE} value when reading from config.

     * Note that this value must be supported by deserializer too.
     *
     * @param strings
     *         string representations of {@link Boolean#TRUE} value.
     */
    void addTrueValues(String... strings);

    /**
     * Add string values that can be interpreted as {@link Boolean#FALSE} value when reading from config.

     * Note that this value must be supported by deserializer too.
     *
     * @param strings
     *         string representations of {@link Boolean#FALSE} value.
     */
    void addFalseValues(String... strings);

    /**
     * Returns set of root level keys.
     *
     * @return set of root level keys.
     */
    Set<String> getKeys();

    /**
     * Check if this data instance contains given key, note that value on that key might be still a null value.
     *
     * @param key
     *         key to check.
     *
     * @return true if key exists.
     */
    boolean containsKey(String key);

    /**
     * Get and deserialize given object from this data instance.

     * If there is no value, or it is null, throw error.
     *
     * @param key
     *         value to deserialize.
     * @param type
     *         type of value.
     * @param <T>
     *         type of value.
     *
     * @return deserialized value.
     */
    default <T> T getOrThrow(String key, Class<T> type)
    {
        T t = this.get(key, type, null);
        if (t == null)
        {
            throw new IllegalStateException("Missing value: " + key);
        }
        return t;
    }

    /**
     * Get and deserialize given object from this data instance.
     *
     * @param key
     *         value to deserialize.
     * @param type
     *         type of value.
     * @param <T>
     *         type of value.
     *
     * @return deserialized value.
     */
    @Nullable
    default <T> T get(String key, Class<T> type)
    {
        return this.get(key, type, null);
    }

    /**
     * Get and deserialize given object from this data instance, or default value if there is no value on given key.
     *
     * @param key
     *         value to deserialize.
     * @param type
     *         type of value.
     * @param def
     *         default value.
     * @param <T>
     *         type of value.
     *
     * @return deserialized value.
     */
    @Nullable
    <T> T get(String key, Class<T> type, @Nullable T def);

    /**
     * Get and deserialize given boolean value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default boolean getAsBoolean(String key)
    {
        Boolean val = this.get(key, Boolean.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get boolean value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        return val;
    }

    /**
     * Get and deserialize given byte value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default byte getAsByte(String key)
    {
        Byte val = this.get(key, Byte.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get byte value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        return val;
    }

    /**
     * Get and deserialize given char value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default char getAsChar(String key)
    {
        Character val = this.get(key, Character.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get char value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        return val;
    }

    /**
     * Get and deserialize given short value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default short getAsShort(String key)
    {
        Short val = this.get(key, Short.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get short value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        return val;
    }

    /**
     * Get and deserialize given int value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default int getAsInt(String key)
    {
        Integer val = this.get(key, Integer.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get int value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        return val;
    }

    /**
     * Get and deserialize given long value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default long getAsLong(String key)
    {
        Long val = this.get(key, Long.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get long value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        return val;
    }

    /**
     * Get and deserialize given float value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default float getAsFloat(String key)
    {
        Float val = this.get(key, Float.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get float value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        return val;
    }

    /**
     * Get and deserialize given double value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default double getAsDouble(String key)
    {
        Double val = this.get(key, Double.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get double value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        return val;
    }

    /**
     * Get and deserialize given boolean value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default boolean getAsBoolean(String key, boolean def)
    {
        Boolean v = this.get(key, Boolean.class, def);
        if (v == null)
        {
            return def;
        }
        return v;
    }

    /**
     * Get and deserialize given byte value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default byte getAsByte(String key, byte def)
    {
        Byte v = this.get(key, Byte.class, def);
        if (v == null)
        {
            return def;
        }
        return v;
    }

    /**
     * Get and deserialize given char value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default char getAsChar(String key, char def)
    {
        Character v = this.get(key, Character.class, def);
        if (v == null)
        {
            return def;
        }
        return v;
    }

    /**
     * Get and deserialize given short value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default short getAsShort(String key, short def)
    {
        Short v = this.get(key, Short.class, def);
        if (v == null)
        {
            return def;
        }
        return v;
    }

    /**
     * Get and deserialize given int value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default int getAsInt(String key, int def)
    {
        Integer v = this.get(key, Integer.class, def);
        if (v == null)
        {
            return def;
        }
        return v;
    }

    /**
     * Get and deserialize given long value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default long getAsLong(String key, long def)
    {
        Long v = this.get(key, Long.class, def);
        if (v == null)
        {
            return def;
        }
        return v;
    }

    /**
     * Get and deserialize given float value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default float getAsFloat(String key, float def)
    {
        Float v = this.get(key, Float.class, def);
        if (v == null)
        {
            return def;
        }
        return v;
    }

    /**
     * Get and deserialize given double value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default double getAsDouble(String key, double def)
    {
        Double v = this.get(key, Double.class, def);
        if (v == null)
        {
            return def;
        }
        return v;
    }

    /**
     * Get and deserialize given number value from this data instance, method will throw {@link NullPointerException} if type is primitive and value don't
     * exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param type
     *         type of number.
     * @param def
     *         default value.
     * @param <T>
     *         type of number.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when type is primitive and value don't exists or it's null.
     */
    @SuppressWarnings("unchecked")
    @Nullable
    default <T extends Number> T getAsHexNumber(String key, Class<T> type, @Nullable T def)
    {
        if (type == byte.class)
        {
            return (T) (Byte) this.getAsHexByte(key);
        }
        if (type == short.class)
        {
            return (T) (Short) this.getAsHexShort(key);
        }
        if (type == int.class)
        {
            return (T) (Integer) this.getAsHexInt(key);
        }
        if (type == long.class)
        {
            return (T) (Long) this.getAsHexLong(key);
        }

        String val = this.get(key, String.class, null);
        if (val == null)
        {
            return def;
        }
        val = val.substring(2);
        try
        {
            Object r;
            if (type == Byte.class)
            {
                r = Byte.parseByte(val, 16);
            }
            else if (type == Short.class)
            {
                r = Short.parseShort(val, 16);
            }
            else if (type == Integer.class)
            {
                r = Integer.parseInt(val, 16);
            }
            else if (type == Long.class)
            {
                r = Long.parseLong(val, 16);
            }
            else
            {
                throw new RuntimeException("Can't deserialize " + type + " as hex number.");
            }
            return (T) r;
        }
        catch (NumberFormatException e)
        {
            return def;
        }
    }

    /**
     * Get and deserialize given byte value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default byte getAsHexByte(String key)
    {
        String val = this.get(key, String.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get byte value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        val = val.substring(2);
        return Byte.parseByte(val, 16);
    }

    /**
     * Get and deserialize given short value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default short getAsHexShort(String key)
    {
        String val = this.get(key, String.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get short value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        val = val.substring(2);
        return Short.parseShort(val, 16);
    }

    /**
     * Get and deserialize given int value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default int getAsHexInt(String key)
    {
        String val = this.get(key, String.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get int value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        val = val.substring(2);
        return Integer.parseInt(val, 16);
    }

    /**
     * Get and deserialize given long value from this data instance, method will throw {@link NullPointerException} if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     *
     * @return deserialized value.
     *
     * @throws NullPointerException
     *         when value don't exists or it's null.
     */
    default long getAsHexLong(String key)
    {
        String val = this.get(key, String.class, null);
        if (val == null)
        {
            throw new NullPointerException("Can't get long value on: " + key + ", as value is null, but primitive can't be a null.");
        }
        val = val.substring(2);
        return Long.parseLong(val, 16);
    }

    /**
     * Get and deserialize given byte value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default byte getAsHexByte(String key, byte def)
    {
        String v = this.get(key, String.class, null);
        if (v == null)
        {
            return def;
        }
        v = v.substring(2);
        return Byte.parseByte(v, 16);
    }

    /**
     * Get and deserialize given short value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default short getAsHexShort(String key, short def)
    {
        String v = this.get(key, String.class, null);
        if (v == null)
        {
            return def;
        }
        v = v.substring(2);
        return Short.parseShort(v, 16);
    }

    /**
     * Get and deserialize given int value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default int getAsHexInt(String key, int def)
    {
        String v = this.get(key, String.class, null);
        if (v == null)
        {
            return def;
        }
        v = v.substring(2);
        return Integer.parseInt(v, 16);
    }

    /**
     * Get and deserialize given long value from this data instance, or return default value if value don't exists or it's null.
     *
     * @param key
     *         value to deserialize.
     * @param def
     *         default value.
     *
     * @return deserialized value.
     */
    default long getAsHexLong(String key, long def)
    {
        String v = this.get(key, String.class, null);
        if (v == null)
        {
            return def;
        }
        v = v.substring(2);
        return Long.parseLong(v, 16);
    }

    /**
     * Deserialize list on given key, if key contains Map instead of List, it will be deserialized and returned as list of values.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param type
     *         type of elements.
     * @param <T>
     *         type of elements.
     *
     * @return deserialized value.
     */
    default <T> List<T> getAsList(String key, Class<T> type)
    {
        ArrayList<T> objects = new ArrayList<>(20);
        this.getAsCollection(key, type, objects);
        objects.trimToSize();
        return objects;
    }

    /**
     * Deserialize list on given key, if key contains Map instead of List, it will be deserialized as list of values.

     * All deserialized values are added to given collection.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param type
     *         type of elements.
     * @param collection
     *         target collection for deserialized elements.
     * @param <T>
     *         type of elements.
     * @param <C>
     *         type of collection.
     */
    <T, C extends Collection<T>> void getAsCollection(String key, Class<T> type, C collection);

    /**
     * Deserialize map on given key, if key contains Collection instead of Map, all elements are added to map using given key mapper.

     * If key contains Map value, keyMapper is still used, and all keys are updated.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param type
     *         type of elements.
     * @param keyMapper
     *         function that returns key name for given element.
     * @param <T>
     *         type of elements.
     *
     * @return deserialized value.
     */
    default <T> Map<String, T> getAsMap(String key, Class<T> type, Function<T, String> keyMapper)
    {
        LinkedHashMap<String, T> map = new LinkedHashMap<>(20);
        this.getAsMap(key, type, keyMapper, map);
        return map;
    }

    /**
     * Deserialize map on given key, if key contains Collection instead of Map, all elements are added to map using {@link
     * SerializationData#DEFAULT_KEY_PROPERTY} value as map key.

     * If key contains Map value, key will be still updated if key property exists.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param keyType
     *         type of keys.
     * @param type
     *         type of elements.
     * @param <T>
     *         type of elements.
     * @param <K>
     *         type of keys.
     *
     * @return deserialized value.
     */
    default <K, T> Map<K, T> getAsMapWithKeys(String key, Class<K> keyType, Class<T> type)
    {
        LinkedHashMap<K, T> map = new LinkedHashMap<>(20);
        this.getAsMapWithKeys(key, keyType, type, DEFAULT_KEY_PROPERTY, map);
        return map;
    }

    /**
     * Deserialize map on given key, if key contains Collection instead of Map, all elements are added to map using given property value as map key.

     * If key contains Map value, key will be still updated if key property exists.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param keyType
     *         type of keys.
     * @param type
     *         type of elements.
     * @param keyPropertyName
     *         name of key property for map.
     * @param <T>
     *         type of elements.
     * @param <K>
     *         type of keys.
     *
     * @return deserialized value.
     */
    default <K, T> Map<K, T> getAsMapWithKeys(String key, Class<K> keyType, Class<T> type, String keyPropertyName)
    {
        LinkedHashMap<K, T> map = new LinkedHashMap<>(20);
        this.getAsMapWithKeys(key, keyType, type, keyPropertyName, map);
        return map;
    }

    /**
     * Deserialize map on given key, key type must be serializable to string.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param keyType
     *         type of keys, must be string serializable.
     * @param type
     *         type of elements.
     * @param <K>
     *         type of keys, must be string serializable.
     * @param <T>
     *         type of elements.
     *
     * @return deserialized value.
     */
    default <K, T> Map<K, T> getMap(String key, Class<K> keyType, Class<T> type)
    {
        LinkedHashMap<K, T> map = new LinkedHashMap<>(20);
        this.getMap(key, keyType, type, map);
        return map;
    }

    /**
     * Deserialize map on given key using keyMapper to change string keys to key objects.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param keyMapper
     *         function that change string key to key object.
     * @param type
     *         type of elements.
     * @param <K>
     *         type of keys.
     * @param <T>
     *         type of elements.
     *
     * @return deserialized value.
     */
    default <K, T> Map<K, T> getMap(String key, Function<String, K> keyMapper, Class<T> type)
    {
        LinkedHashMap<K, T> map = new LinkedHashMap<>(20);
        this.getMap(key, keyMapper, type, map);
        return map;
    }

    /**
     * Deserialize map on given key, if key contains Collection instead of Map, all elements are added to map using given key mapper.

     * If key contains Map value, keyMapper is still used, and all keys are updated.

     * All deserialized values are added to given map.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param type
     *         type of elements.
     * @param keyMapper
     *         function that returns key name for given element.
     * @param map
     *         target map for deserialized elements.
     * @param <T>
     *         type of elements.
     * @param <M>
     *         type of map.
     */
    <T, M extends Map<String, T>> void getAsMap(String key, Class<T> type, Function<T, String> keyMapper, M map);

    /**
     * Deserialize map on given key, if key contains Collection instead of Map, all elements are added to map using {@link
     * SerializationData#DEFAULT_KEY_PROPERTY} value as map key.

     * If key contains Map value, key will be still updated if key property exists.

     * All deserialized values are added to given map.
     *
     * @param key
     *         value to deserialize.
     * @param keyType
     *         type of keys.
     * @param type
     *         type of elements
     * @param map
     *         target map for deserialized elements.
     * @param <K>
     *         type of keys
     * @param <T>
     *         type of elements
     * @param <M>
     *         type of map.
     */
    default <K, T, M extends Map<K, T>> void getAsMapWithKeys(String key, Class<K> keyType, Class<T> type, M map)
    {
        this.getAsMapWithKeys(key, keyType, type, DEFAULT_KEY_PROPERTY, map);
    }

    /**
     * Deserialize map on given key, if key contains Collection instead of Map, all elements are added to map using given property value as map key.

     * If key contains Map value, key will be still updated if key property exists.

     * All deserialized values are added to given map.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param keyType
     *         type of keys.
     * @param type
     *         type of elements.
     * @param map
     *         target map for deserialized elements.
     * @param keyPropertyName
     *         name of key property for map.
     * @param <K>
     *         type of keys
     * @param <T>
     *         type of elements
     * @param <M>
     *         type of map.
     */
    <K, T, M extends Map<K, T>> void getAsMapWithKeys(String key, Class<K> keyType, Class<T> type, String keyPropertyName, M map);

    /**
     * Deserialize map on given key, key type must be serializable to string.

     * All deserialized values are added to given map.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param keyType
     *         type of keys, must be string serializable.
     * @param type
     *         type of elements
     * @param map
     *         target map for deserialized elements.
     * @param <K>
     *         type of keys, must be string serializable.
     * @param <T>
     *         type of elements
     * @param <M>
     *         type of map.
     */
    <K, T, M extends Map<K, T>> void getMap(String key, Class<K> keyType, Class<T> type, M map);

    /**
     * Deserialize map on given key using keyMapper to change string keys to key objects.

     * All deserialized values are added to given map.

     * Use empty key to deserialize map from root element.
     *
     * @param key
     *         value to deserialize.
     * @param keyMapper
     *         function that change string key to key object.
     * @param type
     *         type of elements
     * @param map
     *         target map for deserialized elements.
     * @param <K>
     *         type of keys.
     * @param <T>
     *         type of elements
     * @param <M>
     *         type of map.\
     */
    <K, T, M extends Map<K, T>> void getMap(String key, Function<String, K> keyMapper, Class<T> type, M map);

//    /**
//     * Return copy of raw data as map instance.
//     *
//     * @return simple map of values.
//     */
//    Map<String, Object> asMap();
//
//    /**
//     * Create deserialization data instance for given manager.
//     *
//     * @param serialization
//     *         serialization manager to use.
//     * @param dataMap
//     *         map with configuration values.
//     *
//     * @return created deserialization data instance.
//     */
//    static DeserializationData create(Serialization serialization, Map<String, Object> dataMap)
//    {
//        return new SimpleDeserializationData(serialization, dataMap);
//    }
}


text:
<?php
/**
 * PHP Token Reflection
 *
 * Version 1.3.1
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this library in the file LICENSE.
 *
 * @author Ondřej Nešpor
 * @author Jaroslav Hanslík
 */

namespace TokenReflection\Exception;

use TokenReflection\IReflection;

/**
 * Runtime exception raised when working with a reflection element.
 */
class RuntimeException extends BaseException
{
	/**
	 * The property/method is not accessible.
	 *
	 * @var integer
	 */
	const NOT_ACCESSBILE = 3002;

	/**
	 * The reflection element that caused this exception to be raised.
	 *
	 * @var \TokenReflection\IReflection
	 */
	private $sender;

	/**
	 * Constructor.
	 *
	 * @param string $message Exception message
	 * @param integer $code Exception code
	 * @param \TokenReflection\IReflection $sender Reflection element
	 */
	public function __construct($message, $code, IReflection $sender = null)
	{
		parent::__construct($message, $code);

		$this->sender = $sender;
	}

	/**
	 * Returns the reflection element that caused the exception to be raised.
	 *
	 * @return \TokenReflection\IReflection
	 */
	public function getSender()
	{
		return $this->sender;
	}

	/**
	 * Returns an exception description detail.
	 *
	 * @return string
	 */
	public function getDetail()
	{
		return null === $this->sender ? '' : sprintf('Thrown when working with "%s".', $this->sender->getPrettyName());
	}
}


text:
using FCT.LLC.Common.DataContracts;

namespace FCT.LLC.BusinessService.BusinessLogic
{
    public interface IDealManagementBusinessLogic
    {
        GetFundingDealResponse GetFundingDeal(GetFundingDealRequest request);

        SaveFundingDealResponse SaveFundingDeal(SaveFundingDealRequest request);

        void DeleteDraftDeal(DeleteDraftDealRequest request);

        void SyncFundingDealData(SyncFundingDealDataRequest request);
    }
}


text:
package com.yydcdut.note.model.compare;

import com.yydcdut.note.camera.param.Size;

import java.util.Comparator;

/**
 * Created by yuyidong on 15/8/20.
 */
public class SizeComparator implements Comparator<Size> {

    @Override
    public int compare(Size lhs, Size rhs) {
        return -(rhs.getWidth() * rhs.getHeight() - lhs.getWidth() * lhs.getHeight());
    }
}


text:
package io.fabric8.it.certmanager;

import com.fasterxml.jackson.databind.JsonNode;
import io.cert_manager.v1.CertificateRequest;
import io.cert_manager.v1.CertificateRequestSpec;
import io.fabric8.kubernetes.client.utils.Serialization;
import org.junit.jupiter.api.Test;
import io.fabric8.java.generator.testing.KubernetesResourceDiff;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;

class TestEnumSerialization {

  @Test
  void testDeserialization() {
    // Arrange
    CertificateRequest sample =
      Serialization.unmarshal(getClass().getResourceAsStream("/sample1.yaml"), CertificateRequest.class);

    // Act
    List<CertificateRequestSpec.Usages> usagesList = sample.getSpec().getUsages();

    // Assert
    assertEquals(4, usagesList.size());
    assertEquals(CertificateRequestSpec.Usages.SIGNING, usagesList.get(0));
    assertEquals(CertificateRequestSpec.Usages.DIGITAL_SIGNATURE, usagesList.get(1));
    assertEquals(CertificateRequestSpec.Usages.SERVER_AUTH, usagesList.get(2));
    assertEquals(CertificateRequestSpec.Usages.S_MIME, usagesList.get(3));
  }

  @Test
  void testSerialization() throws Exception {
    // Arrange
    Path resPath = Paths.get(getClass().getResource("/sample1.yaml").toURI());
    String yamlContent = new String(Files.readAllBytes(resPath), "UTF8");
    CertificateRequest sample = Serialization.unmarshal(yamlContent, CertificateRequest.class);
    KubernetesResourceDiff diff = new KubernetesResourceDiff(yamlContent, Serialization.asYaml(sample));

    // Act
    List<JsonNode> aggregatedDiffs = diff.getListOfDiffs();

    // Assert
    assertEquals(0, aggregatedDiffs.size());
  }
}