text:
<?php

namespace Dezull\Bundle\HelpBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('dezull_help');

        $rootNode
            ->children()
                ->scalarNode('topic_type')
                    ->defaultValue('Dezull\Bundle\HelpBundle\Form\HelpTopicType')
                ->end()
            ->end()
            ->children()
                ->scalarNode('content_editor_width')
                    ->defaultValue('400')
                ->end()
            ->end()
            ->children()
                ->scalarNode('content_editor_height')
                    ->defaultValue('150')
                ->end()
            ->end()
            ->children()
                ->scalarNode('content_editor_language')
                    ->defaultValue('en_uk')
                ->end()
            ->end()
            ->children()
                ->scalarNode('image_upload_url')
                    ->defaultValue('dezull_help_topic_image_upload')
                ->end()
            ->end()
            ->children()
                ->scalarNode('image_dir')
                    ->defaultValue('%kernel.root_dir%/../web/upload/help')
                ->end()
            ->end()
            ->children()
                ->scalarNode('image_baseurl')
                    ->defaultValue('/upload/help')
                ->end()
            ->end()
            ->children()
                ->variableNode('image_mimetypes')
                    ->defaultValue(array(
                        'image/png',
                        'image/jpeg',
                        'image/gif',
                    ))
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}


text:
# Colback.js

**Colback.js** is a JavaScript library aiming at providing simple utilities to shift asynchronous functions from one paradigm to the other.

Full documentation is available [here](http://yomguithereal.github.io/colback/).

## Contribution

[![Build Status](https://travis-ci.org/Yomguithereal/colback.svg)](https://travis-ci.org/Yomguithereal/colback)

Contributions are more than welcome. Just remember to add and pass relevant unit tests before submitting any changes.

```bash
# Installing package dependencies
npm install

# Running tests
npm test
```

redpajama_set_name: RedPajamaGithub


text:
package org.aries.tx;

import javax.management.ObjectName;

import org.aries.util.concurrent.FutureResult;

public abstract class AbstractJMSHandlerArquillionTest extends AbstractServiceSideArquillionTest {

	public abstract String getServiceId();

	public abstract String getTargetArchive();

	protected String username;

	protected String password;

	protected String providerUrl;

	public String getUserName() {
		return username;
	}

	public void setUserName(String userName) {
		this.username = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getProviderUrl() {
		return providerUrl;
	}

	public void setProviderUrl(String providerUrl) {
		this.providerUrl = providerUrl;
	}

	public void setUp() throws Exception {
		super.setUp();
	}

	/*
	 * Runtime support
	 */

	protected FutureResult<Object> registerForResult() throws Exception {
		return registerForResult(getServiceId());
	}

	/*
	 * JMX related calls
	 */

	public void clearContext(String mbeanName) throws Exception {
		ObjectName objectName = new ObjectName(mbeanName);
		jmxManager.invoke(objectName, "clearContext");
	}

}


text:
const logger = require('./../logger/logger');

const config = {
  dbUri: 'mongodb://localhost:27017/fn_en_170',
  logger: logger.info,
  frameNetDir: '/Users/AKB/Dropbox/FrameNetData/fndata-1.7',
  splitsDir: '/Users/AKB/Dropbox/FrameNetData/fndata-1.7',
  importLexUnits: true,
  importFullTexts: true,
  importHierarchy: true,
  frameChunkSize: 150,
  lexUnitChunkSize: 200,
};

module.exports = config;


text:
public class EmptySequenceException extends Exception {
    public EmptySequenceException() {
        super();
    }
}


text:
from __future__ import unicode_literals

from djangobmf.core.filter_queryset import FilterQueryset

__all__ = (
    'generate_filename',
    'form_class_factory',
    'FilterQueryset',
)


text:
package org.unitime.timetable.gwt.shared;

import org.unitime.timetable.gwt.command.client.GwtRpcException;

import com.google.gwt.user.client.rpc.IsSerializable;

/**
 * @author Tomas Muller
 */
public class SavedHQLException extends GwtRpcException implements IsSerializable{
	private static final long serialVersionUID = 2144948330211931475L;

	public SavedHQLException() {
		super();
	}

	public SavedHQLException(String message) {
		super(message);
	}

}


text:
import os
import re
from jinja2 import Environment, FileSystemLoader

# set(dir(DummyObj)).symmetric_difference(set(dir(self))) == your class attrs
class DummyObj(object):
    pass

class _Singleton(type):
    """ A metaclass that creates a Singleton base class when called. """
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Singleton(_Singleton('SingletonMeta', (object,), {})): pass

# TODO: test
class LazyStorage:
    pass

# creates class from dict on demand
class LazyClass(object):
    oftype = None

    def __init__(self, name = None, oftype = None):
        if not self.oftype and oftype:
            self.oftype = oftype

        assert name is not None, ('You should provide a name for new class')
        assert self.oftype is not None, ('You should provide a type for new class')

        self.attrs = dict()
        self.name = name

    def __call__(self):
        # TODO: decide whether to put them into separate module
        # set_attr('__module__', '')
        # TODO: move 'type' instances into globals() or another place (callee?)
        return type(self.name, (self.oftype,), dict(self.attrs))

    def set_attr(self, key, value):
        self.attrs[key] = value

class Template():
    def __init__(self):
        self.loader = FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))
        self.env = Environment(loader = self.loader)

    def render(self, template_name, **kwargs):
        template = self.env.get_template(template_name)
        return template.render(**kwargs)

# processes $ref links
def Resolver(obj, path, full = False):
    m = re.search('#/(.*)/(.*)', path)
    x = None

    if full:
        b = obj[m.group(1)]
        x = b[m.group(2)]
    else:
        x = m.group(2)

    return x


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace InBloomClient.Entities
{
    public class EducationOrganization
    {
        public string id { get; set; }

        public List<AccountabilityRating> accountabilityRatings { get; set; }

        public List<Address> addresses { get; set; }

        public string agencyHierarchyName { get; set; }

        public List<EducationOrgIdentificationCode> educationOrgIdentificationCode { get; set; }

        [StringLength(75)]
        public string nameOfInstituation { get; set; }

        public string oparationalStatus { get; set; }

        public List<string> organizationCategories { get; set; }

        public List<string> programReferences { get; set; }

        [StringLength(75)]
        public string shortNameOfInstituation { get; set; }

        [StringLength(60)]
        public string stateOrganizationId { get; set; }

        public List<InstitutionTelephone> telephone { get; set; }

        [StringLength(80)] //(5-80)
        public string website { get; set; }

        public EducationOrganization parentEducationAgency { get; set; }
    }
}


text:
<?php

namespace MacFJA\PharBuilder\Builder\Compressor;

/**
 * Class AbstractFilesCompression
 *
 * @codeCoverageIgnore Impossible to UT: To many dependencies to the platform
 *
 * @package            MacFJA\PharBuilder\Builder\Compressor
 */
abstract class AbstractFilesCompression implements CompressorInterface
{
    use CompressionValidatorTrait;

    public function execute(\Phar $phar, int $compression): bool
    {
        if (!$this->isCompressionValid($compression)) {
            return false;
        }

        $content = $phar->getChildren();

        /** @var \PharFileInfo $pharFileInfo */
        foreach ($content as $pharFileInfo) {
            if ($pharFileInfo->isDir()) {
                continue;
            }
            $this->compress($pharFileInfo, $compression);
        }

        return true;
    }

    abstract protected function compress(\PharFileInfo $pharFileInfo, int $compression): void;
}


text:
/**
 * Created by bmf on 11/2/13.
 */
 /* jslint node: true */
'use strict';

var assert = require('assert');
var binding = require('../build/Release/sodium');
var toBuffer = require('./toBuffer');

module.exports =  function CryptoBaseBuffer() {
    var self = this;

    /**
     * Expected size of the buffer.
     * All buffers need to have expectedSize bytes to be valid
     * */
    self.expectedSize = 0;          // This should be set to the appropriate Lib Sodium constant

    /** internal state buffer */
    self.baseBuffer = undefined;

    /** default encoding to use in all string operations */
    self.defaultEncoding = undefined;

    /** Default valid string encoding schemes */
    self.validEncodings = /^(?:hex|base64)$/;

    /** Type of data stored in the buffer. (key, pulicKey, secretKey, nonce) **/
    self.type = undefined;

    /**
     * Initialize object
     * If a key is not given generate a new random key.
     *
     * Valid keys, once converted to a node buffer, must have expectedSize in length.
     * If a key is represented by a string the string length depends on the encoding
     * so do not rely on string lengths to calculate key sizes.
     *
     * @param {number} expectedSize          expected size of the buffer in bytes
     * @param {String|Buffer|Array} [value]  value to initialize the buffer with
     * @param {Srting} [encoding]            encoding to use in conversion if value is a string. Defaults to 'hex'
     */
    self.init = function(options) {
        options = options || {};

        assert(typeof options.expectedSize == 'number' && options.expectedSize > 0, 'options.expectedSize > 0');

        if ( !options.type ) {
            throw self.error('type must be passed to init');
        }
        assert(typeof options.type == 'string');

        self.type = options.type;

        if ( !options.expectedSize ) {
            throw self.error('expectedSize must be passed to init');
        }
        self.expectedSize = options.expectedSize;

        if( !options.buffer ) {
            self.generate();
            return;
        }

        self.set(options.buffer, options.encoding);
    };

    /**
     * Set the default encoding to use in all string conversions
     * @param {String} encoding  encoding to use
     */
    self.setEncoding = function(encoding) {
        assert(typeof encoding == 'string');
        assert(encoding.match(self.validEncodings));
        self.defaultEncoding = encoding;
    };

    /**
     * Get the current default encoding
     * @returns {undefined|String}
     */
    self.getEncoding = function() {
        return self.defaultEncoding;
    };

    /**
     * Return the type of data stored in the buffer.
     * Example: "BoxKeyPublicKey" for a Box object's public key
     * @returns {undefined|String}
     */
    self.getType = function() {
        return self.type;
    };

    /**
     * Set the valid string encodings
     *
     * A lot of cryptographic functions rely on random buffer data that cannot
     * be accurately converted to and from some encoding schemes. This method
     * allows you to restrict the string encoding to settings you know will work
     *
     * @param {Array} encList   array of strings with supported encodings
     */
    self.setValidEncodings = function(encList) {
        if( !encList ) {
            return;
        }
        assert(encList instanceof Array);
        var rxStr = '^(?:';
        var l = encList.length;
        for(var i=0; i < l; i++) {
            if( encList[i] === 'utf8' ) {
                throw self.error('utf8 cannot be used to decode random byte buffers. Crypto is "random"');
            }
            rxStr += encList[i];
            if( i != l-1 ) rxStr += '|';
        }
        rxStr += ')$';

        self.validEncodings = new RegExp(rxStr);
    };

    /**
     * Generate a new Error appropriate to use with throw
     * @param errorMessage
     * @returns {Error}
     */
    self.error = function(errorMessage) {
        return new Error('[CryptoBaseBuffer] ' + self.type + ' ' + errorMessage);
    };

    /**
     * Convert value into a buffer
     *
     * @param {String|Buffer|Array} value  a buffer, and array of bytes or a string that you want to convert to a buffer
     * @param {String} [encoding]          encoding to use in conversion if value is a string. Defaults to 'hex'
     * @returns {*}
     */
    self.toBuffer = function(value, encoding) {
        encoding = encoding || self.defaultEncoding;

        if( encoding && !encoding.match(self.validEncodings)) {
            throw self.error('invalid encoding');
        }

        return toBuffer(value, encoding);
    };

    /**
     * Get the length of the buffer
     * @returns {number} length in bytes of the buffer
     */
    self.size = function() {
        return self.expectedSize;
    };

    /**
     * Get the length of the buffer
     * @returns {number} length in bytes of the buffer
     */
    self.bytes = self.size;

    /**
     * Check if value could be used by CryptoBaseBuffer as a buffer
     *
     * @param {String|Buffer|Array} value to test
     * @param {String} [encoding]   encoding to use in conversion if value is a string. Defaults to 'hex'
     * @returns {boolean} true      if value could be used as a CryptoBaseBuffer
     */
    self.isValid = function(value, encoding) {
        if( !self.expectedSize ) {
            throw self.error('expectedSize must be set in the sub-class by calling init()');
        }

        if( typeof value === 'string' ) {
            encoding = encoding || self.defaultEncoding || 'hex';

            if( encoding === 'utf8' ) {
                throw self.error('utf8 cannot be used to encode/decode random byte buffers. Crypto is "random"');
            }

            if( encoding && !encoding.match(self.validEncodings)) {
                throw self.error('invalid encoding');
            }

            return Buffer.byteLength(value, encoding) == self.expectedSize;
        }

        if( typeof value == 'object' ) {
            if( value instanceof Array || value instanceof Buffer ) {
                return value.length == self.expectedSize;
            }
            if( value instanceof CryptoBaseBuffer ) {
                return value.size() == self.expectedSize;
            }
        }
        return false;
    };

    /**
     * Wipe buffer securely
     */
    self.wipe = function() {
        if( self.baseBuffer ) {
            binding.memzero(self.baseBuffer);
        }
    };

    /**
     * Fill buffer with random bytes
     * This method can be redefined in each sub-class to implement
     * the specific needs of that class
     */
    self.generate = function() {
        if( !self.expectedSize ) {
            throw self.error('expectedSize must be set in the sub-class by calling init()');
        }
        self.baseBuffer = Buffer.allocUnsafe(self.expectedSize);
        binding.randombytes_buf(self.baseBuffer);
    };

    /**
     *  Getter for the baseBuffer
     * @returns {undefined| Buffer} secret key
     */
    self.get = function() {
        return self.baseBuffer;
    };

    /**
     * Set the secret key to a known value
     * @param {String|Buffer|Array} value   the secret value to set the buffer to
     * @param {String} [encoding]           If v is a string you can specify the encoding.
     */
    self.set = function(value, encoding) {
        encoding = encoding || self.defaultEncoding;

        if( !value ) {
            self.wipe();
            return;
        }

        if( encoding && !encoding.match(self.validEncodings)) {
            throw self.error('invalid encoding');
        }

        if( !self.isValid(value, encoding) ) {
            throw self.error('baseBuffer length must be ' + self.expectedSize + ' bytes');
        }

        if( value instanceof CryptoBaseBuffer ) {
            self.baseBuffer = value;
        }
        else {
            self.baseBuffer = self.toBuffer(value, encoding);
        }
    };

    /**
     * Convert the secret key to a string object
     * @param encoding {String} optional sting encoding. defaults to 'hex'
     */
    self.toString = function(encoding) {
        encoding = encoding || self.defaultEncoding || 'hex';

        if( encoding.toLowerCase() === 'utf8' ) {
            throw self.error('utf8 cannot be used to decode random byte buffers. Crypto is "random"');
        }

        if( encoding && !encoding.match(self.validEncodings)) {
            throw self.error('invalid encoding');
        }

        if( !self.baseBuffer ) {
            throw self.error('buffer has not been generated or set yet.');
        }

        return self.baseBuffer.toString(encoding);
    };

    /**
     * Serialize a CryptoBaseBuffer
     *
     * @param {String} [encoding]   encoding used to convert the buffer to a string
     * @returns {string}            parsable JSON string
     */
    self.serialize = function(encoding) {
        encoding = encoding || self.defaultEncoding || 'hex';

        if( encoding.toLowerCase() === 'utf8' ) {
            throw self.error('utf8 cannot be used to decode random byte buffers. Crypto is "random"');
        }

        var out = '{ "buffer:"' + self.toString(encoding) + ',';
        out += ' "encoding:"' + encoding + '}';
        return out;
    };

    /**
     * Deserialize object. Take a parsable JSON string and create a valid buffer object
     *
     * @param {Object} obj    parsable JSON String
     */
    self.deserialize = function(obj) {
        var o;
        try {
            o = JSON.parse(obj);
        }
        catch (e) {
            throw self.error('invalid object to deserialize: ' + e.message);
        }

        self.set(o.buffer, o.encoding);
    };

    // some aliases
    self.toJSON = self.serialize;
    self.parse = self.deserialize;
};


text:
//
// Copyright 2019 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//

using Google.Apis.Compute.v1;
using Google.Apis.Compute.v1.Data;
using Google.Solutions.Common.ApiExtensions.Request;
using Google.Solutions.Common.Diagnostics;
using Google.Solutions.Common.Locator;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Google.Solutions.Common.ApiExtensions.Instance
{
    /// <summary>
    /// Extension methods for mutating instance metadata.
    /// </summary>
    public static class AddMetadataExtensions
    {
        private const uint DefaultAttempts = 6;

        /// <summary>
        /// Generic helper method that works for both instance and
        /// project metdata
        /// </summary>
        private static async Task UpdateMetadataAsync(
            Func<Task<Metadata>> readMetadata,
            Func<Metadata, Task> writeMetadata,
            Action<Metadata> updateMetadata,
            uint maxAttempts)
        {
            for (int attempt = 1; ; attempt++)
            {
                //
                // NB. Metadata must be updated all-at-once. Therefore,
                // fetch the existing entries first before merging them
                // with the new entries.
                //
                var metadata = await readMetadata()
                    .ConfigureAwait(false);

                updateMetadata(metadata);

                try
                {
                    await writeMetadata(metadata)
                        .ConfigureAwait(false);
                    break;
                }
                catch (GoogleApiException e)
                {
                    if (attempt == maxAttempts)
                    {
                        //
                        // That's enough, give up.
                        //
                        CommonTraceSources.Default.TraceWarning(
                            "SetMetadata failed with {0} (code error {1})", e.Message,
                            e.Error?.Code);

                        throw;
                    }

                    if (e.Error != null && e.Error.Code == 412)
                    {
                        // Fingerprint mismatch - that happens when somebody else updated metadata
                        // in patallel.

                        int backoff = 100;
                        CommonTraceSources.Default.TraceWarning(
                            "SetMetadata failed with {0} (code error {1}) - retrying after {2}ms", e.Message,
                            e.Error?.Code,
                            backoff);

                        await Task.Delay(backoff).ConfigureAwait(false);
                    }
                    else
                    {
                        CommonTraceSources.Default.TraceWarning(
                            "Setting metdata failed {0} (code error {1})", e.Message,
                            e.Error?.Code);

                        throw;
                    }
                }
            }
        }

        //---------------------------------------------------------------------
        // Project metadata.
        //---------------------------------------------------------------------

        /// <summary>
        /// Project/common instance metadata.
        /// </summary>
        public static async Task UpdateMetadataAsync(
            this ProjectsResource resource,
            string projectId,
            Action<Metadata> updateMetadata,
            CancellationToken token,
            uint maxAttempts = DefaultAttempts)
        {
            using (CommonTraceSources.Default.TraceMethod().WithParameters(projectId))
            {
                await UpdateMetadataAsync(
                        async () =>
                        {
                            var project = await resource.Get(projectId)
                                .ExecuteAsync(token)
                                .ConfigureAwait(false);

                            return project.CommonInstanceMetadata;
                        },
                        async metadata =>
                        {
                            await resource.SetCommonInstanceMetadata(
                                    metadata,
                                    projectId)
                                .ExecuteAndAwaitOperationAsync(
                                    projectId,
                                    token)
                                .ConfigureAwait(false);
                        },
                        updateMetadata,
                        maxAttempts)
                    .ConfigureAwait(false);
            }
        }

        /// <summary>
        /// Adds or overwrite a metadata key/value pair.
        /// Existing metadata is kept as is.
        /// </summary>
        public static Task AddMetadataAsync(
            this ProjectsResource resource,
            string projectId,
            string key,
            string value,
            CancellationToken token)
        {
            return AddMetadataAsync(
                resource,
                projectId,
                new Metadata()
                {
                    Items = new List<Metadata.ItemsData>()
                    {
                        new Metadata.ItemsData()
                        {
                            Key = key,
                            Value = value
                        }
                    }
                },
                token);
        }

        public static Task AddMetadataAsync(
           this ProjectsResource resource,
           string projectId,
           Metadata metadata,
           CancellationToken token)
        {
            return UpdateMetadataAsync(
                resource,
                projectId,
                existingMetadata =>
                {
                    existingMetadata.Add(metadata);
                },
                token);
        }

        //---------------------------------------------------------------------
        // Instance metadata.
        //---------------------------------------------------------------------

        /// <summary>
        /// Modify instance metadata.
        /// </summary>
        public static async Task UpdateMetadataAsync(
            this InstancesResource resource,
            InstanceLocator instanceRef,
            Action<Metadata> updateMetadata,
            CancellationToken token,
            uint maxAttempts = DefaultAttempts)
        {
            using (CommonTraceSources.Default.TraceMethod().WithParameters(instanceRef))
            {
                await UpdateMetadataAsync(
                        async () =>
                        {
                            var instance = await resource.Get(
                                    instanceRef.ProjectId,
                                    instanceRef.Zone,
                                    instanceRef.Name)
                                .ExecuteAsync(token)
                                .ConfigureAwait(false);

                            return instance.Metadata;
                        },
                        async metadata =>
                        {
                            await resource.SetMetadata(
                                    metadata,
                                    instanceRef.ProjectId,
                                    instanceRef.Zone,
                                    instanceRef.Name)
                                .ExecuteAndAwaitOperationAsync(
                                    instanceRef.ProjectId,
                                    token)
                                .ConfigureAwait(false);
                        },
                        updateMetadata,
                        maxAttempts)
                    .ConfigureAwait(false);
            }
        }

        /// <summary>
        /// Adds or overwrite a metadata key/value pair.
        /// Existing metadata is kept as is.
        /// </summary>
        public static Task AddMetadataAsync(
            this InstancesResource resource,
            InstanceLocator instanceRef,
            string key,
            string value,
            CancellationToken token)
        {
            return AddMetadataAsync(
                resource,
                instanceRef,
                new Metadata()
                {
                    Items = new List<Metadata.ItemsData>()
                    {
                        new Metadata.ItemsData()
                        {
                            Key = key,
                            Value = value
                        }
                    }
                },
                token);
        }

        public static Task AddMetadataAsync(
           this InstancesResource resource,
           InstanceLocator instanceRef,
           Metadata metadata,
           CancellationToken token)
        {
            return UpdateMetadataAsync(
                resource,
                instanceRef,
                existingMetadata =>
                {
                    existingMetadata.Add(metadata);
                },
                token);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="guest_space_bottom_buttons_text_size">12sp</dimen>
    <dimen name="guest_space_bottom_buttons_padding">1dp</dimen>
    <dimen name="guest_space_super_stable_description_text_size">12sp</dimen>
    <dimen name="guest_space_super_stable_description_text_lineSpacingExtra">5dp</dimen>
</resources>


text:
<?php

class Services_Actions_EditUserPrefs {
    private $_daoFactory;
    private $_settings;

	private $_svcUserFilter;
	private $_svcUserRecord;
	private $_svcUserAuth;
	private $_spotSec;

	function __construct(Dao_Factory $daoFactory, Services_Settings_Container $settings, SpotSecurity $spotSec) {
        $this->_daoFactory = $daoFactory;
        $this->_settings = $settings;

		$this->_svcUserFilter = new Services_User_Filters($this->_daoFactory, $this->_settings);
		$this->_svcUserRecord = new Services_User_Record($this->_daoFactory, $this->_settings);
		$this->_svcUserAuth = new Services_User_Authentication($this->_daoFactory, $this->_settings);

		$this->_spotSec = $spotSec;
	} # ctor

	function editUserPref(array $editUserPrefsForm, array $userPrefTemplate, array $spotUser, $avatarFileName) {
		/*
		 * We want the anonymous' users account so we can use this users' preferences as a
		 * template. This makes sure all properties are at least set.
		 */
		$anonUser = $this->_svcUserRecord->getUser(SPOTWEB_ANONYMOUS_USERID);

		/*
		 * We have a few dummy preferenes -- these are submitted like a checkbox for example
		 * but in reality do something completely different.
		 *
		 * Because we use cleanseUserPreferences() those dummies will not end up in the database
		 */
		if (isset($editUserPrefsForm['_dummy_prevent_porn'])) {
			$this->_svcUserFilter->setEroticIndexFilter($spotUser['userid']);
		} else {
			$this->_svcUserFilter->removeIndexFilter($spotUser['userid']);
		} # if

		# Save the current' user preferences because we need them before cleansing
		$savePrefs = $spotUser['prefs'];
		$spotUser['prefs'] = $this->_svcUserRecord->cleanseUserPreferences($editUserPrefsForm,
									$anonUser['prefs'],
									$userPrefTemplate);

		# Validate all preferences
		$result = $this->_svcUserRecord->validateUserPreferences($spotUser['prefs'], $savePrefs);
		$spotUser['prefs'] = $result->getData('prefs');

		# Make sure user has permission to select this template
		if ($spotUser['prefs']['normal_template'] != $savePrefs['normal_template']) {
			$this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_select_template, $spotUser['prefs']['normal_template']);
		} # if

		if ($spotUser['prefs']['mobile_template'] != $savePrefs['mobile_template']) {
			$this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_select_template, $spotUser['prefs']['mobile_template']);
		} # if

		if ($spotUser['prefs']['tablet_template'] != $savePrefs['tablet_template']) {
			$this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_select_template, $spotUser['prefs']['tablet_template']);
		} # if

		if ($result->isSuccess()) {

			# Test to see if a new avatar was provided
            if (!empty($avatarFileName)) {
                $avatarResult  = $this->_svcUserRecord->changeAvatar(
                    $spotUser['userid'],
                    file_get_contents($avatarFileName));

                /*
                 * Merge the result of the avatar update to our
                 * total result
                 */
                $result->mergeResult($avatarResult);
            } # if
		} # if

		if ($result->isSuccess()) {
			# and actually update the user in the database
			$this->_svcUserRecord->setUser($spotUser);
		} # if

		/*
		 * We have the register Spotweb with the notification providers (growl, prowl, etc) atleast once.
		 * The safes option is to just do this wih each preferences submit. But first we create a fake
		 * session for this user.
		 */
		$fakeSession = $this->_svcUserAuth->createNewSession($spotUser['userid']);
		$fakeSession['security'] = new SpotSecurity($this->_daoFactory->getUserDao(),
                                                    $this->_daoFactory->getAuditDao(),
                                                    $this->_settings,
                                                    $fakeSession['user'],
                                                    '');

		$spotsNotifications = new SpotNotifications($this->_daoFactory, $this->_settings, $fakeSession);
		$spotsNotifications->register();

        return $result;
	} # editUserPref

} # Services_Actions_EditUserPrefs


text:
/**
 * fis.baidu.com
 */

var cssgrace = require('./lib/cssgrace.js');
module.exports = function (content, file, settings) {
    return cssgrace.pack(content, { from: settings.filename } );
};


text:
<?php
/**
 * WC API Client Products resource class
 *
 * @since 2.0
 */
class WC_API_Client_Resource_Products extends WC_API_Client_Resource {

	/**
	 * Setup the resource
	 *
	 * @since 2.0
	 * @param WC_API_Client $client class instance
	 */
	public function __construct( $client ) {

		parent::__construct( 'products', 'product', $client );
	}

	/**
	 * Get products
	 *
	 * GET /products
	 * GET /products/#{id}
	 *
	 * @since 2.0
	 * @param null|int $id product ID or null to get all products
	 * @param array $args acceptable products endpoint args, like `filter[]`
	 * @return array|object products!
	 */
	public function get( $id = null, $args = array() ) {

		$this->set_request_args( array(
			'method' => 'GET',
			'path'   => $id,
			'params' => $args,
		) );

		return $this->do_request();
	}

	/**
	 * Get product by SKU
	 *
	 * GET /products/sku/{sku}
	 *
	 * Note this will throw an exception if no products are found (404 not found)
	 *
	 * @since 2.0
	 * @param string $sku product SKU
	 * @param array $args acceptable product SKU lookup endpoint args, currently only `fields`
	 * @return array|object product!
	 */
	public function get_by_sku( $sku, $args = array() ) {

		$this->set_request_args( array(
			'method' => 'GET',
			'path'   => array( 'sku', urlencode( $sku ) ),
			'params' => $args,
		) );

		return $this->do_request();
	}

	/**
	 * Create a product
	 *
	 * POST /products
	 *
	 * @since 2.0
	 * @param array $data valid product data
	 * @return array|object your newly-created product
	 */
	public function create( $data ) {

		$this->set_request_args( array(
			'method' => 'POST',
			'body'   => $data,
		) );

		return $this->do_request();
	}

	/**
	 * Update a product
	 *
	 * PUT /product/#{id}
	 *
	 * @since 2.0
	 * @param int $id product ID
	 * @param array $data product data to update
	 * @return array|object your newly-updated product
	 */
	public function update( $id, $data ) {

		$this->set_request_args( array(
			'method' => 'PUT',
			'path'   => $id,
			'body'   => $data,
		) );

		return $this->do_request();
	}

	/**
	 * Delete a product
	 *
	 * DELETE /products/#{id}
	 *
	 * @since 2.0
	 * @param int $id product ID
	 * @param bool $force true to permanently delete the product, false to trash it
	 * @return array|object response
	 */
	public function delete( $id, $force = false ) {

		$this->set_request_args( array(
			'method' => 'DELETE',
			'path'   => $id,
			'params' => array( 'force' => $force ),
		) );

		return $this->do_request();
	}

	/**
	 * Get a count of products
	 *
	 * GET /products/count
	 *
	 * @since 2.0
	 * @param array $args acceptable product endpoint args, like `type` or `filter[]`
	 * @return array|object the count
	 */
	public function get_count( $args = array() ) {

		$this->set_request_args( array(
			'method' => 'GET',
			'path'   => 'count',
			'params' => $args,
		) );

		return $this->do_request();
	}

	/**
	 * Get product reviews
	 *
	 * GET /products/#{product_id}/reviews
	 *
	 * @since 2.0
	 * @param int $id product ID
	 * @param array $args acceptable product reviews endpoint args, currently only `fields`
	 * @return array|object product reviews!
	 */
	public function get_reviews( $id, $args = array() ) {

		$this->set_request_args( array(
			'method' => 'GET',
			'path'   => array( $id, 'reviews' ),
			'params' => $args,
		) );

		return $this->do_request();
	}

	/**
	 * Get a list of product categories or a single product category
	 *
	 * GET /products/categories
	 * GET /products/categories/{#id}
	 *
	 * @since 2.0
	 * @param int $id category ID or null to get all product categories
	 * @param array $args acceptable product categories endpoint args, currently only `fields`
	 * @return array|object product categories!
	 */
	public function get_categories( $id = null, $args = array() ) {

		$this->set_request_args( array(
			'method' => 'GET',
			'path'   => array( 'categories', $id ),
			'params' => $args,
		) );

		return $this->do_request();
	}

	/** Convenience methods - these do not map directly to an endpoint ********/

	/**
	 * Update the stock quantity for a product
	 *
	 * PUT /products/#{id} with stock quantity
	 *
	 * @param int $id order ID
	 * @param int|float $quantity new stock quantity
	 * @return array|object newly-updated product
	 */
	public function update_stock( $id, $quantity ) {

		$this->set_request_args( array(
			'method' => 'PUT',
			'path'   => $id,
			'body'   => array( 'stock_quantity' => $quantity ),
		) );

		return $this->do_request();
	}

}


text:
package skin.support.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

/**
 * Created by pengfengwang on 2017/1/13.
 */

public class SkinCompatRelativeLayout extends RelativeLayout implements SkinCompatSupportable {
    private SkinCompatBackgroundHelper mBackgroundTintHelper;

    public SkinCompatRelativeLayout(Context context) {
        this(context, null);
    }

    public SkinCompatRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SkinCompatRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mBackgroundTintHelper = new SkinCompatBackgroundHelper(this);
        mBackgroundTintHelper.loadFromAttributes(attrs, defStyleAttr);
    }

    @Override
    public void setBackgroundResource(int resId) {
        super.setBackgroundResource(resId);
        if (mBackgroundTintHelper != null) {
            mBackgroundTintHelper.onSetBackgroundResource(resId);
        }
    }

    @Override
    public void applySkin() {
        if (mBackgroundTintHelper != null) {
            mBackgroundTintHelper.applySkin();
        }
    }

}


text:
/**
 * Helper Class for working with the application cache.
 *
 * Listen for the following events:
 * UPDATE_READY - an update to the cache is ready
 * UPDATE_NONE - the cache hasn't changed since the last app load.
 * CACHE_LOADED - the cache has finished loading.
 * CACHE_ERROR - an error was thrown by the browser while attempting to load the cache.
 *
 * For more information on application cache:
 * https://developer.mozilla.org/en-US/docs/HTML/Using_the_application_cache
 * Many thanks and all kudos go to the following blog posts:
 * http://www.html5rocks.com/en/tutorials/this.appCache/beginner/
 */
define([
    "dojo/_base/declare",
    "dojo/Evented",
    "dojo/_base/lang"],
    function(declare,Evented,lang){
        return declare([Evented], {
            UPDATE_READY: "update-ready",
            UPDATE_NONE: "no-update",
            CACHE_EVENT: "cache-event",
            CACHE_LOADED: "cache-loaded",
            CACHE_ERROR: "cache-error",
            appCache: window.applicationCache,

            constructor: function(/* boolean */autoUpdate, /* boolean */ setListeners)
            {
                if(autoUpdate)this.setUpdateCache();
                if(setListeners)this.setCacheListeners();
                console.log("appCacheManager.js enabled");
            },

            setUpdateCache:function(){
                // Check if a new cache is available on page load.
                window.addEventListener('load', function(evt) {

                    window.applicationCache.addEventListener('updateready', function(evt) {
                        if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
                            // Browser downloaded a new app cache.
                            if (confirm('A new version of this cache is available.')) {
                                window.location.reload();
                                console.log("App cache reloaded");
                                this.emit(this.UPDATE_READY,null);
                            }
                        } else {
                            // Manifest didn't changed. Nothing new to server.
                            console.log("App cache no change");
                            this.emit(this.UPDATE_NONE,null);
                        }
                    }, false);

                }, false);
            },

            setCacheListeners:function(){
                this.appCache.addEventListener('cached', this._handleCacheEvents.bind(this), false);

                // Checking for an update. Always the first event fired in the sequence.
                this.appCache.addEventListener('checking', this._handleCacheEvents.bind(this), false);

                // An update was found. The browser is fetching resources.
                this.appCache.addEventListener('downloading', this._handleCacheEvents.bind(this), false);

                // The manifest returns 404 or 410, the download failed,
                // or the manifest changed while the download was in progress.
                this.appCache.addEventListener('error', this._handleCacheErrors.bind(this), false);

                // Fired after the first download of the manifest.
                this.appCache.addEventListener('noupdate', this._handleCacheEvents.bind(this), false);

                // Fired if the manifest file returns a 404 or 410.
                // This results in the application cache being deleted.
                this.appCache.addEventListener('obsolete', this._handleCacheEvents.bind(this), false);

                // Fired for each resource listed in the manifest as it is being fetched.
                this.appCache.addEventListener('progress', this._handleCacheEvents.bind(this), false);

                // Fired when the manifest resources have been newly redownloaded.
                this.appCache.addEventListener('updateready', this._handleCacheEvents.bind(this), false);
            },

            getCacheStatus:function(){

                switch (this.appCache.status) {
                    case this.appCache.UNCACHED: // UNCACHED == 0
                        return 'UNCACHED';
                        break;
                    case this.appCache.IDLE: // IDLE == 1
                        return 'IDLE';
                        break;
                    case this.appCache.CHECKING: // CHECKING == 2
                        return 'CHECKING';
                        break;
                    case this.appCache.DOWNLOADING: // DOWNLOADING == 3
                        return 'DOWNLOADING';
                        break;
                    case this.appCache.UPDATEREADY:  // UPDATEREADY == 4
                        return 'UPDATEREADY';
                        break;
                    case this.appCache.OBSOLETE: // OBSOLETE == 5
                        return 'OBSOLETE';
                        break;
                    default:
                        return 'UKNOWN CACHE STATUS';
                        break;
                };
            },

            _handleCacheEvents:function(evt){
                if(evt.hasOwnProperty("total") && evt.hasOwnProperty("loaded")){
                    if(evt.total == evt.loaded){
                        console.log("appCacheManager: cache has finished loading.")
                        this.emit(this.CACHE_LOADED,"cache-loaded");
                    }
                }
                this.emit(this.CACHE_EVENT,evt);
            },

            _handleCacheErrors:function(evt){
                this.emit(this.CACHE_ERROR,evt);
            }
        })
    }
)


text:
package io.dveamer.oxboard.enums;

/**
 * Created by dveamer on 16. 4. 10
 */
public enum GameState {
    PLAYING, DRAW, WHITE_WON, BLACK_WON
}


text:
class Cat < ActiveRecord::Base

  def to_s
    "Cat number #{self.id} with a name of #{self.name} and is a #{self.breed}"
  end

end


text:
int main (void)
{
	char bread_type = '\0', double_size = '\0', manual_bake = '\0';

	bread_type = prompt_bread ();
	double_size = prompt_double ();
	manual_bake = prompt_manual ();

	if (bread_type == 'w')
	{
		white_bread_main (double_size, manual_bake);
	}
	else
	{
		sweet_bread_main (double_size, manual_bake);
	}

	return 0;
}


text:
using System;
using System.Linq.Expressions;

namespace DragonSpark.Application.Entities.Queries.Compiled;

sealed class ManyGeneric<TIn, TOut> : Reflection.Types.Generic<LambdaExpression, Delegate[], IElements<TIn, TOut>>
{
	public ManyGeneric(Type definition) : base(definition) {}
}


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [0.7.0] - 2018-04-18
### Added
- Feature flag to disable authorization check for FilesRecord.
  Should only be used if needed, because of client-app behavior.

## [0.6.9] - 2018-03-22
### Added
- `ProvenanceAssessmentTaken` records and tests.

## [0.6.8] - 2018-03-16
### Changed
- Default values maintained when django present but
  not configured.

## [0.6.7] - 2018-03-16
### Fixed
- Better exception handling for django environments.

## [0.6.6] - 2018-03-09
### Added
- Tests for `set_created_date()`.

## [0.6.5] - 2018-03-09
### Added
- `Asset` `createdDate` method implementations.

## [0.6.4] - 2018-03-07
### Changed
- Returns a foreign `Catalog` object instead of a `json_`
  one.

## [0.6.3] - 2018-03-06
### Added
- Django `setup` calls to get settings configured correctly.

## [0.6.2] - 2018-03-01
### Changed
- `filesystem_adapter` always returns a wrapped `AssetContent`
  from an `AssetContentList`.

## [0.6.1] - 2018-03-01
### Changed
- FilesRecord uses internal helper method and AssetLookup
  to get AssetContents, instead of AssetContentLookup.

## [0.6.0] - 2018-02-28
### Added
- diskcache and configuration options. Changes default caching
  behavior when turned on to use `diskcache` instead of `memcache`.

## [0.5.18] - 2018-02-23
### Added
- microseconds data for AssessmentTaken results.

### Fixed
- AssetContent filenames with `filesystem_adapter` are
  correctly renamed for secondary storage paths, if
  provided.

## [0.5.17] - 2018-01-16
### Added
- memcached URI configuration flag.

### Changed
- Reverted to previous records scheme.
- Travis CI settings.

## [0.5.16] - 2017-12-27
### Changed
- Failed attempt to fix records...removed from PyPI.

## [0.5.15] - 2017-12-27
### Changed
- Attempted to implement new records scheme.

## [0.5.14] - 2017-12-05
### Added
- License file to pypi bundle.

## [0.5.13] - 2017-09-13
### Fixed
- Consider cases where `django` settings already configured.

## [0.5.12] - 2017-09-13
### Fixed
- Better handling and configuration of `django` settings, to not rely on
  an environment variable.

## [0.5.11] - 2017-09-13
### Added
- Use `tox` for testing.

### Fixed
- Better handcar config management when `django` is in the environment.

## [0.5.10] - 2017-09-11
### Fixed
- For getting section results, account for non-magic-multiple-choice
  choices.

## [0.5.9] - 2017-09-05
### Changed
- `GradeLookupSession` in `authz_adapter` to throw Permission Denied,
  due to a non-existent method from the template.

### Fixed
- Various test setups to work with new `QuerySessions`.

## [0.5.8] - 2017-08-31
### Changed
- Default config to remove authorization adapter.

## [0.5.7] - 2017-08-30
### Changed
- Default config to use `JSON_1` for authorization.

### Added
- More tests
- AssessmentPartBankSession, AssessmentPartBankAssignmentSession
- AuthorizationVaultSession, AuthorizationVaultAssignmentSession

## [0.5.6] - 2017-07-21
### Fixed
- Lore and edX record extensions export compositions with unique names.

## [0.5.5] - 2017-07-19
### Added
- `dupliate_item` and `duplicate_assessment` methods with tests.

## [0.5.4] - 2017-07-19
### Added
- Tests for the `edX` and `lore` `repository` record extensions.
- Decorator in AWS and Filesystem adapters to remove `None` proxy for
  Manager methods.
- Test cassettes for AWS tests.
- Tests for most `primordium` objects.
- Cataloging tests.

### Changed
- Temporal record extension returns `DateTime` object, not `dict`.

### Fixed
- Various bugs in the `edX` and `lore` `repository` record extensions.

### Removed
- Unused `duplicate_X` methods.
- Auto-enclosure on create and update asset forms.

## [0.5.3] - 2017-07-07
### Fixed
- Fix method names for creating and updating sequence rules in `assessment_utilities.py`.
- Getting existing `mdata` values returns key with matching type, i.e. returns `existing_date_time_values` instead of `existing_object_values`.
- Fixed method name when checking if `Assessment` has shuffled sections. (out of spec)
- Missing `Id` use when getting `items` for an `AssessmentTaken`.
- Extraneous argument when checking `priority` is valid, in `osid.logging.LogEntryForm.set_priority` template.
- `delete_question` uses the right key to query the database.
- Handle notification sessions in services better.
- Fixed various templates in `ResourceBinAssignmentSession` methods to use template contexts, instead of the `resource` words like `bin` and `resource`.
- Fix `services` builder to handle sub-package methods better.
- Learning `Activity` methods to check what type of `Activity` it is.
- Drag and drop record type handles missing `description` field.
- QTI record type handles non-multilanguage QTI.

### Changed
- Updated many `mdata` values from basic strings to `DisplayText` objects.
- `GradeSystem` timestamps to be stored as actual `datetime` objects, not dictionaries.
- Mocked out external service calls for Handcar and AWS tests.
- Ignored profile files, `app_configs` and `abstract_osid` directories for coverage reporting.

### Added
- Unimplemented methods:
   - `_get_previous_assessment_section`
   - `SequenceRuleQuery` `__init__`
   - `GradebookColumnSummaryQuery` `__init__`
   - `osid.logging.LogEntryForm.clear_priority_template`
   - Various authz adapter passthroughs that were missing
- More extensive testing:
   - Change skipped tests to actually test for `Unimplemented` exception.
   - Parameterized tests using `pytest`, to test across different service configurations.
   - Switch to `pytest` syntax instead of `unittest` syntax.
- Cataloging package.
- Series of hand-written tests put in the `tests/other` directory.

## [0.5.2] - 2017-06-12
### Fixed
- Compatibility with `pymongo` 2 and 3.

## [0.5.1] - 2017-06-06
### Changed
- Unlock Previous changed to simple string, instead of DisplayText.

## [0.5.0] - 2017-06-05
### Added
- Tests for CLIx `N of M` records.
- Tests for reviewable assessment offered and taken records.
- CLIx record for `unlockPrev` setting for the previous button.

## [0.4.2] - 2017-05-31
### Fixed
- Unicode handling in two records, for Python 2 / 3 compatibility.

## [0.4.1] - 2017-05-31
### Added
- Tests for json and filesystem utilities.
- Mock handcar adapter tests with `vcrpy` library.

### Changed
- MongoListener handles filesystem and test cases better.
- Filesystem `.json` encoding forced to `utf8`.
- Handcar adapter uses `requests` library.

### Fixed
- Filesystem query method `len()` of keys check.
- Helper iterator forces lists to be iterators.

## [0.4.0] - 2017-05-26
### Changed
- Python 3.4+ compatibility.

## [0.3.7] - 2017-05-10
### Added
- Tests for various records.

### Fixed
- Check for `text` is not `None` in `FilesRecord` when replacing
  urls.

## [0.3.6] - 2017-05-08
### Fixed
- For Windows, use `b` flag in `get_data()` of `filesystem_adapter`.

## [0.3.5] - 2017-04-28
### Added
- Tests for various sessions and managers.

## [0.3.4] - 2017-04-26
### Added
- Some basic tests for the `aws_adapter`. Requires setting
  configurations for AWS S3 and CloudFront.

## [0.3.3] - 2017-04-25
### Added
- Transcript XML template file added to `package_data` in
  `setup.py`.

## [0.3.2] - 2017-04-25
### Added
- Manifest file so that transcript XML template and license
  are part of the distributable.

## [0.3.1] - 2017-04-25
### Fixed
- Old `dlkit_runtime` import in `aws_adapter` changed to
  `dlkit.runtime`.

## [0.3.0] - 2017-04-24
### Added
- `label-ortho-faces` record.
- `edx-numeric-response` record.
- Self evaluation for CLIx and edX records.
- Check in MC Answer form to not add a `None` choice.
- Method in services to grab an `AssetContentLookupSession`.

### Fixed
- CLIx imports that used `dlkit_runtime` to `dlkit.runtime`.

### Changed
- Numeric response `set_answer_value` definition.
- Feedback answers record check for existence of
  `confusedLearningObjectiveIds`.

## [0.2.1] - 2017-04-24
### Fixed
- Changed `fbw` import in the CLIx magic item records
  to point to renamed `adaptive` path.

## [0.2.0] - 2017-04-21
### Added
- Item record entries for `edx-numeric-response-item`
  and `label-ortho-faces`.

## [0.1.1] - 2017-04-21
### Changed
- Project-level config directory is now `dlkit_configs`.

## [0.1.0] - 2017-04-21
### Added
- Media accessibility records.

## [0.0.1] - 2017-04-21
### Added
- Initial public release.

[0.7.0]: https://github.com/mitsei/dlkit/compare/0.6.9...0.7.0
[0.6.9]: https://github.com/mitsei/dlkit/compare/0.6.8...0.6.9
[0.6.8]: https://github.com/mitsei/dlkit/compare/0.6.7...0.6.8
[0.6.7]: https://github.com/mitsei/dlkit/compare/0.6.6...0.6.7
[0.6.6]: https://github.com/mitsei/dlkit/compare/0.6.5...0.6.6
[0.6.5]: https://github.com/mitsei/dlkit/compare/0.6.4...0.6.5
[0.6.4]: https://github.com/mitsei/dlkit/compare/0.6.3...0.6.4
[0.6.3]: https://github.com/mitsei/dlkit/compare/0.6.2...0.6.3
[0.6.2]: https://github.com/mitsei/dlkit/compare/0.6.1...0.6.2
[0.6.1]: https://github.com/mitsei/dlkit/compare/0.6.0...0.6.1
[0.6.0]: https://github.com/mitsei/dlkit/compare/0.5.18...0.6.0
[0.5.18]: https://github.com/mitsei/dlkit/compare/0.5.17...0.5.18
[0.5.17]: https://github.com/mitsei/dlkit/compare/0.5.16...0.5.17
[0.5.16]: https://github.com/mitsei/dlkit/compare/0.5.15...0.5.16
[0.5.15]: https://github.com/mitsei/dlkit/compare/0.5.14...0.5.15
[0.5.14]: https://github.com/mitsei/dlkit/compare/0.5.13...0.5.14
[0.5.13]: https://github.com/mitsei/dlkit/compare/0.5.12...0.5.13
[0.5.12]: https://github.com/mitsei/dlkit/compare/0.5.11...0.5.12
[0.5.11]: https://github.com/mitsei/dlkit/compare/0.5.10...0.5.11
[0.5.10]: https://github.com/mitsei/dlkit/compare/0.5.9...0.5.10
[0.5.9]: https://github.com/mitsei/dlkit/compare/0.5.8...0.5.9
[0.5.8]: https://github.com/mitsei/dlkit/compare/0.5.7...0.5.8
[0.5.7]: https://github.com/mitsei/dlkit/compare/0.5.6...0.5.7
[0.5.6]: https://github.com/mitsei/dlkit/compare/0.5.5...0.5.6
[0.5.5]: https://github.com/mitsei/dlkit/compare/0.5.4...0.5.5
[0.5.4]: https://github.com/mitsei/dlkit/compare/0.5.3...0.5.4
[0.5.3]: https://github.com/mitsei/dlkit/compare/0.5.2...0.5.3
[0.5.2]: https://github.com/mitsei/dlkit/compare/0.5.1...0.5.2
[0.5.1]: https://github.com/mitsei/dlkit/compare/0.5.0...0.5.1
[0.5.0]: https://github.com/mitsei/dlkit/compare/0.4.2...0.5.0
[0.4.2]: https://github.com/mitsei/dlkit/compare/0.4.1...0.4.2
[0.4.1]: https://github.com/mitsei/dlkit/compare/0.4.0...0.4.1
[0.4.0]: https://github.com/mitsei/dlkit/compare/0.3.7...0.4.0
[0.3.7]: https://github.com/mitsei/dlkit/compare/0.3.6...0.3.7
[0.3.6]: https://github.com/mitsei/dlkit/compare/0.3.5...0.3.6
[0.3.5]: https://github.com/mitsei/dlkit/compare/0.3.4...0.3.5
[0.3.4]: https://github.com/mitsei/dlkit/compare/0.3.3...0.3.4
[0.3.3]: https://github.com/mitsei/dlkit/compare/0.3.2...0.3.3
[0.3.2]: https://github.com/mitsei/dlkit/compare/0.3.1...0.3.2
[0.3.1]: https://github.com/mitsei/dlkit/compare/0.3.0...0.3.1
[0.3.0]: https://github.com/mitsei/dlkit/compare/0.2.1...0.3.0
[0.2.1]: https://github.com/mitsei/dlkit/compare/0.2.0...0.2.1
[0.2.0]: https://github.com/mitsei/dlkit/compare/0.1.1...0.2.0
[0.1.1]: https://github.com/mitsei/dlkit/compare/0.1.0...0.1.1
[0.1.0]: https://github.com/mitsei/dlkit/compare/0.0.1...0.1.0
[0.0.1]: https://github.com/mitsei/dlkit/compare/0.0.1...0.0.1


text:
//=============================================================================
// Copyright 2006-2013 Daniel W. Dyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=============================================================================
package org.uncommons.reportng;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.LoggerFactory;

/**
 * Provides access to static information useful when generating a report.
 * @author Daniel Dyer
 */
public final class ReportMetadata
{
    static final String PROPERTY_KEY_PREFIX = "org.uncommons.reportng.";
    static final String TITLE_KEY = PROPERTY_KEY_PREFIX + "title";
    static final String DEFAULT_TITLE = "Test Results Report";
    static final String COVERAGE_KEY = PROPERTY_KEY_PREFIX + "coverage-report";
    static final String EXTERNAL_LINK_CLASSNAME_KEY = PROPERTY_KEY_PREFIX + "external-link-classname";
    static final String EXCEPTIONS_KEY = PROPERTY_KEY_PREFIX + "show-expected-exceptions";
    static final String OUTPUT_KEY = PROPERTY_KEY_PREFIX + "escape-output";
    static final String XML_DIALECT_KEY = PROPERTY_KEY_PREFIX + "xml-dialect";
    static final String STYLESHEET_KEY = PROPERTY_KEY_PREFIX + "stylesheet";
    static final String LOCALE_KEY = PROPERTY_KEY_PREFIX + "locale";
    static final String VELOCITY_LOG_KEY = PROPERTY_KEY_PREFIX + "velocity-log";

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("EEEE dd MMMM yyyy");
    private static final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm z");
    private org.slf4j.Logger LOG
            = LoggerFactory.getLogger(ReportMetadata.class);

    /**
     * The date/time at which this report is being generated.
     */
    private final Date reportTime = new Date();

    /**
     * @return A String representation of the report date.
     * @see #getReportTime()
     */
    public String getReportDate()
    {
        return DATE_FORMAT.format(reportTime);
    }

    /**
     * @return A String representation of the report time.
     * @see #getReportDate()
     */
    public String getReportTime()
    {
        return TIME_FORMAT.format(reportTime);
    }

    public String getReportTitle()
    {
        return System.getProperty(TITLE_KEY, DEFAULT_TITLE);
    }

    /**
     * @return The URL (absolute or relative) of an HTML coverage report associated
     * with the test run.  Null if there is no coverage report.
     */
    public String getCoverageLink()
    {

        return System.getProperty(COVERAGE_KEY);

    }

   /**
    * The fully qualified classname
    * implementing org.uncommons.reportng.IExternalLink interface.
    * This is placed in the external link slot near the coverage link
    *
    * @return the classname as string
    */
     public String getExternalLinkClassname()
    {
        return System.getProperty(EXTERNAL_LINK_CLASSNAME_KEY,null);
    }

     /**
      * render an external link by classname. Only called if
      * an external link classname is specified
      * @return
      */
     public String renderExternalLink()
     {
         String linkString = "";
         String className = getExternalLinkClassname();
         LOG.debug("class name is "+className);
         //System.out.println("class name is "+className);
         if (className != null)
         {
             try {
                 Class myClass = Class.forName(className);
                 Constructor constructor = myClass.getConstructor();
                 IExternalLink linkItem =
                         (IExternalLink) constructor.newInstance();
                 linkString = linkItem.renderLinkText();
             } catch (ClassNotFoundException ex) {
                 LOG.error("Could not find class "+     className);

             } catch (NoSuchMethodException ex) {
                 LOG.error("No constructorr for  class "+     className);

             } catch (SecurityException ex) {
                  LOG.error("Security problem constructing class "
                          +     className);
             } catch (InstantiationException |
                     IllegalAccessException |
                     IllegalArgumentException |
                     InvocationTargetException ex) {

                  LOG.error("Problem calling  constructor for class "+
                          className+" "+ex.getMessage());
             }
         }

         return linkString;

     }

    /**
     * If a custom CSS file has been specified, returns the path.  Otherwise
     * returns null.
     * @return A {@link File} pointing to the stylesheet, or null if no stylesheet
     * is specified.
     */
    public File getStylesheetPath()
    {
        String path = System.getProperty(STYLESHEET_KEY);
        return path == null ? null : new File(path);
    }

    /**
     * Returns false (the default) if stack traces should not be shown for
     * expected exceptions.
     * @return True if stack traces should be shown even for expected exceptions,
     * false otherwise.
     */
    public boolean shouldShowExpectedExceptions()
    {
        return System.getProperty(EXCEPTIONS_KEY, "false").equalsIgnoreCase("true");
    }

    /**
     * Returns true (the default) if log text should be escaped when displayed in a
     * report.  Turning off escaping allows you to do something link inserting
     * link tags into HTML reports, but it also means that other output could
     * accidentally corrupt the mark-up.
     * @return True if reporter log output should be escaped when displayed in a
     * report, false otherwise.
     */
    public boolean shouldEscapeOutput()
    {
        return System.getProperty(OUTPUT_KEY, "true").equalsIgnoreCase("true");
    }

    /**
     * If the XML dialect has been set to "junit", we will render all skipped tests
     * as failed tests in the XML.  Otherwise we use TestNG's extended version of
     * the XML format that allows for "<skipped>" elements.
     */
    public boolean allowSkippedTestsInXML()
    {
        return !System.getProperty(XML_DIALECT_KEY, "testng").equalsIgnoreCase("junit");
    }

    /**
     * @return True if Velocity should generate a log file, false otherwise.
     */
    public boolean shouldGenerateVelocityLog()
    {
        return System.getProperty(VELOCITY_LOG_KEY, "false").equalsIgnoreCase("true");
    }

    /**
     * @return The user account used to run the tests and the host name of the
     * test machine.
     * @throws UnknownHostException If there is a problem accessing the machine's host name.
     */
    public String getUser() throws UnknownHostException
    {
        String user = System.getProperty("user.name");
        String host = InetAddress.getLocalHost().getHostName();
        return user + '@' + host;
    }

    public String getJavaInfo()
    {
        return String.format("Java %s (%s)",
                             System.getProperty("java.version"),
                             System.getProperty("java.vendor"));
    }

    public String getPlatform()
    {
        return String.format("%s %s (%s)",
                             System.getProperty("os.name"),
                             System.getProperty("os.version"),
                             System.getProperty("os.arch"));
    }

    /**
     * @return The locale specified by the System properties, or the platform default locale
     * if none is specified.
     */
    public Locale getLocale()
    {
        if (System.getProperties().containsKey(LOCALE_KEY))
        {
            String locale = System.getProperty(LOCALE_KEY);
                String[] components = locale.split("_", 3);
            switch (components.length)
            {
                case 1: return new Locale(locale);
                case 2: return new Locale(components[0], components[1]);
                case 3: return new Locale(components[0], components[1], components[2]);
                default: System.err.println("Invalid locale specified: " + locale);
            }
        }
        return Locale.getDefault();
    }
}


text:
package com.teammental.memapper.util.mapping;

import com.teammental.memapper.exception.TargetTypeInstantiationException;
import com.teammental.memapper.util.FieldUtil;
import com.teammental.mehelper.PrimitiveHelper;
import com.teammental.mehelper.StringHelper;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;

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

/**
 * author @er-han on 3/30/2017.
 */
public class MapByFieldNameUtil {

  private static final Logger logger = LoggerFactory.getLogger(MapByFieldNameUtil.class);

  /**
   * Maps given source object's suitable fields
   * to a newly instantiated object of type targetType.
   *
   * @param source     the object which's fields will be taken as map source.
   * @param targetType the type which will be used to instantiate a target object.
   * @param <SourceT>  source object' type.
   * @param <TargetT>  target object's type.
   * @return an object of type targetType.
   * @throws TargetTypeInstantiationException throws this when can't instantiate a new object.
   */
  public static <SourceT, TargetT> TargetT map(SourceT source,
                                               Class<TargetT> targetType)
      throws TargetTypeInstantiationException {

    if (source == null) {
      return null;
    }

    Class<?> sourceType = source.getClass();
    logger.debug("Started mapping from source type '"
        + sourceType.getName() + "' to target type '" + targetType.getName() + "'.");

    TargetT target;

    try {
      target = (TargetT) targetType.newInstance();
    } catch (Exception ex) {
      TargetTypeInstantiationException exception =
          new TargetTypeInstantiationException(targetType, ex);
      logger.debug(exception.getMessage());
      throw exception;
    }

    target = map(source, target);

    return target;
  }

  /**
   * Maps from source to target.
   * Both source and target must be Mappable.
   *
   * @param source    the object which's fields will be taken as map source.
   * @param target    the object which's fields will be taken as map target.
   * @param <SourceT> source object' type.
   * @param <TargetT> target object's type.
   * @return an object of type targetType.
   */
  public static <SourceT, TargetT> TargetT map(SourceT source,
                                               TargetT target) {
    if (source == null || target == null) {
      return null;
    }
    Class<?> sourceType = source.getClass();
    List<Field> sourceFields = CommonMapUtil.getAllFields(sourceType);

    logger.debug("Found fields in the source type: " + sourceFields);

    Class<?> targetType = target.getClass();
    List<Field> targetFields = CommonMapUtil.getAllFields(targetType);

    logger.debug("Found fields in the target type: " + targetFields);

    for (Field sourceField :
        sourceFields) {
      String sourceFieldName = sourceField.getName();
      Class<?> sourceFieldType = sourceField.getType();

      Stream<Field> targetFieldsStream = targetFields.stream();
      Optional<Field> targetFieldOptional = targetFieldsStream
          .filter(field ->
              field.getName().equals(sourceFieldName))
          .findFirst();

      if (targetFieldOptional.isPresent()) {

        Class<?> targetFieldType = targetFieldOptional.get().getType();

        if (sourceFieldType.equals(targetFieldType)
            || (sourceFieldType.isPrimitive()
            && PrimitiveHelper.getWrapperClass(sourceFieldType).equals(targetFieldType))
            || (targetFieldType.isPrimitive()
            && PrimitiveHelper.getWrapperClass(targetFieldType).equals(sourceFieldType))
            || sourceFieldType.isAssignableFrom(targetFieldType)
            || targetFieldType.isAssignableFrom(sourceFieldType)
            ) {

          String fieldNameCapitalized = StringHelper.capitalizeFirstLetter(sourceFieldName);

          Method sourceGetMethod = null;
          String sourceGetMethodName = "";
          if (FieldUtil.isBoolean(sourceField)) {
            sourceGetMethodName = "is" + fieldNameCapitalized;
            try {
              sourceGetMethod = sourceType.getMethod(sourceGetMethodName);
            } catch (NoSuchMethodException ex) {
              logger.debug("Field '" + sourceType.getName() + " "
                  + sourceFieldName + "' does not have a getter method named " + sourceGetMethodName
                  + ".");
            }
          }

          if (sourceGetMethod == null) {
            sourceGetMethodName = "get" + fieldNameCapitalized;
            try {
              sourceGetMethod = sourceType.getMethod(sourceGetMethodName);
            } catch (NoSuchMethodException ex) {
              logger.debug("Field '" + sourceType.getName() + " "
                  + sourceFieldName + "' does not have a getter method."
                  + " Field is ignored.");
              continue;
            }
          }

          Object sourceFieldVal;
          try {
            sourceFieldVal = sourceGetMethod.invoke(source, null);
          } catch (InvocationTargetException ex) {
            logger.debug("Invokation of  '" + sourceType.getName()
                + " " + sourceGetMethodName + "' failed. "
                + "Probably it requires at least 1 arg.");
            continue;
          } catch (IllegalAccessException ex) {
            logger.debug("Invokation of  '"
                + sourceType.getName() + " " + sourceGetMethodName + "' failed. "
                + "It has restricted access.");
            continue;
          } catch (IllegalArgumentException ex) {
            logger.debug("Invokation of  '"
                + sourceType.getName() + " " + sourceGetMethodName + "' failed. "
                + "Illegal argument.");
            continue;
          }

          Method targetSetMethod;
          String targetSetMethodName = "set" + fieldNameCapitalized;
          try {
            targetSetMethod = targetType.getMethod(targetSetMethodName, targetFieldType);
          } catch (NoSuchMethodException ex) {
            logger.debug("Field '" + targetType.getName() + " "
                + sourceFieldName + "' does not have a setter method.");
            continue;
          }

          try {
            targetSetMethod.invoke(target, sourceFieldVal);
          } catch (InvocationTargetException ex) {
            logger.debug("Invokation of  '" + targetType.getName()
                + " " + targetSetMethodName + "' failed. "
                + "Probably it requires at least 1 arg.");
            continue;
          } catch (IllegalAccessException ex) {
            logger.debug("Invokation of  '" + targetType.getName()
                + " " + targetSetMethodName + "' failed. "
                + "It has restricted access.");
            continue;
          } catch (IllegalArgumentException ex) {
            logger.debug("Invokation of  '" + targetType.getName()
                + " " + targetSetMethodName + "' failed. "
                + "Illegal argument.");
            continue;
          }

        }
      } else {

      }
    }
    return target;
  }

  /**
   * Maps given source object's suitable fields
   * to a newly instantiated object of type targetType.
   *
   * @param source    the object which's fields will be taken as map source.
   * @param supplier  the supplier which will be used to instantiate a target object.
   * @param <SourceT> source object' type.
   * @param <TargetT> target object's type.
   * @return an object of type targetType.
   */
  public static <SourceT, TargetT> TargetT map(SourceT source,
                                               Supplier<TargetT> supplier) {
    if (supplier == null) {
      return null;
    }
    return map(source, supplier.get());
  }

  /**
   * @param sources    A list of object's to be mapped from.
   * @param targetType the type which will be used to instantiate a target object.
   * @param <SourceT>  source object' type.
   * @param <TargetT>  target object's type.
   * @return A List<targetT> object of type targetType.
   * @throws TargetTypeInstantiationException throws this when can't instantiate a new object.
   */
  public static <SourceT, TargetT> Iterable<TargetT> map(Iterable<SourceT> sources,
                                                         Class<TargetT> targetType)
      throws TargetTypeInstantiationException {

    try {
      targetType.newInstance();
    } catch (Exception ex) {
      TargetTypeInstantiationException exception =
          new TargetTypeInstantiationException(targetType, ex);
      logger.debug(exception.getMessage());
      throw exception;
    }

    return map(sources, () -> {
      try {
        return targetType.newInstance();
      } catch (Exception ex) {
        return null;
      }
    });

  }

  /**
   * @param sources   A list of object's to be mapped from.
   * @param supplier  Target type's supplier function.
   * @param <SourceT> source object' type.
   * @param <TargetT> target object's type.
   * @return A List<targetT> object of type targetType.
   */
  public static <SourceT, TargetT> Iterable<TargetT> map(Iterable<SourceT> sources,
                                                         Supplier<TargetT> supplier) {
    if (sources == null || supplier == null) {
      return null;
    }

    List<TargetT> targets = new ArrayList<TargetT>();
    sources.forEach(source -> targets.add(map(source, supplier)));

    return targets;
  }
}


text:
package com.querydsl.apt.domain;

import static org.junit.Assert.assertNotNull;

import org.junit.Test;

import com.querydsl.core.annotations.Config;
import com.querydsl.core.annotations.QueryEntity;

public class QuerydslConfig2Test {

    @Config(entityAccessors = true)
    @QueryEntity
    public static class Entity extends Superclass {

        Entity prop1;

    }

    @Config(createDefaultVariable = false)
    @QueryEntity
    public static class Entity2 extends Superclass2 {

        Entity prop1;

    }

    @QueryEntity
    public static class Superclass {

        Entity prop2;
    }

    @Config(entityAccessors = true)
    @QueryEntity
    public static class Superclass2 {

        Entity prop2;
    }

    @Test
    public void test() {
        assertNotNull(QQuerydslConfig2Test_Entity.entity);
    }

    @Test(expected = NoSuchFieldException.class)
    public void Create_Default_Variable() throws SecurityException, NoSuchFieldException {
        QQuerydslConfig2Test_Entity2.class.getField("entity2");
    }
}


text:
===============
DbfCmd Notices
===============

Copyright 2012 Various Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Contributors
=============

The following people have contributed code and licensed their contributions
under the Apache License, Version 2.0:

* Stephen Jennings <http://github.com/jennings>