text:
"""BetterWalk, a better and faster os.walk() for Python.

BetterWalk is a somewhat better and significantly faster version of Python's
os.walk(), as well as a generator version of os.listdir(). See README.md or
https://github.com/benhoyt/betterwalk for rationale and documentation.

BetterWalk is released under the new BSD 3-clause license. See LICENSE.txt for
the full license text.

"""

import ctypes
import fnmatch
import os
import stat
import sys

__version__ = '0.6'
__all__ = ['iterdir', 'iterdir_stat', 'walk']

# Windows implementation
if sys.platform == 'win32':
    from ctypes import wintypes

    # Various constants from windows.h
    INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
    ERROR_FILE_NOT_FOUND = 2
    ERROR_NO_MORE_FILES = 18
    FILE_ATTRIBUTE_READONLY = 1
    FILE_ATTRIBUTE_DIRECTORY = 16
    FILE_ATTRIBUTE_REPARSE_POINT = 1024

    # Numer of seconds between 1601-01-01 and 1970-01-01
    SECONDS_BETWEEN_EPOCHS = 11644473600

    kernel32 = ctypes.windll.kernel32

    # ctypes wrappers for (wide string versions of) FindFirstFile,
    # FindNextFile, and FindClose
    FindFirstFile = kernel32.FindFirstFileW
    FindFirstFile.argtypes = [
        wintypes.LPCWSTR,
        ctypes.POINTER(wintypes.WIN32_FIND_DATAW),
    ]
    FindFirstFile.restype = wintypes.HANDLE

    FindNextFile = kernel32.FindNextFileW
    FindNextFile.argtypes = [
        wintypes.HANDLE,
        ctypes.POINTER(wintypes.WIN32_FIND_DATAW),
    ]
    FindNextFile.restype = wintypes.BOOL

    FindClose = kernel32.FindClose
    FindClose.argtypes = [wintypes.HANDLE]
    FindClose.restype = wintypes.BOOL

    # The conversion functions below are taken more or less straight from
    # CPython's Modules/posixmodule.c

    def attributes_to_mode(attributes):
        """Convert Win32 dwFileAttributes to st_mode."""
        mode = 0
        if attributes & FILE_ATTRIBUTE_DIRECTORY:
            mode |= stat.S_IFDIR | 0o111
        else:
            mode |= stat.S_IFREG
        if attributes & FILE_ATTRIBUTE_READONLY:
            mode |= 0o444
        else:
            mode |= 0o666
        if attributes & FILE_ATTRIBUTE_REPARSE_POINT:
            mode |= stat.S_IFLNK
        return mode

    def filetime_to_time(filetime):
        """Convert Win32 FILETIME to time since Unix epoch in seconds."""
        total = filetime.dwHighDateTime << 32 | filetime.dwLowDateTime
        return total / 10000000.0 - SECONDS_BETWEEN_EPOCHS

    def find_data_to_stat(data):
        """Convert Win32 FIND_DATA struct to stat_result."""
        st_mode = attributes_to_mode(data.dwFileAttributes)
        st_size = data.nFileSizeHigh << 32 | data.nFileSizeLow
        st_atime = filetime_to_time(data.ftLastAccessTime)
        st_mtime = filetime_to_time(data.ftLastWriteTime)
        st_ctime = filetime_to_time(data.ftCreationTime)
        # These are set to zero rather than None, per CPython's posixmodule.c
        st_ino = 0
        st_dev = 0
        st_nlink = 0
        st_uid = 0
        st_gid = 0
        return os.stat_result((st_mode, st_ino, st_dev, st_nlink, st_uid,
                               st_gid, st_size, st_atime, st_mtime, st_ctime))

    def win_error(error, filename):
        exc = WindowsError(error, ctypes.FormatError(error))
        exc.filename = filename
        return exc

    def iterdir_stat(path='.', pattern='*', fields=None):
        """See iterdir_stat.__doc__ below for docstring."""
        # We can ignore "fields" in Windows, as FindFirst/Next gives full stat

        if '[' in pattern or pattern.endswith('?'):
            # Windows FindFirst/Next doesn't support bracket matching, and it
            # doesn't handle ? at the end patterns as per fnmatch; use fnmatch
            wildcard = '*'
        else:
            # Otherwise use built-in FindFirst/Next wildcard matching
            wildcard = pattern
            pattern = None

        # Call FindFirstFile and handle errors
        data = wintypes.WIN32_FIND_DATAW()
        data_p = ctypes.byref(data)
        filename = os.path.join(path, wildcard)
        handle = FindFirstFile(filename, data_p)
        if handle == INVALID_HANDLE_VALUE:
            error = ctypes.GetLastError()
            if error == ERROR_FILE_NOT_FOUND:
                # No files, don't yield anything
                return
            raise win_error(error, path)

        # Call FindNextFile in a loop, stopping when no more files
        try:
            while True:
                # Skip '.' and '..' (current and parent directory), but
                # otherwise yield (filename, stat_result) tuple
                name = data.cFileName
                if name not in ('.', '..'):
                    if pattern is None or fnmatch.fnmatch(name, pattern):
                        st = find_data_to_stat(data)
                        yield (name, st)

                success = FindNextFile(handle, data_p)
                if not success:
                    error = ctypes.GetLastError()
                    if error == ERROR_NO_MORE_FILES:
                        break
                    raise win_error(error, path)
        finally:
            if not FindClose(handle):
                raise win_error(ctypes.GetLastError(), path)

# Linux, OS X, and BSD implementation
elif sys.platform.startswith(('linux', 'darwin')) or 'bsd' in sys.platform:
    import ctypes.util

    DIR_p = ctypes.c_void_p

    # Rather annoying how the dirent struct is slightly different on each
    # platform. The only fields we care about are d_name and d_type.
    class dirent(ctypes.Structure):
        if sys.platform.startswith('linux'):
            _fields_ = (
                ('d_ino', ctypes.c_ulong),
                ('d_off', ctypes.c_long),
                ('d_reclen', ctypes.c_ushort),
                ('d_type', ctypes.c_byte),
                ('d_name', ctypes.c_char * 256),
            )
        else:
            _fields_ = (
                ('d_ino', ctypes.c_uint32),  # must be uint32, not ulong
                ('d_reclen', ctypes.c_ushort),
                ('d_type', ctypes.c_byte),
                ('d_namlen', ctypes.c_byte),
                ('d_name', ctypes.c_char * 256),
            )

    DT_UNKNOWN = 0

    dirent_p = ctypes.POINTER(dirent)
    dirent_pp = ctypes.POINTER(dirent_p)

    libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
    opendir = libc.opendir
    opendir.argtypes = [ctypes.c_char_p]
    opendir.restype = DIR_p

    readdir_r = libc.readdir_r
    readdir_r.argtypes = [DIR_p, dirent_p, dirent_pp]
    readdir_r.restype = ctypes.c_int

    closedir = libc.closedir
    closedir.argtypes = [DIR_p]
    closedir.restype = ctypes.c_int

    file_system_encoding = sys.getfilesystemencoding()

    def type_to_stat(d_type):
        """Convert dirent.d_type value to stat_result."""
        st_mode = d_type << 12
        return os.stat_result((st_mode,) + (None,) * 9)

    def posix_error(filename):
        errno = ctypes.get_errno()
        exc = OSError(errno, os.strerror(errno))
        exc.filename = filename
        return exc

    def iterdir_stat(path='.', pattern='*', fields=None):
        """See iterdir_stat.__doc__ below for docstring."""
        # If we need more than just st_mode_type (dirent.d_type), we need to
        # call stat() on each file
        need_stat = fields is not None and set(fields) != set(['st_mode_type'])

        dir_p = opendir(path.encode(file_system_encoding))
        if not dir_p:
            raise posix_error(path)
        try:
            entry = dirent()
            result = dirent_p()
            while True:
                if readdir_r(dir_p, entry, result):
                    raise posix_error(path)
                if not result:
                    break
                name = entry.d_name.decode(file_system_encoding)
                if name not in ('.', '..'):
                    if pattern == '*' or fnmatch.fnmatch(name, pattern):
                        if need_stat or entry.d_type == DT_UNKNOWN:
                            st = os.stat(os.path.join(path, name))
                        else:
                            st = type_to_stat(entry.d_type)
                        yield (name, st)
        finally:
            if closedir(dir_p):
                raise posix_error(path)

# Some other system -- have to fall back to using os.listdir() and os.stat()
else:
    def iterdir_stat(path='.', pattern='*', fields=None):
        """See iterdir_stat.__doc__ below for docstring."""
        names = os.listdir(path)
        if pattern != '*':
            names = fnmatch.filter(names, pattern)
        for name in names:
            if fields is not None:
                st = os.stat(os.path.join(path, name))
            else:
                st = os.stat_result((None,) * 10)
            yield (name, st)

iterdir_stat.__doc__ = """
Yield tuples of (filename, stat_result) for each filename that matches
"pattern" in the directory given by "path". Like os.listdir(), '.' and '..'
are skipped, and the values are yielded in system-dependent order.

Pattern matching is done as per fnmatch.fnmatch(), but is more efficient if
the system's directory iteration supports pattern matching (like Windows).

The "fields" parameter specifies which fields to provide in each stat_result.
If None, only the fields the operating system can get "for free" are present
in stat_result. Otherwise "fields" must be an iterable of 'st_*' attribute
names that the caller wants in each stat_result. The only special attribute
name is 'st_mode_type', which means the type bits in the st_mode field.

In practice, all fields are provided for free on Windows; whereas only the
st_mode_type information is provided for free on Linux, Mac OS X, and BSD.
"""

def iterdir(path='.', pattern='*'):
    """Like iterdir_stat(), but only yield the filenames."""
    for name, st in iterdir_stat(path, pattern=pattern):
        yield name

def walk(top, topdown=True, onerror=None, followlinks=False):
    """Just like os.walk(), but faster, as it uses iterdir_stat internally."""
    # Determine which are files and which are directories
    dirs = []
    dir_stats = []
    nondirs = []
    try:
        for name, st in iterdir_stat(top, fields=['st_mode_type']):
            if stat.S_ISDIR(st.st_mode):
                dirs.append(name)
                dir_stats.append(st)
            else:
                nondirs.append(name)
    except OSError as err:
        if onerror is not None:
            onerror(err)
        return

    # Yield before recursion if going top down
    if topdown:
        yield top, dirs, nondirs

    # Recurse into sub-directories, following symbolic links if "followlinks"
    for name, st in zip(dirs, dir_stats):
        new_path = os.path.join(top, name)
        if followlinks or not stat.S_ISLNK(st.st_mode):
            for x in walk(new_path, topdown, onerror, followlinks):
                yield x

    # Yield before recursion if going bottom up
    if not topdown:
        yield top, dirs, nondirs


text:
import { Argv } from 'yargs';
import { getResolver } from '@cardstack/did-resolver';
import { Resolver } from 'did-resolver';
import { Arguments, CommandModule } from 'yargs';
import fetch from 'node-fetch';

export default {
  command: 'resolve-aka <did>',
  describe: 'Decode the DID to a JSON DIDResult and output the contents of the alsoKnownAs URL',
  builder(yargs: Argv) {
    return yargs.positional('did', {
      type: 'string',
      description: 'The DID to decode',
    });
  },
  async handler(args: Arguments) {
    let { did } = args as unknown as {
      did: string;
    };
    let didResolver = new Resolver(getResolver());
    let didResult = await didResolver.resolve(did);
    if (!didResult.didDocument?.alsoKnownAs) {
      throw new Error('No alsoKnownAs found for DID');
    }
    let urlResponse = await fetch(didResult.didDocument?.alsoKnownAs[0]);
    let content = await urlResponse.json();
    console.log(JSON.stringify(content, null, 1));
  },
} as CommandModule;

redpajama_set_name: RedPajamaGithub


text:
import Promise from 'bluebird';
import { isNil } from 'ramda';

import Config from './config.js';
import maps from './trelloPropertyMaps';
import net from './net/networkService';
import trelloFactory from './trelloFactory';

/**
 * An object-oriented wrapper for the Trello API.
 *
 * @module trello-yello
 * @main trello-yello
 */

/**
 * Trello Yello's entry point for accessing the Trello API. It serves as both an
 * object factory for Trello objects as well as a platform for performing
 * operations that aren't associated with specific Trello objects, such as
 * queries against the Trello search engine.
 * @class trello
 * @constructor
 * @param {Object} params the constructor parameters object
 * @param {String} params.key the application key for accessing Trello
 * @param {String} params.token a valid Trello API token
 */
export default (cParams) => {
	const { key, token } = cParams;

	if (isNil(key) || isNil(token)) {
		throw new Error('Key, token, and network service are required.');
	}

	const config = new Config(key, token, 1);

	/**
	 * Creates a new Trello object for the given type. If the object type is
	 * invalid or if the object type does not allow creation through the API,
	 * then this method resolves to an error.
	 *
	 * @method create
	 * @param {Object} params the method parameters object
	 * @param {String} params.objType the type of Trello object. Please refer to
	 * other documentation for the list of allowed types.
	 * @param {Object} params.initialVals the initial values of the Trello
	 * object
	 * @param {Function} [params.callback] the callback function once the
	 * operation is complete. This is optional, as a Promise is returned.
	 * @return {Object} a Promise that resolves to the newly created trelloObj
	 * object
	 * @private
	 */
	const create = (params) => {
		const { objType, initialVals, callback } = params;

		if (maps[objType] === undefined) {
			return Promise.reject(new Error(
					`Object type ${objType} does not exist.`
			)).nodeify(callback);
		}

		if (!maps[objType].allowCreation) {
			return Promise.reject(new Error(
					`Object type ${objType} does not allow creation.`
			)).nodeify(callback);
		}

		return net.post(config, objType, null, initialVals)
				.then((response) => {
					const rawObj = JSON.parse(response.body);
					return Promise.resolve(trelloFactory.createTrelloObject({
						maps,
						objType,
						config,
						id: rawObj.id,
						net,
						initialVals: rawObj,
						objConstructor: trelloFactory.createTrelloObject
					})).nodeify(callback);
				});
	};

	/**
	 * Retrieves an existing Trello object.
	 *
	 * @method get
	 * @param {Object} params the method parameters object
	 * @param {String} params.objType the type of Trello object. Please refer to other
	 * documentation for the list of allowed types.
	 * @param {String} params.id the ID of the Trello object
	 * @return {Object} the retrieved trelloObj object
	 */
	const get = (params) => {
		const { objType, id } = params;
		if (isNil(id)) {
			throw new Error('Must supply a valid object type and id.');
		}

		return trelloFactory.createTrelloObject({
			maps,
			objType,
			config,
			id,
			net,
			objConstructor: trelloFactory.createTrelloObject
		});
	};

	////////////////////////////////////////////////////////////////////////////
	//															PUBLIC METHODS														//
	////////////////////////////////////////////////////////////////////////////

	/**
	 * @method createBoard
	 * @param {Object} params the method parameters object
	 * @param {String} params.name the board's name
	 * @param {String} [params.description] the board's description
	 * @param {String} [params.organizationId] the board's organization
	 * @param {String} [params.cloneId] the id of the existing board to clone
	 * @param {String} [params.keepFromSource='all'] a comma-separated list of
	 * properties to keep from the source board, or 'all'
	 * @param {String} [params.powerUps] the powerUps to give the new board. This
	 * is a comma separated list of values that can include 'calendar',
	 * 'cardAging', 'recap', and 'voting'.
	 * @param {String} [params.permissionLevel='default'] the permissions level
	 * of the board. Valid values are 'org', 'private', and 'public'.
	 * @param {String} [params.voting='disabled'] the board permissions for
	 * voting. Valid values are 'disabled', 'members', 'observers', 'org', and
	 * 'public'.
	 * @param {String} [params.comments='members'] the board permissions for
	 * commenting. Valid values are 'disabled', 'members', 'observers', 'org',
	 * and 'public'.
	 * @param {String} [params.invitations='members'] the board permissions for
	 * sending invitations. Valid values are 'admins' and 'members'.
	 * @param {Boolean} [params.selfJoin=true] the board permissions for allowing
	 * members to self join
	 * @param {Boolean} [params.cardCovers=true] the board setting for card
	 * covers.
	 * @param {String} [params.background='blue'] the board's background
	 * @param {String} [params.cardAging='regular'] the board's card aging
	 * setting. Valid values are 'regular' and 'pirate'.
	 * @param {Function} [params.callback] the callback function once the
	 * operation is complete. This is optional, as a Promise is returned.
	 * @return {Object} a Promise that resolves to the new board
	 */
	const createBoard = (params) => {
		const initialVals = {
			name: params.name,
			desc: params.description,
			idOrganization: params.organizationId,
			idBoardSource: params.cloneId,
			keepFromSource: params.keepFromSource,
			powerUp: params.powerUps,
			prefs_permissionLevel: params.permissionLevel,
			prefs_voting: params.voting,
			prefs_comments: params.comments,
			prefs_invitations: params.invitations,
			prefs_selfJoin: params.selfJoin,
			prefs_cardCovers: params.cardCovers,
			prefs_background: params.background,
			prefs_cardAging: params.cardAging
		};

		const args = {
			objType: 'board',
			initialVals,
			callback: params.callback
		};

		return create(args);
	};

	/**
	 * @method createCard
	 * @param {Object} params the method parameters object
	 * @param {String} params.name the card's name
 	 * @param {String} params.listId the id of the list the card will be added to
	 * @param {String} [params.description] the card's description
	 * @param {String | Number} [params.position='bottom'] the card's position.
	 * This can be 'top', 'bottom', or a positive number.
	 * @param {Date} [params.dueDate] the card's due date. If not included, it won't
	 * have a due date.
	 * @param {String} [params.labels] a comma-separated list of colors, or 'all'
	 * @param {String} [params.memberIds] a comma-separated list of member id's
	 * that will be assigned to the card
	 * @param {String} [params.labelIds] a comma-separated list of label id's
	 * that will be assigned to the card
	 * @param {String} [params.urlSource] if included, a URL starting with
	 * http:// or https://
	 * @param {File} [params.fileSource] a file
	 * @param {String} [params.sourceCardId] the id of the card to clone
	 * @param {String} [params.keepFromSource='all'] a comma-separated list of
	 * properties to keep from the source card, or 'all'
	 * @param {Function} [params.callback] the callback function once the
	 * operation is complete. This is optional, as a Promise is returned.
	 * @return {Object} a Promise that resolves to the new card
	 */
	const createCard = (params) => {
		const initialVals = {
			name: params.name,
			desc: params.description,
			pos: params.position,
			due: params.dueDate,
			labels: params.labels,
			idList: params.listId,
			idMembers: params.memberIds,
			idLabels: params.labelIds,
			urlSource: params.urlSource,
			fileSource: params.fileSource,
			idCardSource: params.sourceCardId,
			keepFromSource: params.keepFromSource
		};

		const args = {
			objType: 'card',
			initialVals,
			callback: params.callback
		};

		return create(args);
	};

	/**
	 * @method createChecklist
	 * @param {Object} params the method parameters object
	 * @param {String} params.name the checklist's name
	 * @param {String} [params.boardId] the id of the checklist's board
	 * @param {String} [params.cardId] the id of the checklist's card
	 * @param {String | Number} [params.position='bottom'] the checklist's
	 * position. Valid values are 'top', 'bottom', or a positive number.
	 * @param {String} [params.cloneId] the id of a checklist to clone
	 * @param {Function} [params.callback] the callback function once the
	 * operation is complete. This is optional, as a Promise is returned.
	 * @return {Object} a Promise that resolves to the new checklist
	 */
	const createChecklist = (params) => {
		const initialVals = {
			name: params.name,
			idBoard: params.boardId,
			idCard: params.cardId,
			pos: params.position,
			idChecklistSource: params.cloneId
		};

		const args = {
			objType: 'checklist',
			initialVals,
			callback: params.callback
		};

		return create(args);
	};

	/**
	 * @method createLabel
	 * @param {Object} params the method parameters object
	 * @param {String} params.name the label's name
 	 * @param {String} params.color the label's color
	 * @param {String} params.boardId the id of the label's board
	 * @param {Function} [params.callback] the callback function once the
	 * operation is complete. This is optional, as a Promise is returned.
	 * @return {Object} a Promise that resolves to the new label
	 */
	const createLabel = (params) => {
		const initialVals = {
			name: params.name,
			color: params.color,
			idBoard: params.boardId
		};

		const args = {
			objType: 'label',
			initialVals,
			callback: params.callback
		};

		return create(args);
	};

	/**
	 * @method createList
	 * @param {Object} params the method parameters object
	 * @param {String} params.name the list's name
	 * @param {String} params.boardId the id of the list's board
	 * @param {String} [params.cloneId] the id of the list to clone
	 * @param {String | Number} [params.position='top'] the position of the list.
	 * Valid values are 'top', 'bottom', or a positive number.
	 * @param {Function} [params.callback] the callback function once the
	 * operation is complete. This is optional, as a Promise is returned.
	 * @return {Object} a Promise that resolves to the new list
	 */
	const createList = (params) => {
		const initialVals = {
			name: params.name,
			idBoard: params.boardId,
			idListSource: params.cloneId,
			pos: params.position
		};

		const args = {
			objType: 'list',
			initialVals,
			callback: params.callback
		};

		return create(args);
	};

	/**
	 * @method createOrganization
	 * @param {Object} params the method parameters object
	 * @param {String} [params.name] the organization's name
	 * @param {String} [params.displayName] the organization's display name
	 * @param {String} [params.description] the organization's description
	 * @param {String} [params.website] the organization's website. Must be a
	 * valid URL starting with 'http://', 'https://', or null.
	 * @return {Object} a Promise that resolves to the new organization
	 */
	const createOrganization = (params) => {
		const initialVals = {
			name: params.name,
			displayName: params.displayName,
			desc: params.description,
			website: params.website
		};

		const args = {
			objType: 'organization',
			initialVals,
			callback: params.callback
		};

		return create(args);
	};

	/**
	 * @method createWebhook
	 * @param {Object} params the method parameters object
	 * @param {String} params.watchId the id of the model to watch
	 * @param {String} params.callbackUrl the url of the webhook's callback
	 * @param {String} [params.description] the description of the webhook
	 * @param {Function} [params.callback] the callback function once the
	 * operation is complete
	 * @return {Object} a Promise that resolves to the new webhook object
	 */
	const createWebhook = (params) => {
		const initialVals = {
			idModel: params.watchId,
			callbackURL: params.callbackUrl,
			description: params.description
		};

		const args = {
			objType: 'webhook',
			initialVals,
			callback: params.callback
		};

		return create(args);
	};

	/**
	 * @method getAction
	 * @param {String} actionId the id of the action
	 * @return {Object} the action object
	 */
	const getAction = (actionId) => {
		return get({ objType: 'action', id: actionId });
	};

	/**
	 * @method getBoard
	 * @param {String} boardId the id of the board
	 * @return {Object} the board object
	 */
	const getBoard = (boardId) => {
		return get({ objType: 'board', id: boardId });
	};

	/**
	 * @method getCard
	 * @param {String} cardId the id of the card
	 * @return {Object} the card object
	 */
	const getCard = (cardId) => {
		return get({ objType: 'card', id: cardId });
	};

	/**
	 * @method getChecklist
	 * @param {String} checklistId the id of the checklist
	 * @return {Object} the checklist object
	 */
	const getChecklist = (checklistId) => {
		return get({ objType: 'checklist', id: checklistId });
	};

	/**
	 * @method getLabel
	 * @param {String} labelId the id of the label
	 * @return {Object} the label object
	 */
	const getLabel = (labelId) => {
		return get({ objType: 'label', id: labelId });
	};

	/**
	 * @method getList
	 * @param {String} listId the id of the list
	 * @return {Object} the list object
	 */
	const getList = (listId) => {
		return get({ objType: 'list', id: listId });
	};

	/**
	 * @method getMember
	 * @param {String} memberId the id of the member
	 * @return {Object} the member object
	 */
	const getMember = (memberId) => {
		return get({ objType: 'member', id: memberId });
	};

	/**
	 * @method getNotification
	 * @param {String} notificationId the id of the notification
	 * @return {Object} the notification object
	 */
	const getNotification = (notificationId) => {
		return get({ objType: 'notification', id: notificationId });
	};

	/**
	 * @method getOrganization
	 * @param {String} organizationId the id of the organization
	 * @return {Object} the organization object
	 */
	const getOrganization = (organizationId) => {
		return get({ objType: 'organization', id: organizationId });
	};

	/**
	 * @method getToken
	 * @param {String} tokenId the id of the token
	 * @return {Object} the token object
	 */
	const getToken = (tokenId) => {
		return get({ objType: 'token', id: tokenId });
	};

	/**
	 * @method getWebhook
	 * @param {String} webhookId the id of the webhook
	 * @return {Object} the webhook object
	 */
	const getWebhook = (webhookId) => {
		return get({ objType: 'webhook', id: webhookId });
	};

	/**
	 * @method getCurrentUser
	 * @return {Object} the member object for the current user
	 */
	const getCurrentUser = () => {
		return getMember('me');
	};

	/**
	 * Marks all notifications read by the user.
	 *
	 * @method markAllNotificationsRead
	 * @param {Function} [callback] the callback function once the
	 * operation is complete
	 * @return {Object} a Promise that resolves to a truthy value if successful
	 */
	const markAllNotificationsRead = (callback) => {
		return net.post(config, 'notification', 'all', {}, 'read').nodeify(callback);
	};

	/**
	 * Runs a query against the Trello search engine.
	 *
	 * @method
	 * @param {Object} params the method parameters object
	 * @param {string} params.query the search query to run
	 * @param {Function} [params.callback] the callback function once the
	 * operation is complete. This is optional, as a Promise is returned.
	 * @return {Object} the query result
	 */
	const search = (params) => {
		const { query, callback } = params;
		const parameters = {
			query,
			idBoards: 'mine',
			modelTypes: 'all',
			board_fields: 'all',
			boards_limit: '1000',
			card_fields: 'all',
			cards_limit: '1000',
			card_board: 'true',
			card_list: 'true',
			card_members: 'true',
			card_stickers: 'true',
			card_attachments: 'true',
			organization_fields: 'all',
			organizations_limit: '1000',
			member_fields: 'all',
			members_limit: '1000',
			partial: 'false'
		};

		return net.get(config, 'search', undefined, parameters)
				.then((response) => Promise.resolve(JSON.parse(response.body))
						.nodeify(callback));
	};

	return Object.freeze({
		createBoard,
		createCard,
		createChecklist,
		createLabel,
		createList,
		createOrganization,
		createWebhook,
		getAction,
		getBoard,
		getCard,
		getChecklist,
		getLabel,
		getList,
		getMember,
		getNotification,
		getOrganization,
		getToken,
		getWebhook,
		getCurrentUser,
		markAllNotificationsRead,
		search
	});
};


text:
/**
 * @file    NewProjectPanelBase.cpp
 * @author  Marvin Smith
 * @date    5/25/2017
 */
#include "NewProjectPanelBase.hpp"

/*********************************/
/*          Constructor          */
/*********************************/
NewProjectPanelBase::NewProjectPanelBase( System_Configuration::ptr_t sys_config,
                                          QWidget *parent)
 : QWidget(parent),
   m_sys_config(sys_config),
   m_class_name("NewProjectPanelBase")
{
}


text:
#ifndef __ELF_OBJECT_HH__
#define __ELF_OBJECT_HH__

#include <set>
#include <vector>

#include "base/loader/object_file.hh"

class ElfObject : public ObjectFile
{
  protected:
    // The global definition of a gem5 "Section" is closest to ELF's segments.
    typedef ObjectFile::Section Segment;

    // These values are provided to a linux process by the kernel, so we
    // need to keep them around.
    Addr _programHeaderTable;
    uint16_t _programHeaderSize;
    uint16_t _programHeaderCount;
    std::set<std::string> sectionNames;

    ElfObject *interpreter;

    // An interpreter load bias is the location in the process address space
    // where the interpreter is chosen to reside. Typically, this is carved
    // out of the top of the mmap reserve section.
    Addr ldBias;

    // The interpreter is typically a relocatable shared library and will
    // have a default value of zero which means that it does not care where
    // it is placed. However, the loader can be compiled and linked so that
    // it does care and needs a specific entry point.
    bool relocate;

    // The ldMin and ldMax fields are required to know how large of an
    // area is required to map the interpreter.
    Addr ldMin;
    Addr ldMax;

    /// Helper functions for loadGlobalSymbols() and loadLocalSymbols().
    bool loadSomeSymbols(SymbolTable *symtab, int binding, Addr mask,
                         Addr base, Addr offset);

    ElfObject(const std::string &_filename, size_t _len, uint8_t *_data,
              Arch _arch, OpSys _opSys);

    void getSections();
    bool sectionExists(std::string sec);

    std::vector<Segment> extraSegments;

  public:
    virtual ~ElfObject() {}

    bool loadSections(PortProxy& mem_proxy, Addr addr_mask = maxAddr,
                      Addr offset = 0) override;

    virtual bool loadAllSymbols(SymbolTable *symtab, Addr base = 0,
                                Addr offset = 0, Addr addr_mask = maxAddr)
                                override;

    virtual bool loadGlobalSymbols(SymbolTable *symtab, Addr base = 0,
                                   Addr offset = 0, Addr addr_mask = maxAddr)
                                   override;

    virtual bool loadLocalSymbols(SymbolTable *symtab, Addr base = 0,
                                  Addr offset = 0, Addr addr_mask = maxAddr)
                                  override;

    virtual bool loadWeakSymbols(SymbolTable *symtab, Addr base = 0,
                                 Addr offset = 0, Addr addr_mask = maxAddr)
                                 override;

    virtual ObjectFile *getInterpreter() const override
    { return interpreter; }
    virtual Addr bias() const override { return ldBias; }
    virtual bool relocatable() const override { return relocate; }
    virtual Addr mapSize() const override { return ldMax - ldMin; }
    virtual void updateBias(Addr bias_addr) override;

    virtual bool hasTLS() override { return sectionExists(".tbss"); }

    static ObjectFile *tryFile(const std::string &fname,
                               size_t len, uint8_t *data,
                               bool skip_interp_check = false);
    Addr programHeaderTable() {return _programHeaderTable;}
    uint16_t programHeaderSize() {return _programHeaderSize;}
    uint16_t programHeaderCount() {return _programHeaderCount;}
};

#endif // __ELF_OBJECT_HH__


text:
ComponentPrimitiveMesh::ComponentPrimitiveMesh()
{
	type = COMP_PRIMITIVE_MESH;
}

ComponentPrimitiveMesh::ComponentPrimitiveMesh(const ComponentPrimitiveMesh & cpy) :ComponentMesh(cpy)
{
	type = COMP_PRIMITIVE_MESH;
}

// Destructors ==================================
ComponentPrimitiveMesh::~ComponentPrimitiveMesh()
{

}

void ComponentPrimitiveMesh::SetPrimitiveType(PRIMITIVE_TYPE type)
{
	primitive_type = type;
}

PRIMITIVE_TYPE ComponentPrimitiveMesh::GetPrimitiveType() const
{
	return primitive_type;
}


text:
This intention replaces if statement with
another if statement using inverted condition inside.

The intention might be useful to e.g. simplify complex code using multiple nested if statements.


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Bearnaise Sauce</title>
      <categories>
        <cat/></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>8</qty>
          <unit>ounces</unit></amt>
        <item>Butter</item></ing>
      <ing>
        <amt>
          <qty>1/4</qty>
          <unit>cups</unit></amt>
        <item>Red wine vinegar</item></ing>
      <ing>
        <amt>
          <qty>1/4</qty>
          <unit>cups</unit></amt>
        <item>White wine vinegar</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Shallot; chopped</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Tarragon; chopped</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Salt and pepper</item></ing>
      <ing>
        <amt>
          <qty>4</qty>
          <unit/></amt>
        <item>Egg yolk</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Water</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Whole lemon; juiced</item></ing></ingredients>
    <directions>
      <step>  1. Clarify the butter by heating slowly. When it stops inging it's
  clarified and you can pour off the top part the solids will be in the
  bottom of the pan. Keep warm.

  2. In a small saucepan, heat the vinegars with the shallots, tarragon, salt
  and pepper. Let boil slowly until all the liquid has been reduced.

  3. In a stainless steel bowl, beat the egg yolks with 1 tablespoon of water
  over a double boiler on a low flame. This will create a lot of volume to
  the yolks while cooking them. Beath until you reach the ribbon stage.

  4. Stir in the clarified buytter, very slowly, as you would do for a
  mayonnaise. Add the reduction.

  5. Correct the seasonings with salt, pepper, and lemon juice. Keep in a
  warm place for up to three hours.
  Posted to EAT-L Digest 29 Aug 96

  Date:    Fri, 30 Aug 1996 15:38:39 -465800

  From:    Terry Pogue <tpogue@IDS2.IDSONLINE.COM>

</step></directions></recipe></recipeml>


text:
'use strict';

describe('Login controller', function() {

  var scope, $q;

  beforeEach(module('services'));
  beforeEach(module('controllers'));

  beforeEach(inject(function($rootScope, $controller, _$q_) {
    scope = $rootScope.$new();
    $controller('LoginCtrl', {
      $scope: scope
    });
    $q = _$q_;
  }));

  it('should pass login with valid credentials', inject(function(AuthenticationService) {
    spyOn(AuthenticationService, 'login').and.returnValue($q.when('mySecretToken'));
    scope.login({});
    scope.$apply();
    expect(scope.failedLogin).toBeFalsy();
  }));

  it('should fail login with invalid credentials', inject(function(AuthenticationService) {
    spyOn(AuthenticationService, 'login').and.returnValue($q.reject('Fake login rejection'));
    scope.login({});
    scope.$apply();
    expect(scope.failedLogin).toBeTruthy();
  }));

});


text:
<databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd">

  <changeSet author="murygina" id="add_person_reference_to_comment">

    <preConditions>
      <tableExists tableName="Comment"/>
      <columnExists tableName="Comment" columnName="nameOfCommentingPerson"/>
    </preConditions>

    <addColumn tableName="Comment">
      <column name="person_id" type="INT(10)"/>
    </addColumn>

    <sql>
      UPDATE Comment comment SET person_id = (SELECT person.id FROM Person person WHERE
      CONCAT(person.firstName, ' ', person.lastName) LIKE comment.nameOfCommentingPerson);
    </sql>

  </changeSet>

  <changeSet author="murygina" id="remove_deprecated_column_nameOfCommentingPerson_from_comment">

    <preConditions>
      <tableExists tableName="Comment"/>
      <columnExists tableName="Comment" columnName="nameOfCommentingPerson"/>
      <columnExists tableName="Comment" columnName="person_id"/>
    </preConditions>

    <dropColumn tableName="Comment" columnName="nameOfCommentingPerson"/>

  </changeSet>

</databaseChangeLog>


text:
function setErrors(element, valueAccessor) {

    var value = ko.unwrap(valueAccessor());

    if (value.length > 0) {

        var span = element.querySelector('.ko-input-error');

        if (!span) {

            // No existing error display.

            if (!element.className.match(/has\-error/)) {

                element.className = element.className + ' has-error';
            }

            span = document.createElement('span');

            span.className = 'help-block ko-input-error';

            // Finds the holder element.

            var holder = element.querySelector('.checkbox');

            if (!holder) {

                holder = element.querySelector('.form-control');
            }

            holder.parentNode.appendChild(span);
        }

        // Update errors display.

        span.innerHTML = value.join(' ');

    } else {

        // Removes error class and messages.

        element.className = element.className.replace(/has\-error/, '');
        element.className = element.className.replace(/\s+/, ' ');

        var error = element.querySelector('.ko-input-error');

        if (error) {

            error.parentNode.removeChild(error);
        }
    }
}

// Defines the errors binding.

ko.bindingHandlers.errors = {

    init: function(element, valueAccessor) {

        setErrors(element, valueAccessor);
    },

    update: function(element, valueAccessor, allBindings) {

        setErrors(element, valueAccessor);
    }
};


text:
<component name="libraryTable">
  <library name="unity-classes">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/libs/unity-classes.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text: #include "envelope.cc"


text:
Kernel.hub.define('toilets', {
    init: function () {
        var self = this;
        console.log('toilet hub started');
        self.listen('fetch-toilets-list', function () {
            console.log('fetching toilets...')
            $.ajax({
                url: "toilets",
                contentType: 'application/json',
                success: function (data) {
                    hub.broadcast('fetched-toilets-list', data);
                },
                error: function () {
                    hub.broadcast('error', 'error fetching toilet data');
                }
            });
        });
    }
});

var hub = Kernel.hub.get('toilets');
hub.init();


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class VmFaultToleranceVmTerminatedEvent extends VmEvent
{
  public String reason;

  public String getReason()
  {
    return this.reason;
  }

  public void setReason(String reason)
  {
    this.reason=reason;
  }
}


text:
using System;
using System.Text;
using Org.Unidal.Cat.Message.Spi.Codec;
using Org.Unidal.Cat.Util;

namespace Org.Unidal.Cat.Message.Internals
{
    public abstract class AbstractMessage : IMessage
    {
        private String _mName;
        private String _mType;
        private bool _mCompleted;
        private StringBuilder _mData;

        private String _mStatus = "unset";

        protected AbstractMessage(String type, String name)
        {
            _mType = type;
            _mName = name;
            TimestampInMicros = MilliSecondTimer.UnixNowMicroSeconds();
        }

        /// <summary>
        ///   其实是Ticks除以10
        /// </summary>
        protected long TimestampInMicros { get; private set; }

        #region IMessage Members

        public String Data
        {
            get { return _mData == null ? "" : _mData.ToString(); }
        }

        public String Name
        {
            get { return _mName; }
            set { _mName = value ?? CatConstants.NULL_STRING; }
        }

        public String Status
        {
            get { return _mStatus; }

            set
            {
                _mStatus = (value == null) ? "unset" : (value.Length > 64 ? value.Substring(0, 64) : value);
            }
        }

        /// <summary>
        ///   其实是Ticks除以10000
        /// </summary>
        public long Timestamp
        {
            get { return TimestampInMicros/1000L; }
            set { TimestampInMicros = value*1000L; }
        }

        public String Type
        {
            get { return _mType; }
            set { _mType = value ?? CatConstants.NULL_STRING; }
        }

        public virtual void AddData(String keyValuePairs)
        {
            try
            {
                // No meaning to add null as data.
                if (null == keyValuePairs)
                    return;

                if (_mData == null)
                {
                    _mData = new StringBuilder(keyValuePairs);
                }
                else
                {
                    _mData.Append(keyValuePairs);
                }
            }
            catch (Exception ex)
            {
                Cat.lastException = ex;
            }
        }

        public virtual void AddData(String key, Object value)
        {
            try
            {
                if (_mData == null)
                {
                    _mData = new StringBuilder();
                }
                else if (_mData.Length > 0)
                {
                    _mData.Append('&');
                }

                _mData.Append(key).Append('=').Append(value);
            }
            catch (Exception ex)
            {
                Cat.lastException = ex;
            }
        }

        public virtual void Complete()
        {
            SetCompleted(true);
        }

        public bool IsCompleted()
        {
            return _mCompleted;
        }

        public bool IsSuccess()
        {
            return CatConstants.SUCCESS.Equals(_mStatus);
        }

        public void SetStatus(Exception e)
        {
            if (null != e)
            {
                _mStatus = e.GetType().FullName;
            }
        }

        #endregion

        public void SetCompleted(bool completed)
        {
            _mCompleted = completed;
        }

        public override String ToString()
        {
            try
            {
                PlainTextMessageCodec codec = new PlainTextMessageCodec();
                ChannelBuffer buf = new ChannelBuffer(8192);

                codec.EncodeMessage(this, buf);
                buf.Reset();

                return buf.ToString();
            }
            catch (Exception ex)
            {
                Cat.lastException = ex;
                return "";
            }
        }

        public int EstimateByteSize()
        {
            return (Type == null ? 0 : Type.Length)
                + (Name == null ? 0 : Name.Length)
                + (Data == null ? 0 : Data.Length);
                //+ (_mStatus == null ? 0 : _mStatus.Length);
        }
    }
}


text:
            [__OBJ__ retain]

#define FLRelease(__OBJ__) \
            [__OBJ__ release]

#define FLAutorelease(__OBJ__) \
            [__OBJ__ autorelease]

#define FLAutoreleaseObject(__OBJ__) \
            [__OBJ__ autorelease];

NS_INLINE
void FLRetainObject(id object) {
    [object retain];
}

#define FLSuperDealloc() \
            [super dealloc]

#define FLBridge(__TO__, __FROM__) \
            ((__TO__) __FROM__)

#define FLBridgeTransfer(__TO__, __FROM__) \
            ((__TO__) __FROM__)

#define bridge_retain_(__TO__, __FROM__) \
            ((__TO__) [__FROM__ retain])

#define FLBridge(__TO__, __FROM__) \
            ((__TO__) __FROM__)

#define FLBridgeTransfer(__TO__, __FROM__) \
            ((__TO__) __FROM__)

#define FLBridgeRetain(__TO__, __FROM__) \
            ((__TO__) [__FROM__ retain])

// mrc utils

NS_INLINE
void FLManuallyRelease(id* obj) {
    if(obj && *obj) {
        [*obj release];
        *obj = nil;
    }
}

NS_INLINE
void _FLReleaseBlockWithNil(dispatch_block_t* block) {
    if(block && *block) {
        FLRelease(*block);
        *block = nil;
    }
}

#define FLReleaseBlockWithNil(b) \
            _FLReleaseBlockWithNil((dispatch_block_t*) &(b))

#define FLAutoreleasePoolOpen(__NAME__) \
    { \
        NSAutoreleasePool* __NAME__ = [[NSAutoreleasePool alloc] init]; \
        @try {

#define FLAutoreleasePoolClose(__NAME__) \
            [__NAME__ drain]; \
        } \
        @catch(id exception) { \
            [exception retain]; \
            [__NAME__ drain]; \
            [exception autorelease]; \
            @throw; \
        } \
    }

NS_INLINE
void FLSaveBlockForLater(dispatch_block_t* block) {
    if(block && *block) {
        *block = [[*block copy] autorelease];
    }
}

#define FLPrepareBlockForFutureUse(__BLOCK__) \
    FLSaveBlockForLater((dispatch_block_t*) &__BLOCK__)

#endif


text:
#include "fennel/common/CommonPreamble.h"
#include "fennel/segment/SegmentFactory.h"
#include "fennel/segment/LinearDeviceSegment.h"
#include "fennel/segment/LinearViewSegment.h"
#include "fennel/segment/WALSegment.h"
#include "fennel/segment/VersionedSegment.h"
#include "fennel/segment/ScratchSegment.h"
#include "fennel/segment/RandomAllocationSegment.h"
#include "fennel/segment/SnapshotRandomAllocationSegment.h"
#include "fennel/segment/VersionedRandomAllocationSegment.h"
#include "fennel/segment/DynamicDelegatingSegment.h"
#include "fennel/segment/CircularSegment.h"
#include "fennel/segment/SegmentAccessor.h"
#include "fennel/common/ConfigMap.h"
#include "fennel/common/FileSystem.h"
#include "fennel/device/RandomAccessFileDevice.h"

FENNEL_BEGIN_CPPFILE("$Id$");

ParamName SegmentFactory::paramTraceSegments = "traceSegments";

SharedSegmentFactory SegmentFactory::newSegmentFactory(
    ConfigMap const &configMap,
    SharedTraceTarget pTraceTarget)
{
    return SharedSegmentFactory(
        new SegmentFactory(configMap, pTraceTarget));
}

SegmentFactory::SegmentFactory(
    ConfigMap const &configMapInit,
    SharedTraceTarget pTraceTargetInit)
    : configMap(configMapInit)
{
    pTraceTarget = pTraceTargetInit;

    // TODO:  parameterize
    firstTempDeviceId = DeviceId(512);
    tempDeviceIdBitset.resize(512);
}

SegmentFactory::~SegmentFactory()
{
}

ConfigMap const &SegmentFactory::getConfigMap() const
{
    return configMap;
}

SharedSegment SegmentFactory::newLinearDeviceSegment(
    SharedCache cache,
    LinearDeviceSegmentParams const &params)
{
    SharedSegment pSegment(
        new LinearDeviceSegment(cache, params),
        ClosableObjectDestructor());
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "LinearDeviceSegment");
    tracingSegment->initForUse();
    return tracingSegment;
}

SharedSegment SegmentFactory::newRandomAllocationSegment(
    SharedSegment delegateSegment,
    bool bFormat,
    bool deferInit)
{
    RandomAllocationSegment *pRandomSegment =
        new RandomAllocationSegment(delegateSegment);
    SharedSegment pSegment(pRandomSegment, ClosableObjectDestructor());
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "RandomAllocationSegment");
    // Format the segment through the tracing segment so the operation
    // is traced
    if (bFormat) {
        tracingSegment->deallocatePageRange(NULL_PAGE_ID, NULL_PAGE_ID);
    }
    if (!deferInit) {
        tracingSegment->initForUse();
    }
    return tracingSegment;
}

SharedSegment SegmentFactory::newVersionedRandomAllocationSegment(
    SharedSegment delegateSegment,
    SharedSegment pTempSegment,
    bool bFormat,
    bool deferInit)
{
    VersionedRandomAllocationSegment *pVersionedRandomSegment =
        new VersionedRandomAllocationSegment(delegateSegment, pTempSegment);
    SharedSegment pSegment(pVersionedRandomSegment, ClosableObjectDestructor());
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "VersionedRandomAllocationSegment");
    // Format the segment through the tracing segment so the operation
    // is traced
    if (bFormat) {
        tracingSegment->deallocatePageRange(NULL_PAGE_ID, NULL_PAGE_ID);
    }
    if (!deferInit) {
        tracingSegment->initForUse();
    }
    return tracingSegment;
}

SharedSegment SegmentFactory::newSnapshotRandomAllocationSegment(
    SharedSegment delegateSegment,
    SharedSegment versionedSegment,
    TxnId snapshotCsn,
    bool readOnlyCommittedData)
{
    SnapshotRandomAllocationSegment *pSnapshotSegment =
        new SnapshotRandomAllocationSegment(
            delegateSegment,
            versionedSegment,
            snapshotCsn,
            readOnlyCommittedData);
    SharedSegment pSegment(pSnapshotSegment, ClosableObjectDestructor());
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "SnapshotRandomAllocationSegment");
    tracingSegment->initForUse();
    return tracingSegment;
}

SharedSegment SegmentFactory::newDynamicDelegatingSegment(
    SharedSegment delegateSegment)
{
    DynamicDelegatingSegment *pDelegatingSegment =
        new DynamicDelegatingSegment(WeakSegment(delegateSegment));
    SharedSegment pSegment(pDelegatingSegment, ClosableObjectDestructor());
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "DynamicDelegatingSegment");
    tracingSegment->initForUse();
    return tracingSegment;
}

SharedSegment SegmentFactory::newWALSegment(
    SharedSegment logSegment)
{
    SharedSegment pSegment(
        new WALSegment(logSegment),
        ClosableObjectDestructor());
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "WALSegment");
    tracingSegment->initForUse();
    return tracingSegment;
}

SharedSegment SegmentFactory::newLinearViewSegment(
    SharedSegment delegateSegment,
    PageId firstPageId)
{
    SharedSegment pSegment(
        new LinearViewSegment(delegateSegment, firstPageId),
        ClosableObjectDestructor());
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "LinearViewSegment");
    tracingSegment->initForUse();
    return tracingSegment;
}

SharedSegment SegmentFactory::newVersionedSegment(
    SharedSegment dataSegment,
    SharedSegment logSegment,
    PseudoUuid const &onlineUuid,
    SegVersionNum versionNumber)
{
    SharedSegment pSegment(
        new VersionedSegment(
            dataSegment, logSegment, onlineUuid, versionNumber),
        ClosableObjectDestructor());
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "VersionedSegment");
    tracingSegment->initForUse();
    return tracingSegment;
}

SegmentAccessor SegmentFactory::newScratchSegment(
    SharedCache pCache,
    uint nPagesMax)
{
    boost::shared_ptr<ScratchSegment> pSegment(
        new ScratchSegment(pCache, nPagesMax),
        ClosableObjectDestructor());
    SegmentAccessor segmentAccessor;
    segmentAccessor.pSegment = newTracingSegment(pSegment, "ScratchSegment");
    segmentAccessor.pSegment->initForUse();
    segmentAccessor.pCacheAccessor = pSegment;
    return segmentAccessor;
}

SharedSegment SegmentFactory::newCircularSegment(
    SharedSegment delegateSegment,
    SharedCheckpointProvider pCheckpointProvider,
    PageId oldestPageId,
    PageId newestPageId)
{
    SharedSegment pSegment(
        new CircularSegment(
            delegateSegment,
            pCheckpointProvider,
            oldestPageId, newestPageId),
        ClosableObjectDestructor());
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "CircularSegment");
    tracingSegment->initForUse();
    return tracingSegment;
}

SharedSegment SegmentFactory::newTracingSegment(
    SharedSegment pSegment,
    std::string sourceName,
    bool qualifySourceName)
{
    if (!pTraceTarget.get()) {
        return pSegment;
    }
    if (qualifySourceName) {
        std::ostringstream oss;
        oss << "segment." << sourceName << "." << pSegment.get();
        sourceName = oss.str();
    }
    if (pTraceTarget->getSourceTraceLevel(sourceName) > TRACE_FINE) {
        // all segment tracing is TRACE_FINE or lower, so don't bother
        return pSegment;
    }
    SharedSegment pTracingSegment(
        new TracingSegment(pSegment, pTraceTarget, sourceName),
        ClosableObjectDestructor());

    pSegment->setTracingSegment(WeakSegment(pTracingSegment));

    return pTracingSegment;
}

// TODO:  parameters
SharedSegment SegmentFactory::newTempDeviceSegment(
    SharedCache pCache,
    DeviceMode deviceMode,
    std::string deviceFileName)
{
    // TODO:  guard to automatically deallocateTempDeviceId on failure?
    DeviceId deviceId = allocateTempDeviceId();
    if (deviceMode.create) {
        FileSystem::remove(deviceFileName.c_str());
    }
    // TODO: depending on config params?
    // deviceMode.temporary = true;
    SharedRandomAccessDevice pDevice(
        new RandomAccessFileDevice(deviceFileName, deviceMode));
    pCache->registerDevice(deviceId, pDevice);
    LinearDeviceSegmentParams deviceParams;
    CompoundId::setDeviceId(deviceParams.firstBlockId, deviceId);
    CompoundId::setBlockNum(deviceParams.firstBlockId, 0);
    deviceParams.nPagesAllocated = 0;
    if (!deviceMode.create) {
        deviceParams.nPagesAllocated = MAXU;
    }
    SharedSegment pSegment(
        new LinearDeviceSegment(pCache, deviceParams),
        TempSegDestructor(shared_from_this()));
    SharedSegment tracingSegment =
        newTracingSegment(pSegment, "TempLinearDeviceSegment");
    tracingSegment->initForUse();
    return tracingSegment;
}

DeviceId SegmentFactory::allocateTempDeviceId()
{
    StrictMutexGuard mutexGuard(mutex);
    // TODO:  submit fast find-clear-bit to boost
    for (uint i = 0; i < tempDeviceIdBitset.size(); ++i) {
        if (!tempDeviceIdBitset[i]) {
            tempDeviceIdBitset[i] = true;
            return firstTempDeviceId + i;
        }
    }
    permAssert(false);
}

void SegmentFactory::deallocateTempDeviceId(DeviceId deviceId)
{
    StrictMutexGuard mutexGuard(mutex);
    uint i = opaqueToInt(deviceId - firstTempDeviceId);
    assert(tempDeviceIdBitset[i]);
    tempDeviceIdBitset[i] = false;
}

TempSegDestructor::TempSegDestructor(
    SharedSegmentFactory pSegmentFactoryInit)
    : pSegmentFactory(pSegmentFactoryInit)
{
}

void TempSegDestructor::operator()(Segment *pSegment)
{
    LinearDeviceSegment *pLinearDeviceSegment =
        dynamic_cast<LinearDeviceSegment *>(pSegment);
    SharedCache pCache = pSegment->getCache();
    DeviceId deviceId = pLinearDeviceSegment->getDeviceId();
    // NOTE:  pSegment and pLinearDeviceSegment are invalidated here
    ClosableObjectDestructor::operator()(pSegment);
    pCache->unregisterDevice(deviceId);
    pSegmentFactory->deallocateTempDeviceId(deviceId);
}

SnapshotRandomAllocationSegment *SegmentFactory::getSnapshotSegment(
    SharedSegment pSegment)
{
    SnapshotRandomAllocationSegment *pSnapshotSegment =
        SegmentFactory::dynamicCast<SnapshotRandomAllocationSegment *>(
            pSegment);
    if (pSnapshotSegment == NULL) {
        DynamicDelegatingSegment *pDynamicSegment =
            SegmentFactory::dynamicCast<DynamicDelegatingSegment *>(
                pSegment);
        if (pDynamicSegment != NULL) {
            pSnapshotSegment =
                SegmentFactory::dynamicCast<SnapshotRandomAllocationSegment *>(
                    pDynamicSegment->getDelegateSegment());
        }
    }
    return pSnapshotSegment;
}

FENNEL_END_CPPFILE("$Id$");

// End SegmentFactory.cpp


text:
package main

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"reflect"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"testing"

	"github.com/kyma-project/test-infra/development/gcp/pkg/iam"
	"github.com/kyma-project/test-infra/development/gcp/pkg/pubsub"
	"github.com/kyma-project/test-infra/development/gcp/pkg/secretmanager"
	gcpiam "google.golang.org/api/iam/v1"
	"google.golang.org/api/option"
	gcpsecretmanager "google.golang.org/api/secretmanager/v1"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes/fake"
)

var (
	testingProjectName      = "testing"
	gardenerSecretNamespace = "garden-cluster"
	saSecretLabels          = map[string]string{
		"type":                      "gardener-service-account",
		"kubeconfig-secret":         "kubeconfig-secret",
		"gardener-secret":           "sa-secret",
		"gardener-secret-namespace": gardenerSecretNamespace}
	fakeSAData0 = createFakeServiceAccountJSONData("email", "key0")
	fakeSAData  = createFakeServiceAccountJSONData("email", "key1")
	fakeSAData2 = createFakeServiceAccountJSONData("email", "key2")
)

type fakeKubernetesSecret struct {
	namespace string
	data      map[string][]byte
}

type fakeSecretVersion struct {
	Data  string
	Date  string
	State string
}

func createFakeServiceAccountJSONData(email, key string) string {
	data := iam.ServiceAccountJSON{
		ProjectID:    projectID,
		ClientEmail:  email,
		PrivateKeyID: key,
	}
	dataString, err := json.Marshal(data)
	if err != nil {
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(dataString)
}

type fakeSecret struct {
	Labels   map[string]string
	Versions map[string]*fakeSecretVersion
}

type fakeSecretServer struct {
	secrets                  map[string]*fakeSecret
	unknownEndpointCallCount int
}

// naiveParseLabelFilter fakes filter parsing on server-side.
// Expects filter in labels.name=value format
// returns name, value, error
func naiveParseLabelFilter(filter string) (string, string, error) {
	first, value, equalFilter := strings.Cut(filter, "=")
	if !equalFilter {
		return "", "", errors.New("unexpected filter:" + filter + ", expected = symbol")
	}
	labels, name, twoPartFilter := strings.Cut(first, ".")
	if (labels != "labels") || !twoPartFilter {
		return "", "", errors.New("unexpected filter:" + filter + ", expected = symbol")
	}
	return name, value, nil
}

// naiveParseStateFilter fakes filter parsing on server-side.
// Expects filter in key:value format
// returns key, value, error
func naiveParseSimpleFilter(filter string) (string, string, error) {
	key, value, colonFilter := strings.Cut(filter, ":")
	if !colonFilter {
		return "", "", errors.New("unexpected filter:" + filter + ", expected = symbol")
	}
	return key, value, nil
}

func createSecretName(project, secret string) string {
	return "projects/" + project + "/secrets/" + secret
}

func createSecretVersionName(project, secret, version string) string {
	return createSecretName(project, secret) + "/versions/" + version
}

func (s *fakeSecretServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var err error

	versionsRegex := regexp.MustCompile("/v1/projects/(.*)/secrets/(.*)/versions$")
	versionsLatestRegex := regexp.MustCompile("/v1/projects/(.*)/secrets/(.*)/versions/latest$")
	versionAccessRegex := regexp.MustCompile("/v1/projects/(.*)/secrets/(.*)/versions/(.*):access$")
	versionDestroyRegex := regexp.MustCompile("/v1/projects/(.*)/secrets/(.*)/versions/(.*):destroy$")
	versionAddRegex := regexp.MustCompile("/v1/projects/(.*)/secrets/(.*):addVersion$")

	switch path := r.URL.Path; {
	case path == "/v1/projects/"+testingProjectName+"/secrets":
		{
			filterLabel := ""
			filterLabelValue := ""
			if r.URL.Query().Get("filter") != "" {
				filterLabel, filterLabelValue, err = naiveParseLabelFilter(r.URL.Query().Get("filter"))
				if err != nil {
					http.Error(w, "unable to parse labels filter: "+err.Error(), http.StatusBadRequest)
				}
			}

			resp := gcpsecretmanager.ListSecretsResponse{}
			for name, s := range s.secrets {
				if filterLabel != "" {
					if val, ok := s.Labels[filterLabel]; ok && val != filterLabelValue {
						continue
					}
				}
				resp.Secrets = append(resp.Secrets, &gcpsecretmanager.Secret{Name: createSecretName(testingProjectName, name), Labels: s.Labels})
			}
			b, err := json.Marshal(resp)
			if err != nil {
				http.Error(w, "unable to marshal request: "+err.Error(), http.StatusBadRequest)
				return
			}
			w.Write(b)
		}
	case versionsRegex.MatchString(path):
		{
			versionsResponse := gcpsecretmanager.ListSecretVersionsResponse{}
			// unknown url: /v1/secret_one_version/versions ;Query: filter=state%3Aenabled
			filterKey := ""
			filterValue := ""
			if r.URL.Query().Get("filter") != "" {
				filterKey, filterValue, err = naiveParseSimpleFilter(r.URL.Query().Get("filter"))
				if err != nil {
					http.Error(w, "unable to parse version state filter: "+err.Error(), http.StatusBadRequest)
				}
				if filterKey != "state" {
					http.Error(w, "Bad filter key, expected state, got "+filterKey, http.StatusBadRequest)
				}
			}
			projectName := strings.Split(path, "/")[3]
			secretName := strings.Split(path, "/")[5]
			if secret, ok := s.secrets[secretName]; ok {
				var versionKeys []string
				for versionName := range secret.Versions {
					versionKeys = append(versionKeys, versionName)
				}
				sort.Strings(versionKeys)

				for _, versionName := range versionKeys {
					currentVersion := secret.Versions[versionName]
					if filterValue != "" {
						if currentVersion.State != filterValue {
							continue
						}
					}
					// secret versions are returned in reverse, from latest to oldest
					version := &gcpsecretmanager.SecretVersion{Name: createSecretVersionName(projectName, secretName, versionName), CreateTime: currentVersion.Date, State: currentVersion.State}
					versionsResponse.Versions = append([]*gcpsecretmanager.SecretVersion{version}, versionsResponse.Versions...)
				}
			} else {
				http.Error(w, "unable to find secret: "+secretName, http.StatusBadRequest)
			}

			b, err := json.Marshal(versionsResponse)
			if err != nil {
				http.Error(w, "unable to marshal request: "+err.Error(), http.StatusBadRequest)
				return
			}
			w.Write(b)
		}
	case versionsLatestRegex.MatchString(path):
		{
			var secret *fakeSecret
			var ok bool

			projectName := strings.Split(path, "/")[3]
			secretName := strings.Split(path, "/")[5]
			if secret, ok = s.secrets[secretName]; !ok {
				http.Error(w, "unable to find secret"+secretName, http.StatusBadRequest)
				return
			}
			var versionKeys []string
			for versionName := range secret.Versions {
				versionKeys = append(versionKeys, versionName)
			}
			sort.Strings(versionKeys)

			versionName := versionKeys[len(versionKeys)-1]

			latestVersion := secret.Versions[versionName]

			version := &gcpsecretmanager.SecretVersion{Name: createSecretVersionName(projectName, secretName, versionName), CreateTime: latestVersion.Date, State: latestVersion.State}
			b, err := json.Marshal(version)
			if err != nil {
				http.Error(w, "unable to marshal request: "+err.Error(), http.StatusBadRequest)
				return
			}
			w.Write(b)
		}
	case versionAccessRegex.MatchString(path):
		{
			projectName := strings.Split(path, "/")[3]
			secretName := strings.Split(path, "/")[5]
			versionNameRaw := strings.Split(path, "/")[7]
			versionName := strings.Split(versionNameRaw, ":")[0]

			var version *fakeSecretVersion

			secret, ok := s.secrets[secretName]
			if !ok {
				http.Error(w, "unable to find secret: "+secretName, http.StatusBadRequest)
				return
			}
			if versionName == "latest" {
				var versionKeys []string
				for versionName := range secret.Versions {
					versionKeys = append(versionKeys, versionName)
				}
				sort.Strings(versionKeys)

				if len(versionKeys) > 0 {
					versionName = versionKeys[len(versionKeys)-1]
				}
			}

			version, ok = secret.Versions[versionName]
			if !ok {
				http.Error(w, "unable to find secret "+secretName+" version "+versionName, http.StatusBadRequest)
				return
			}

			payload := gcpsecretmanager.SecretPayload{Data: version.Data}
			versionResponse := gcpsecretmanager.AccessSecretVersionResponse{Name: createSecretVersionName(projectName, secretName, versionName), Payload: &payload}
			b, err := json.Marshal(versionResponse)
			if err != nil {
				http.Error(w, "unable to marshal request: "+err.Error(), http.StatusBadRequest)
				return
			}
			w.Write(b)
		}
	case versionDestroyRegex.MatchString(path):
		{
			// projectName := strings.Split(path, "/")[3]
			secretName := strings.Split(path, "/")[5]
			versionNameRaw := strings.Split(path, "/")[7]
			versionName := strings.Split(versionNameRaw, ":")[0]

			ver := s.secrets[secretName].Versions[versionName]
			ver.State = "DESTROYED"

			b, err := json.Marshal(ver)
			if err != nil {
				http.Error(w, "unable to marshal request: "+err.Error(), http.StatusBadRequest)
				return
			}
			w.Write(b)
		}
	case versionAddRegex.MatchString(path):
		{
			projectName := strings.Split(path, "/")[3]
			secretNameRaw := strings.Split(path, "/")[5]
			secretName := strings.Split(secretNameRaw, ":")[0]

			data, err := io.ReadAll(r.Body)
			if err != nil {
				http.Error(w, "unable to read request: "+err.Error(), http.StatusBadRequest)
				return
			}

			var unpackedData gcpsecretmanager.AddSecretVersionRequest
			err = json.Unmarshal(data, &unpackedData)
			if err != nil {
				http.Error(w, "unable to unmarshal request: "+err.Error(), http.StatusBadRequest)
				return
			}

			var versions []string
			for versionName := range s.secrets[secretName].Versions {
				versions = append(versions, versionName)
			}
			sort.Strings(versions)

			lastVersion, err := strconv.Atoi(versions[len(versions)-1])
			if err != nil {
				http.Error(w, "unable to convert string to int: "+err.Error(), http.StatusBadRequest)
				return
			}
			newVersionName := strconv.Itoa(lastVersion + 1)
			unpackedPayload, err := base64.StdEncoding.DecodeString(unpackedData.Payload.Data)
			if err != nil {
				http.Error(w, "unable to decode base64: "+err.Error(), http.StatusBadRequest)
				return
			}

			s.secrets[secretName].Versions[newVersionName] = &fakeSecretVersion{Data: string(unpackedPayload), Date: "", State: "ENABLED"}

			secretVersion := &gcpsecretmanager.SecretVersion{Name: createSecretVersionName(projectName, secretName, newVersionName), CreateTime: "", State: "ENABLED"}
			b, err := json.Marshal(secretVersion)
			if err != nil {
				http.Error(w, "unable to marshal request: "+err.Error(), http.StatusBadRequest)
				return
			}
			w.Write(b)

		}
	default:
		{
			fmt.Printf("unknown url: %s ;Query: %s ;Body: %s; %s\n", r.URL.Path, r.URL.Query().Encode(), r.Body, r.Method)
			http.Error(w, "unknown URL: "+r.URL.Path, 500)
			s.unknownEndpointCallCount++
		}
	}
}

type fakeIAMServer struct {
	keys                     map[string]map[string]bool
	unknownEndpointCallCount int
}

func (s *fakeIAMServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	keysPathRegex := regexp.MustCompile("/v1/projects/(.*)/serviceAccounts/(.*)/keys$")
	keyPathRegex := regexp.MustCompile("/v1/projects/(.*)/serviceAccounts/(.*)/keys/(.*)$")
	switch path := r.URL.Path; {
	case keysPathRegex.MatchString(path):
		{
			projectName := strings.Split(path, "/")[3]
			serviceAccountName := strings.Split(path, "/")[5]

			keyID := "key2"

			s.keys[serviceAccountName][keyID] = true

			newKey := gcpiam.ServiceAccountKey{
				Name:           "projects/" + projectName + "/serviceAccounts/" + serviceAccountName + "/keys/" + keyID,
				PrivateKeyData: base64.StdEncoding.EncodeToString([]byte(fakeSAData2)),
			}

			b, err := json.Marshal(newKey)
			if err != nil {
				http.Error(w, "unable to marshal request: "+err.Error(), http.StatusBadRequest)
				return
			}
			w.Write(b)
		}
	case keyPathRegex.MatchString(path):
		{
			if r.Method != "DELETE" {
				return
			}
			// projectName := strings.Split(path, "/")[3]
			serviceAccountName := strings.Split(path, "/")[5]
			keyName := strings.Split(path, "/")[7]

			if _, ok := s.keys[serviceAccountName]; !ok {
				fmt.Printf("unable to find service account %s\n", serviceAccountName)
				// don't return here, as the function can still delete secret version even if the key was deleted manually
			}

			delete(s.keys[serviceAccountName], keyName)

			b, err := json.Marshal(gcpiam.Empty{})
			if err != nil {
				http.Error(w, "unable to marshal request: "+err.Error(), http.StatusBadRequest)
				return
			}
			w.Write(b)
		}
	default:
		{
			fmt.Printf("unknown url: %s ;Query: %s ;Body: %s; %s\n", r.URL.Path, r.URL.Query().Encode(), r.Body, r.Method)
			http.Error(w, "unknown URL: "+r.URL.Path, 500)
			s.unknownEndpointCallCount++
		}
	}
}

func TestRotateGardenerServiceAccount(t *testing.T) {
	var err error
	ctx := context.Background()
	projectID = testingProjectName

	kubeconfigSecret := &fakeSecret{Versions: map[string]*fakeSecretVersion{"1": {Data: base64.StdEncoding.EncodeToString([]byte("data")), State: "ENABLED"}}}

	tests := []struct {
		name string

		keys                      map[string]map[string]bool
		expectedKeys              map[string]map[string]bool
		secrets                   map[string]*fakeSecret
		expectedSecrets           map[string]*fakeSecret
		kuberentesSecrets         map[string]fakeKubernetesSecret
		expectedKuberentesSecrets map[string]fakeKubernetesSecret

		requestBody        pubsub.Message
		requestMessageData pubsub.SecretRotateMessage
		expectedResponse   string
	}{
		{
			name: "One old enabled SA",

			secrets: map[string]*fakeSecret{
				"sa-secret":         {Labels: saSecretLabels, Versions: map[string]*fakeSecretVersion{"1": {Data: fakeSAData, State: "ENABLED"}}},
				"kubeconfig-secret": kubeconfigSecret,
			},
			expectedSecrets: map[string]*fakeSecret{
				"sa-secret":         {Labels: saSecretLabels, Versions: map[string]*fakeSecretVersion{"1": {Data: fakeSAData, State: "DESTROYED"}, "2": {Data: fakeSAData2, State: "ENABLED"}}},
				"kubeconfig-secret": kubeconfigSecret,
			},
			keys:         map[string]map[string]bool{"email": {"key1": true}},
			expectedKeys: map[string]map[string]bool{"email": {"key2": true}},

			kuberentesSecrets:         map[string]fakeKubernetesSecret{"sa-secret": {namespace: gardenerSecretNamespace, data: map[string][]byte{"serviceaccount.json": []byte(fakeSAData)}}},
			expectedKuberentesSecrets: map[string]fakeKubernetesSecret{"sa-secret": {namespace: gardenerSecretNamespace, data: map[string][]byte{"serviceaccount.json": []byte(fakeSAData2)}}},
			requestBody:               pubsub.Message{Message: pubsub.MessagePayload{Attributes: map[string]string{"eventType": "SECRET_ROTATE"}}},
			requestMessageData:        pubsub.SecretRotateMessage{Name: createSecretName(testingProjectName, "sa-secret"), Labels: saSecretLabels},
		},
		{
			name: "One destroyed, one old enabled SA",

			secrets: map[string]*fakeSecret{
				"sa-secret":         {Labels: saSecretLabels, Versions: map[string]*fakeSecretVersion{"1": {Data: fakeSAData0, State: "DESTROYED"}, "2": {Data: fakeSAData, State: "ENABLED"}}},
				"kubeconfig-secret": kubeconfigSecret,
			},
			expectedSecrets: map[string]*fakeSecret{
				"sa-secret":         {Labels: saSecretLabels, Versions: map[string]*fakeSecretVersion{"1": {Data: fakeSAData0, State: "DESTROYED"}, "2": {Data: fakeSAData, State: "DESTROYED"}, "3": {Data: fakeSAData2, State: "ENABLED"}}},
				"kubeconfig-secret": kubeconfigSecret,
			},
			keys:         map[string]map[string]bool{"email": {"key1": true}},
			expectedKeys: map[string]map[string]bool{"email": {"key2": true}},

			kuberentesSecrets:         map[string]fakeKubernetesSecret{"sa-secret": {namespace: gardenerSecretNamespace, data: map[string][]byte{"serviceaccount.json": []byte(fakeSAData)}}},
			expectedKuberentesSecrets: map[string]fakeKubernetesSecret{"sa-secret": {namespace: gardenerSecretNamespace, data: map[string][]byte{"serviceaccount.json": []byte(fakeSAData2)}}},
			requestBody:               pubsub.Message{Message: pubsub.MessagePayload{Attributes: map[string]string{"eventType": "SECRET_ROTATE"}}},
			requestMessageData:        pubsub.SecretRotateMessage{Name: createSecretName(testingProjectName, "sa-secret"), Labels: saSecretLabels},
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			secretServerStruct := fakeSecretServer{secrets: test.secrets}

			secretServer := httptest.NewServer(&secretServerStruct)
			secretManagerService, err = secretmanager.NewService(ctx, option.WithoutAuthentication(), option.WithEndpoint(secretServer.URL))
			if err != nil {
				t.Errorf("Couldn't set up fake secretmanager: %s", err)
			}

			iamServerStruct := fakeIAMServer{keys: test.keys}
			iamServer := httptest.NewServer(&iamServerStruct)
			serviceAccountService, err = iam.NewService(ctx, option.WithoutAuthentication(), option.WithEndpoint(iamServer.URL))
			if err != nil {
				t.Errorf("Couldn't set up fake serviceaccountmanager: %s", err)
			}

			kubernetesClient = fake.NewSimpleClientset()

			for gardenerSecretName, gardenerSecret := range test.kuberentesSecrets {
				meta := metav1.ObjectMeta{Name: gardenerSecretName, Namespace: gardenerSecret.namespace}
				secret := &v1.Secret{Type: "Opaque", Data: gardenerSecret.data, ObjectMeta: meta}
				kubernetesClient.CoreV1().Secrets(gardenerSecretNamespace).Create(ctx, secret, metav1.CreateOptions{})
			}

			rr := httptest.NewRecorder()

			secretRotateMessageByte, err := json.Marshal(test.requestMessageData)
			if err != nil {
				t.Errorf("Couldn't marshall Secret Manager message: %s", err)
			}
			test.requestBody.Message.Data = secretRotateMessageByte

			pubsubMessageByte, err := json.Marshal(test.requestBody)
			if err != nil {
				t.Errorf("Couldn't marshall pubsub message: %s", err)
			}

			req := httptest.NewRequest("GET", "/", strings.NewReader(string(pubsubMessageByte)))
			req.Header.Add("Content-Type", "application/json")

			RotateGardenerServiceAccount(rr, req)

			if got := rr.Body.String(); got != test.expectedResponse {
				t.Errorf("ServiceAccountCleaner(%q) = %q, want %q", test.requestBody, got, test.expectedResponse)
			}

			if !reflect.DeepEqual(test.keys, test.expectedKeys) {
				t.Errorf("List of expected keys differs, %v, want %v", test.keys, test.expectedKeys)
			}

			if !reflect.DeepEqual(test.secrets, test.expectedSecrets) {
				t.Errorf("List of expected secrets differs, %v, want %v", test.secrets, test.expectedSecrets)
			}

			// todo copmpare kubernetes secrets

			test.kuberentesSecrets = make(map[string]fakeKubernetesSecret)
			kubernetesSecrets, err := kubernetesClient.CoreV1().Secrets(gardenerSecretNamespace).List(ctx, metav1.ListOptions{})
			if err != nil {
				t.Errorf("Couldn't get list of Gardener secrets: %s", err)
			}
			for _, ks := range kubernetesSecrets.Items {
				// decodedData, err := base64.RawStdEncoding.DecodeString(string(ks.Data[]))
				test.kuberentesSecrets[ks.Name] = fakeKubernetesSecret{namespace: ks.Namespace, data: ks.Data}
			}

			if !reflect.DeepEqual(test.kuberentesSecrets, test.expectedKuberentesSecrets) {
				t.Errorf("List of expected Kubernetes secrets differs, %v, want %v", test.kuberentesSecrets, test.expectedKuberentesSecrets)
			}
		})
	}
}


text:
package org.bouncycastle.its;

import org.bouncycastle.oer.its.ieee1609dot2.EncryptedDataEncryptionKey;

public interface ETSIKeyWrapper
{
    EncryptedDataEncryptionKey wrap(byte[] secretKey);
}


text:
var root = '../../../';
var User = require(root+'podrick/models/user');

function UserBuilder() {
    this.username = '';
    this.team = '';
}

UserBuilder.Object = User;

UserBuilder.prototype.withUsername = function(username) {
    this.username = username;
    return this;
};

UserBuilder.prototype.withTeam = function(team) {
    this.team = team;
    return this;
};

UserBuilder.prototype.build = function() {
    return new UserBuilder.Object({username: this.username, team: this.team});
};

module.exports = UserBuilder;


text:
Iris ChangeLog
================

# Version 0.2.0 (10/12/2015)

- Setup continuous integration using cAdvisor Docker image

# Version 0.1.0 (09/10/2015)

- cAdvisor client


text:
describe('check if plugin setup ran', function() {
  it('should have set protractor.__BASIC_PLUGIN_RAN', function() {
    expect(protractor.__BASIC_PLUGIN_RAN).toBe(true);
  });
});


text:
package org.elasticsearch.cluster.coordination;

import io.crate.common.collections.Tuple;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.gateway.PersistedClusterStateService;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

public class RemoveSettingsCommand extends ElasticsearchNodeCommand {

    static final String SETTINGS_REMOVED_MSG = "Settings were successfully removed from the cluster state";
    static final String CONFIRMATION_MSG =
        DELIMITER +
        "\n" +
        "You should only run this tool if you have incompatible settings in the\n" +
        "cluster state that prevent the cluster from forming.\n" +
        "This tool can cause data loss and its use should be your last resort.\n" +
        "\n" +
        "Do you want to proceed?\n";

    private final OptionSpec<String> arguments;

    public RemoveSettingsCommand() {
        super("Removes persistent settings from the cluster state");
        arguments = parser.nonOptions("setting names");
    }

    @Override
    protected void processNodePaths(Terminal terminal, Path[] dataPaths, OptionSet options, Environment env)
        throws IOException, UserException {
        final List<String> settingsToRemove = arguments.values(options);
        if (settingsToRemove.isEmpty()) {
            throw new UserException(ExitCodes.USAGE, "Must supply at least one setting to remove");
        }

        final PersistedClusterStateService persistedClusterStateService = createPersistedClusterStateService(env.settings(), dataPaths);

        terminal.println(Terminal.Verbosity.VERBOSE, "Loading cluster state");
        final Tuple<Long, ClusterState> termAndClusterState = loadTermAndClusterState(persistedClusterStateService, env);
        final ClusterState oldClusterState = termAndClusterState.v2();
        final Settings oldPersistentSettings = oldClusterState.metadata().persistentSettings();
        terminal.println(Terminal.Verbosity.VERBOSE, "persistent settings: " + oldPersistentSettings);
        final Settings.Builder newPersistentSettingsBuilder = Settings.builder().put(oldPersistentSettings);
        for (String settingToRemove : settingsToRemove) {
            boolean matched = false;
            for (String settingKey : oldPersistentSettings.keySet()) {
                if (Regex.simpleMatch(settingToRemove, settingKey)) {
                    newPersistentSettingsBuilder.remove(settingKey);
                    if (matched == false) {
                        terminal.println("The following settings will be removed:");
                    }
                    matched = true;
                    terminal.println(settingKey + ": " + oldPersistentSettings.get(settingKey));
                }
            }
            if (matched == false) {
                throw new UserException(ExitCodes.USAGE,
                                        "No persistent cluster settings matching [" + settingToRemove + "] were found on this node");
            }
        }
        final ClusterState newClusterState = ClusterState.builder(oldClusterState)
            .metadata(Metadata.builder(oldClusterState.metadata()).persistentSettings(newPersistentSettingsBuilder.build()).build())
            .build();
        terminal.println(Terminal.Verbosity.VERBOSE,
                         "[old cluster state = " + oldClusterState + ", new cluster state = " + newClusterState + "]");

        confirm(terminal, CONFIRMATION_MSG);

        try (PersistedClusterStateService.Writer writer = persistedClusterStateService.createWriter()) {
            writer.writeFullStateAndCommit(termAndClusterState.v1(), newClusterState);
        }

        terminal.println(SETTINGS_REMOVED_MSG);
    }
}


text:
FROM centos:7

ARG GIT_COMMIT_HASH
ARG VERSION

LABEL org.metadata.version=$VERSION \
	   org.metadata.name="Devops Base Image" \
	   org.metadata.description="A base image for personalized docker environments with several devopsy tools installed." \
	   org.metadata.url="https://github.com/dan9186/docker-devopsbase" \
	   org.metadata.vcs-url="https://github.com/dan9186/docker-devopsbase" \
	   org.metadata.vcs-sha=$GIT_COMMIT_HASH

# Add repos
RUN rpm -Uvh https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm

# Install Packages
RUN yum -y install epel-release && \
    yum -y update && \
    yum -y upgrade && \
    yum install -y \
					ack autoconf automake \
					bind-utils bison bzip2 bzr \
					cmake curl \
					file-devel \
					jq \
					libcurl-devel libffi-devel libicu-devel libpqxx-devel libtool libxml2-devel libxslt-devel libyaml-devel libtool-ltdl-devel \
					gcc-c++ git \
					make man maven mercurial \
					nmap nmap-ncat nodejs npm net-tools \
					patch postgresql96-devel postgresql-devel python-devel python-pip \
					readline-devel \
					sqlite-devel \
					tar \
					unzip \
					vim \
					wget \
					xmlsec1-openssl-devel \
					&& \
    yum clean all

WORKDIR /tmp

# Install Golang
COPY --from=golang:stretch /usr/local/go /usr/local/go
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $PATH:$GOROOT/bin:$GOPATH/bin
RUN mkdir /go

# Upgrade Pip
RUN pip install --upgrade pip

# Install RVM
ENV RVM_VERSION 1.29.9
RUN gpg --keyserver hkp://keys.gnupg.net --recv-keys D39DC0E3 && \
    wget "https://github.com/rvm/rvm/archive/$RVM_VERSION.tar.gz" && \
    tar xvf "$RVM_VERSION.tar.gz" && \
    cd "rvm-$RVM_VERSION" && \
    ./install && \
    cd /tmp && \
    rm -rf "$RVM_VERSION.tar.gz" "rvm-$RVM_VERSION" && \
    echo "bundler" >> /usr/local/rvm/gemsets/global.gems

# Install Python Items
RUN pip install awscli

# Install NPM Items
RUN npm install -g \
	less

WORKDIR /


text:
package uk.ac.ncl.openlab.intake24.foodsql.user

import javax.inject.Inject
import javax.sql.DataSource
import anorm.NamedParameter.symbol
import anorm.{~, SQL, SqlParser, sqlToSimple}
import com.google.inject.Singleton
import com.google.inject.name.Named
import uk.ac.ncl.openlab.intake24.errors.{LookupError, RecordNotFound}
import uk.ac.ncl.openlab.intake24.services.fooddb.user.{GuideImageService, UserGuideImage}
import uk.ac.ncl.openlab.intake24.sql.{SqlDataService, SqlResourceLoader}

@Singleton
class GuideImageServiceImpl @Inject()(@Named("intake24_foods") val dataSource: DataSource) extends GuideImageService with SqlDataService with SqlResourceLoader {

  def getGuideImage(id: String): Either[LookupError, UserGuideImage] = tryWithConnection {
    implicit conn =>
      withTransaction {
        SQL("select description, image_map_id from guide_images where id={id}")
          .on('id -> id)
          .executeQuery()
          .as((SqlParser.str(1) ~ SqlParser.str(2)).singleOpt) match {
          case Some(description ~ imageMapId) =>

            val objects = SQL("select image_map_object_id, weight from guide_image_objects where guide_image_id={id}")
              .on('id -> id)
              .executeQuery()
              .as((SqlParser.int(1) ~ SqlParser.double(2)).*).foldLeft(Map[Int, Double]()) {
              case (result, objectId ~ weight) => result + (objectId -> weight)
            }

            Right(UserGuideImage(description, imageMapId, objects))

          case None =>
            Left(RecordNotFound(new RuntimeException(s"Guide image $id not found")))
        }
      }
  }
}


text:
interface StorageInterface {
  getItem(key: string): Promise<any>;
  removeItem(key: string): Promise<void>;
  setItem(key: string, value: any): Promise<void>;
}

export const localStorage: StorageInterface;
export const syncStorage: StorageInterface;
export {};


text:
namespace Switch {
  namespace System {
    class Type;
    class Object;
  }
}

namespace __s__ {
  template<typename T>
  Switch::System::Type __typeof_();

  template<typename T>
  Switch::System::Type __typeof_(const T& value);
}
/// @endcond

/// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace Switch {
  /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
  namespace System {
    /// @brief Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.
    /// @par Library
    /// Switch.Core
    class core_export_ Type : public Object {
    public:
      /// @cond
      Type(const Type& type);
      /// @endcond

      /// @brief Gets the fully qualified name of the Type, including the namespace of the Type.
      /// @return The fully qualified name of the Type, including the namespace of the Type.
      /// @remarks For example, the fully qualified name of the String type is String.
      property_<String, readonly_> FullName;

      /// @brief Gets the name of the Type.
      /// @return The name of the Type.
      /// @remarks For example, the name of the String type is String.
      property_<String, readonly_> Name;

      /// @brief Gets the namespace of the Type.
      /// @return The namespace of the Type.
      /// @remarks For example, the namespace of the String type is System::
      property_<String, readonly_> Namespace;

      /// @brief Determines whether the specified Object is equal to the current Object.
      /// @param obj The Object to compare with the current Object.
      /// @return bool true if the specified Object is equal to the current Object. otherwise, false.
      bool Equals(const Object& obj) const override;

      /// @brief Determines whether the specified Type is equal to the current Type.
      /// @param type The Type to compare with the current Object.
      /// @return bool true if the specified type is equal to the current Type. otherwise, false.
      bool Equals(const Type& type) const;

      /// @brief Gets the underlying type code of the specified Type
      /// @param value The value of type whose underlying type code to get.
      /// @return The code of the underlying type, or Empty if type is null.
      template<typename T>
      static TypeCode GetTypeCode(const T& value) {
        if (!is<IConvertible>(value))
          return TypeCode::Object;
        return dynamic_cast<const IConvertible&>(value).GetTypeCode();
      }

      template<typename T>
      static bool IsComparable(T value) {return is<IComparable>(value);}

      template<typename T, class TT>
      static bool IsInstanceOfType(TT value) {return is<T>(value);}

      template<typename T>
      static bool IsValueType(T obj) {return is<ValueType>(obj);}

      /// @brief Returns a String representing the name of the current Type.
      /// @return A String representing the name of the current Type.
      String ToString() const override;

    private:
      String GetFullName() const;
      String GetName() const;
      String GetNamespace() const;

      template<typename T>
      friend Type __s__::__typeof_();
      template<typename T>
      friend Type __s__::__typeof_(const T& value);
      friend class Object;

      Type();
      Type(const std::type_info& type);
      Type& operator=(const Type& type);

      const std::type_info& type;
    };
  }
}

/// @cond
namespace __s__ {
  template<typename T>
  Switch::System::Type __typeof_() {
    return System::Type(typeid(T));
  }

  template<typename T>
  Switch::System::Type __typeof_(const T& value) {
    return System::Type(typeid(value));
  }
}
/// @endcond

/// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace Switch {
  /// @brief Used to obtain the type Object for a type. A typeof_ expression takes the following form:
  /// @par Library
  /// Switch.Core
  /// @par Examples
  /// @code
  /// Type type1 = typeof_<Int32>();
  ///
  /// Int32 i = 42;
  /// Type type2 = typeof_(i);
  /// @endcode
  /// @par Examples
  /// To obtain the run-time type of an expression, you can use the Switch method GetType, as in the following example:
  /// @code
  /// Int32 42 = 0;
  /// System::Type Type = i.GetType();
  /// @endcode
  /// @remarks The typeof_ operator cannot be overloaded.
  /// @see System::Type
  /// @ingroup Keywords
#define typeof_  \
  __s__::__typeof_
}

using namespace Switch;


text:
project_path: /web/_project.yaml
book_path: /web/shows/_book.yaml
description: Kent Tamura & Doug Stockwell give an update on the state of Chrome's rendering engine Blink.

{# wf_updated_on: 2015-05-12 #}
{# wf_published_on: 2015-05-12 #}
{# wf_youtube_id: Ap5sWqtCE2o #}

# State of Blink {: .page-title }

<div class="video-wrapper">
  <iframe class="devsite-embedded-youtube-video" data-video-id="Ap5sWqtCE2o"
          data-autohide="1" data-showinfo="0" frameborder="0" allowfullscreen>
  </iframe>
</div>

Kent Tamura & Doug Stockwell give an update on the state of Chrome's rendering engine Blink.


text:
<!DOCTYPE html>

    <title>JavaScript & jQuery - Chapter 13: Form Enhancement and Validation - Changing the type of a Form Input</title>
    <link rel="stylesheet" href="css/c13.css" />

      <form name="login" action="/login/" method="post">

          <fieldset>
            <legend>Login</legend>
            Username:
            <input type="text" id="username" name="username" />
            Password:
            <input type="password" id="pwd" name="pwd" />

            <input type="checkbox" id="showPwd">
            show password
            <input type="submit" value="Login" />
          </fieldset>

      </form>


text:
'''
    Copyright (C) 2008 10gen Inc.

    This program is free software: you can redistribute it and/or  modify
    it under the terms of the GNU Affero General Public License, version 3,
    as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import _10gen
from _10gen import jsMap
assert jsMap.has_key('a')
assert jsMap.has_key('b')
assert jsMap.has_key('n')
assert not jsMap.has_key('c')

assert 'a' in jsMap
assert 'b' in jsMap
assert 'n' in jsMap
assert 'c' not in jsMap

d = jsMap.copy()
_10gen.assert.eq(len(jsMap.keys()), len(d.keys()))
_10gen.assert.eq(len(jsMap), len(d))

_10gen.assert.eq(d['a'], jsMap.a)
_10gen.assert.eq(d['a'], jsMap['a'])
_10gen.assert.eq(d['n'], jsMap.n)
_10gen.assert.eq(d['n'], jsMap['n'])

def compare_list_methods_by_sorted(d, j, meth):
    d_result = list(getattr(d, meth)())
    j_result = list(getattr(j, meth)())
    d_result.sort()
    j_result.sort()
    _10gen.assert.eq(d_result, j_result)

compare_list_methods_by_sorted(d, jsMap, 'iteritems')
compare_list_methods_by_sorted(d, jsMap, 'keys')
compare_list_methods_by_sorted(d, jsMap, 'values')
compare_list_methods_by_sorted(d, jsMap, 'iterkeys')

_10gen.assert.eq(jsMap.get('a'), jsMap['a'])
_10gen.assert.eq(jsMap.get('a', 'default'), jsMap['a'])
_10gen.assert.eq(jsMap.get('zzz', 'default'), 'default')
_10gen.assert.eq(jsMap.get(dict(), 'default'), 'default')

# not implemented yet
#compare_list_methods_by_sorted(d, jsMap, 'items')
_10gen.assert.throws(lambda:
                     compare_list_methods_by_sorted(d, jsMap, 'items'))
#compare_list_methods_by_sorted(d, jsMap, 'itervalues')
_10gen.assert.throws(lambda:
                     compare_list_methods_by_sorted(d, jsMap, 'itervalues'))

# not implemented yet
_10gen.assert.throws(lambda: jsMap.setdefault('a', 9))
#_10gen.assert.eq(jsMap.setdefault('a', 9), jsMap['a'])
#_10gen.assert.eq(jsMap.setdefault('d', 9), 9)
#_10gen.assert.eq(jsMap.setdefault('d', 10), jsMap['d'])
#_10gen.assert.throws(lambda: jsMap.setdefault([], 9))  # can't store non-strings

_10gen.assert.throws(lambda: jsMap.popitem())

_10gen.assert.throws(lambda: jsMap.pop('d', 'default'))
#_10gen.assert.eq(jsMap.pop('zzz', 'default'), 'default')
#_10gen.assert.eq(jsMap.pop('d', 'zig'), 9)
#_10gen.assert.eq(jsMap.pop('d', 'zig'), 'zig')

jsMap.update({'g': 91})
_10gen.jsCheck(jsMap, 'g', 91)

jsMap.update(h=99)
_10gen.jsCheck(jsMap, 'h', 99)

d = jsMap.copy()
oldSize = len(jsMap)
# not implemented yet
#jsMap.clear()
_10gen.assert.throws(lambda: jsMap.clear())
#_10gen.assert.eq(len(jsMap.keys()), 0)
#_10gen.assert.eq(len(jsMap), 0)
_10gen.assert.eq(oldSize, len(d))

# I can't think of a use case for this, so that it's broken is fine
_10gen.assert.throws(lambda: jsMap.fromkeys(['a', 'b', 'c'], 24))


text:
package edu.wustl.xipHost.gui;

import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class PathChooser {

	protected File selectedPath;
	JFileChooser fc = new JFileChooser();
	String strPath = new String();
	//String strOutOK = new String();
	//String strTmpCancel = new String();

	public void displayPathChooser (String path){
		strPath = path;
		fc.setApproveButtonText("Select");
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		//fc.setMultiSelectionEnabled(false);
		try {
			//fc.setCurrentDirectory(new File(new File(".").getCanonicalPath()));
			fc.setCurrentDirectory(new File(new File(path).getCanonicalPath()));
		} catch (IOException e) {
			e.printStackTrace();
		}

	    JFrame frame = new JFrame();
	    int result = fc.showOpenDialog(frame);

	    switch (result) {
	    case JFileChooser.APPROVE_OPTION:
	    	//selectedPath = fc.getCurrentDirectory().getPath();
	    	selectedPath = fc.getSelectedFile();
	    	strPath = selectedPath.getAbsolutePath();
	      break;
	    case JFileChooser.CANCEL_OPTION:
	    	//strPath = strPath;
	    	selectedPath = new File(strPath);
	      break;
	    case JFileChooser.ERROR_OPTION:
	      // The selection process did not complete successfully
	      break;
		}
	}

	public File getSelectedPath(){
		return selectedPath;
	}

}


text:
package com.erigitic.shops.data;

import com.erigitic.shops.ShopItem;
import java.util.Optional;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.key.Key;
import org.spongepowered.api.data.manipulator.immutable.common.AbstractImmutableSingleData;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.api.data.value.immutable.ImmutableValue;

public class ImmutableShopItemData extends AbstractImmutableSingleData<ShopItem, ImmutableShopItemData, ShopItemData> {

    public ImmutableShopItemData(ShopItem shopItem) {
        super(shopItem, ShopKeys.SHOP_ITEM);
    }

    @Override
    public ShopItemData asMutable() {
        return new ShopItemData(getValue());
    }

    @Override
    public int getContentVersion() {
        return ShopItemData.CONTENT_VERSION;
    }

    @Override
    protected ImmutableValue<?> getValueGetter() {
        return Sponge.getRegistry().getValueFactory().createValue(ShopKeys.SHOP_ITEM, getValue()).asImmutable();
    }

    @Override
    public <E> Optional<ImmutableShopItemData> with(Key<? extends BaseValue<E>> key, E value) {
        if (this.supports(key)) {
            return Optional.of(asMutable().set(key, value).asImmutable());
        } else {
            return Optional.empty();
        }
    }
}


text:
Code sharing for Userlite developers.

Allow Userlite developers to connect to the staging environment and synchronize their local code base with the development server.

Features include:

- Code synchronization across all assigned developers
- Lightning fast saves to the staging environment
- Interaction with other connected developers (see who's connected, send open files, request pair programming session)
- Dynamically updated editor buffers for interactive pair programming
- Automatic file versioning and diff calculation
- Integrated file version lookup and restore
- See backtrace of staging environment errors directly in atom with the ability to click into trace files


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/2002/08/xhtml/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/1999/xhtml
                          http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	    <title>
	    	<wicket:message key="dashboard.application.browser_title">
	    		[Dashboard]
			</wicket:message>
		</title>
	</head>
	<body>
		<wicket:panel>
			<div class="filesystem" style="clear: both; margin-top: 9px;">
				<div wicket:id="filesystem-tree-table" />
			</div>
		</wicket:panel>
	</body>
</html>


text:
using JetBrains.ReSharper.FeaturesTestFramework.Intentions;
using JetBrains.ReSharper.TestFramework;
using NUnit.Framework;
using ReCommendedExtension.ContextActions.CodeContracts;

namespace ReCommendedExtension.Tests.ContextActions.CodeContracts.Types
{
    [TestNetFramework4]
    [TestFixture]
    public sealed class TimeSpanNonZeroAvailabilityTests : CSharpContextActionAvailabilityTestBase<TimeSpanNonZero>
    {
        protected override string ExtraPath => "";

        protected override string RelativeTestDataPath => @"ContextActions\CodeContracts\Types\TimeSpanNonZero";

        [Test]
        public void TestAvailability() => DoNamedTest2();
    }
}