text:
package net.orfjackal.retrolambda.lambdas;

import net.orfjackal.retrolambda.fs.*;

import java.io.*;
import java.lang.reflect.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.file.FileSystem;
import java.nio.file.*;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.spi.FileSystemProvider;
import java.util.Set;

public class LambdaClassDumper implements AutoCloseable {

    private final LambdaClassSaver lambdaClassSaver;
    private Field dumperField;

    public LambdaClassDumper(LambdaClassSaver lambdaClassSaver) {
        this.lambdaClassSaver = lambdaClassSaver;
    }

    public void install() {
        try {
            Class<?> mf = Class.forName("java.lang.invoke.InnerClassLambdaMetafactory");
            dumperField = mf.getDeclaredField("dumper");
            makeNonFinal(dumperField);
            dumperField.setAccessible(true);

            Path p = new VirtualPath("");
            dumperField.set(null, newProxyClassesDumper(p));
        } catch (Exception e) {
            throw new IllegalStateException("Cannot initialize dumper; unexpected JDK implementation. " +
                    "Please run Retrolambda using the Java agent (enable forking in the Maven plugin).", e);
        }
    }

    public void uninstall() {
        if (dumperField != null) {
            try {
                dumperField.set(null, null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void close() {
        uninstall();
    }

    private static void makeNonFinal(Field field) throws Exception {
        Field modifiers = field.getClass().getDeclaredField("modifiers");
        modifiers.setAccessible(true);
        int mod = modifiers.getInt(field);
        modifiers.setInt(field, mod & ~Modifier.FINAL);
    }

    private static Object newProxyClassesDumper(Path dumpDir) throws Exception {
        Class<?> dumper = Class.forName("java.lang.invoke.ProxyClassesDumper");
        Constructor<?> c = dumper.getDeclaredConstructor(Path.class);
        c.setAccessible(true);
        return c.newInstance(dumpDir);
    }

    private final class VirtualFSProvider extends FakeFileSystemProvider {

        @Override
        public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) {
            return new ClassChannel(path);
        }

        @Override
        public void createDirectory(Path dir, FileAttribute<?>... attrs) {
        }
    }

    private final class VirtualFS extends FakeFileSystem {

        @Override
        public FileSystemProvider provider() {
            return new VirtualFSProvider();
        }
    }

    private final class VirtualPath extends FakePath {

        private final String path;

        public VirtualPath(String path) {
            this.path = path;
        }

        @Override
        public FileSystem getFileSystem() {
            return new VirtualFS();
        }

        @Override
        public Path getParent() {
            return this;
        }

        @Override
        public Path resolve(String other) {
            if (!path.isEmpty()) {
                throw new IllegalStateException();
            }
            return new VirtualPath(other);
        }

        @Override
        public String toString() {
            return path;
        }
    }

    private final class ClassChannel extends FakeSeekableByteChannel {
        private final Path path;
        private final ByteArrayOutputStream os;
        private final WritableByteChannel ch;

        public ClassChannel(Path path) {
            this.path = path;
            this.os = new ByteArrayOutputStream();
            this.ch = Channels.newChannel(os);
        }

        @Override
        public int write(ByteBuffer src) throws IOException {
            return ch.write(src);
        }

        @Override
        public void close() {
            String className = path.toString();
            className = className.substring(0, className.lastIndexOf(".class"));
            lambdaClassSaver.saveIfLambda(className, os.toByteArray());
        }
    }
}


text:
using Xunit;

namespace CSharpFormatting.Library.IntegrationTest
{
    public class MixedMarkdown
    {
        [Fact]
        public void MarkdownGetsWellWithCsharp()
        {
            var html = TestHelper.JustBody(new CSharpFormatter().GetHtmlForMarkdownContent("# Hello!\r\n    [csharp]\r\n    var aiujk = 9;"));
            Assert.Contains("Hello", html);
            Assert.Contains("aiujk", html);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package utask.model.task;

import utask.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's Frequency in the address book.
 * Guarantees: immutable; is valid as declared in {@link #isValidFrequency(String)}
 */
public class Frequency {

    public static final String MESSAGE_FREQUENCY_CONSTRAINTS =
            "Task frequency should not be blank";

    /*
     * The first character of the address must not be a whitespace,
     * otherwise " " (a blank string) becomes a valid input.
     */
    public static final String FREQUENCY_VALIDATION_REGEX = "[^\\s].*";
    public static final String FREQUENCY_REMOVAL_VALIDATION_REGEX = "^[-]$";

    public final String value;

    /**
     * Validates given frequency.
     *
     * @throws IllegalValueException if given frequency string is invalid.
     */
    public Frequency(String frequency) throws IllegalValueException {
        assert frequency != null;
        if (!isValidFrequency(frequency)) {
            throw new IllegalValueException(MESSAGE_FREQUENCY_CONSTRAINTS);
        }
        this.value = frequency;
    }

    private Frequency() {
        this.value = "";
    }

    public static Frequency getEmptyFrequency() {
        return new Frequency();
    }

    public boolean isEmpty() {
        return "".equals(value);
    }

    /**
     * Returns true if a given string is a valid task email.
     */
    public static boolean isValidFrequency(String test) {
        return test.matches(FREQUENCY_VALIDATION_REGEX);
    }

    @Override
    public String toString() {
        return value;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof Frequency // instanceof handles nulls
                && this.value.equals(((Frequency) other).value)); // state check
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

}


text:
using namespace smoke_jni;
static int __log_priority = smoke_priority::LOG_INFO;

void set_log_priority(int priority) {
    __log_priority = priority;
}

static void __va_console_println(int level, const char *tag, const char *function,
                                 const char *fmt, va_list _vars) {
    if (level < __log_priority) {
        return;
    }

    char fmt_buf[4 * 1024] = {0};
    vsnprintf(fmt_buf, sizeof(fmt_buf),fmt,_vars);

    unsigned int full_size = strlen(function) + strlen(fmt_buf) + 4;
    char full_buf[full_size];
    memset(full_buf, 0,sizeof(full_buf));
    strcpy(full_buf,"[");
    strcat(full_buf,function);
    strcat(full_buf,"] ");
    strcat(full_buf,fmt_buf);
    smoke::_console_println(level,tag,full_buf);
}

void smoke_jni::console_println(int level, const char *tag, const char *function, const char *fmt, ...) {
    va_list arg_list;
    va_start(arg_list,fmt);
    __va_console_println(level, tag, function, fmt, arg_list);
    va_end(arg_list);
}

void smoke_jni::va_console_println(int level, const char *tag, const char *function, const char *fmt, va_list arg_list) {
    __va_console_println(level, tag, function, fmt, arg_list);
}

void smoke_jni::console_verbose(const char *function, const char *fmt, ...) {
    va_list arg_list;
    va_start(arg_list,fmt);
    __va_console_println(smoke_priority::LOG_VERBOSE, __global_tag, function, fmt, arg_list);
    va_end(arg_list);
}

void smoke_jni::va_console_verbose(const char *function, const char *fmt,  va_list arg_list) {
    __va_console_println(smoke_priority::LOG_VERBOSE, __global_tag, function, fmt, arg_list);
}

void smoke_jni::console_debug(const char *function, const char *fmt, ...) {
    va_list arg_list;
    va_start(arg_list,fmt);

    __va_console_println(smoke_priority::LOG_DEBUG, __global_tag, function, fmt, arg_list);

    va_end(arg_list);
}

void smoke_jni::va_console_debug(const char *function, const char *fmt, va_list arg_list) {
    __va_console_println(smoke_priority::LOG_DEBUG, __global_tag, function, fmt, arg_list);
}

void smoke_jni::console_info(const char *function, const char *fmt, ...) {
    va_list arg_list;
    va_start(arg_list,fmt);

    __va_console_println(smoke_priority::LOG_INFO, __global_tag, function, fmt, arg_list);

    va_end(arg_list);
}

void smoke_jni::va_console_info(const char *function, const char *fmt, va_list args) {
    __va_console_println(smoke_priority::LOG_INFO, __global_tag, function, fmt, args);
}

void smoke_jni::console_warn(const char *function, const char *fmt, ...) {
    va_list arg_list;
    va_start(arg_list,fmt);
    __va_console_println(smoke_priority::LOG_WARN, __global_tag, function, fmt, arg_list);
    va_end(arg_list);
}

void smoke_jni::va_console_warn(const char *function, const char *fmt, va_list args) {
    __va_console_println(smoke_priority::LOG_WARN, __global_tag, function, fmt, args);
}

void smoke_jni::console_error(const char *function, const char *fmt, ...) {
    va_list arg_list;
    va_start(arg_list,fmt);
    __va_console_println(smoke_priority::LOG_ERROR, __global_tag, function, fmt, arg_list);
    va_end(arg_list);
}

void smoke_jni::va_console_error(const char *function, const char *fmt, va_list args) {
    __va_console_println(smoke_priority::LOG_ERROR, __global_tag, function, fmt, args);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.oukingtim.mapper.SysRoleMenuMapper">

	<select id="selectMenuIdsByRoleId" resultType="String">
		select menu_id from sys_role_menu where role_id = #{value}
	</select>
</mapper>


text:
using System;
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Logic.Models
{
    /// <summary> The swagger schema. </summary>
    public partial class SwaggerSchema
    {
        /// <summary> Initializes a new instance of SwaggerSchema. </summary>
        public SwaggerSchema()
        {
            Properties = new ChangeTrackingDictionary<string, SwaggerSchema>();
            RequiredProperties = new ChangeTrackingList<string>();
            AllOf = new ChangeTrackingList<SwaggerSchema>();
        }

        /// <summary> Initializes a new instance of SwaggerSchema. </summary>
        /// <param name="reference"> The reference. </param>
        /// <param name="schemaType"> The type. </param>
        /// <param name="title"> The title. </param>
        /// <param name="items"> The items schema. </param>
        /// <param name="properties"> The object properties. </param>
        /// <param name="additionalProperties"> The additional properties. </param>
        /// <param name="requiredProperties"> The object required properties. </param>
        /// <param name="maxProperties"> The maximum number of allowed properties. </param>
        /// <param name="minProperties"> The minimum number of allowed properties. </param>
        /// <param name="allOf"> The schemas which must pass validation when this schema is used. </param>
        /// <param name="discriminator"> The discriminator. </param>
        /// <param name="isReadOnly"> Indicates whether this property must be present in the a request. </param>
        /// <param name="xml"> The xml representation format for a property. </param>
        /// <param name="externalDocs"> The external documentation. </param>
        /// <param name="example"> The example value. </param>
        /// <param name="isNotificationUrlExtension"> Indicates the notification url extension. If this is set, the property's value should be a callback url for a webhook. </param>
        /// <param name="dynamicSchemaOld"> The dynamic schema configuration. </param>
        /// <param name="dynamicSchemaNew"> The dynamic schema configuration. </param>
        /// <param name="dynamicListNew"> The dynamic list. </param>
        /// <param name="dynamicTree"> The dynamic values tree configuration. </param>
        internal SwaggerSchema(string reference, SwaggerSchemaType? schemaType, string title, SwaggerSchema items, IDictionary<string, SwaggerSchema> properties, BinaryData additionalProperties, IList<string> requiredProperties, int? maxProperties, int? minProperties, IList<SwaggerSchema> allOf, string discriminator, bool? isReadOnly, SwaggerXml xml, SwaggerExternalDocumentation externalDocs, BinaryData example, bool? isNotificationUrlExtension, SwaggerCustomDynamicSchema dynamicSchemaOld, SwaggerCustomDynamicProperties dynamicSchemaNew, SwaggerCustomDynamicList dynamicListNew, SwaggerCustomDynamicTree dynamicTree)
        {
            Reference = reference;
            SchemaType = schemaType;
            Title = title;
            Items = items;
            Properties = properties;
            AdditionalProperties = additionalProperties;
            RequiredProperties = requiredProperties;
            MaxProperties = maxProperties;
            MinProperties = minProperties;
            AllOf = allOf;
            Discriminator = discriminator;
            IsReadOnly = isReadOnly;
            Xml = xml;
            ExternalDocs = externalDocs;
            Example = example;
            IsNotificationUrlExtension = isNotificationUrlExtension;
            DynamicSchemaOld = dynamicSchemaOld;
            DynamicSchemaNew = dynamicSchemaNew;
            DynamicListNew = dynamicListNew;
            DynamicTree = dynamicTree;
        }

        /// <summary> The reference. </summary>
        public string Reference { get; set; }
        /// <summary> The type. </summary>
        public SwaggerSchemaType? SchemaType { get; set; }
        /// <summary> The title. </summary>
        public string Title { get; set; }
        /// <summary> The items schema. </summary>
        public SwaggerSchema Items { get; set; }
        /// <summary> The object properties. </summary>
        public IDictionary<string, SwaggerSchema> Properties { get; }
        /// <summary>
        /// The additional properties.
        /// <para>
        /// To assign an object to this property use <see cref="BinaryData.FromObjectAsJson{T}(T, System.Text.Json.JsonSerializerOptions?)"/>.
        /// </para>
        /// <para>
        /// To assign an already formated json string to this property use <see cref="BinaryData.FromString(string)"/>.
        /// </para>
        /// <para>
        /// Examples:
        /// <list type="bullet">
        /// <item>
        /// <term>BinaryData.FromObjectAsJson("foo")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("\"foo\"")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromObjectAsJson(new { key = "value" })</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("{\"key\": \"value\"}")</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// </list>
        /// </para>
        /// </summary>
        public BinaryData AdditionalProperties { get; set; }
        /// <summary> The object required properties. </summary>
        public IList<string> RequiredProperties { get; }
        /// <summary> The maximum number of allowed properties. </summary>
        public int? MaxProperties { get; set; }
        /// <summary> The minimum number of allowed properties. </summary>
        public int? MinProperties { get; set; }
        /// <summary> The schemas which must pass validation when this schema is used. </summary>
        public IList<SwaggerSchema> AllOf { get; }
        /// <summary> The discriminator. </summary>
        public string Discriminator { get; set; }
        /// <summary> Indicates whether this property must be present in the a request. </summary>
        public bool? IsReadOnly { get; set; }
        /// <summary> The xml representation format for a property. </summary>
        public SwaggerXml Xml { get; set; }
        /// <summary> The external documentation. </summary>
        public SwaggerExternalDocumentation ExternalDocs { get; set; }
        /// <summary>
        /// The example value.
        /// <para>
        /// To assign an object to this property use <see cref="BinaryData.FromObjectAsJson{T}(T, System.Text.Json.JsonSerializerOptions?)"/>.
        /// </para>
        /// <para>
        /// To assign an already formated json string to this property use <see cref="BinaryData.FromString(string)"/>.
        /// </para>
        /// <para>
        /// Examples:
        /// <list type="bullet">
        /// <item>
        /// <term>BinaryData.FromObjectAsJson("foo")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("\"foo\"")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromObjectAsJson(new { key = "value" })</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("{\"key\": \"value\"}")</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// </list>
        /// </para>
        /// </summary>
        public BinaryData Example { get; set; }
        /// <summary> Indicates the notification url extension. If this is set, the property's value should be a callback url for a webhook. </summary>
        public bool? IsNotificationUrlExtension { get; set; }
        /// <summary> The dynamic schema configuration. </summary>
        public SwaggerCustomDynamicSchema DynamicSchemaOld { get; set; }
        /// <summary> The dynamic schema configuration. </summary>
        public SwaggerCustomDynamicProperties DynamicSchemaNew { get; set; }
        /// <summary> The dynamic list. </summary>
        public SwaggerCustomDynamicList DynamicListNew { get; set; }
        /// <summary> The dynamic values tree configuration. </summary>
        public SwaggerCustomDynamicTree DynamicTree { get; set; }
    }
}


text:
package jnipap;

/**
 * General input error exception
 */
class InputException extends JnipapException {

	// version ID for serialization
	private static final long serialVersionUID = 0L;

	public InputException(String msg) {
		super(msg);
	}

	public InputException(Throwable cause) {
		super(cause);
	}

}


text:
@interface TLMyQRCodeViewController : TLViewController

@property (nonatomic, strong) TLUser *user;

@end


text:
using Foundation;
using UIKit;
using Microsoft.Azure.Mobile;
using Microsoft.Azure.Mobile.Analytics;
using Microsoft.Azure.Mobile.Crashes;
using FFImageLoading.Forms.Touch;

namespace SafeOrizer.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {

        string VSMobileCenterAppId = "e57e54e2-1952-44d5-98bf-f43678a91bcd";
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {

            global::Xamarin.Forms.Forms.Init();

            // Mobile center integration
            MobileCenter.Start(this.VSMobileCenterAppId,
                    typeof(Analytics), typeof(Crashes));

            CachedImageRenderer.Init();

            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
    }
}


text:
var Backbone = require('backbone');

require('backbone.validation');
_.extend(Backbone.Model.prototype, Backbone.Validation.mixin);

// Customize global form error display
_.extend(Backbone.Validation.callbacks, {
    valid: function ($view, attr, selector) {
        var $field = $view.$('[name=' + attr + ']').parent();
        $field.removeClass('error');

        $field.find('.ui.red.pointing.label').remove();
     },
    invalid: function ($view, attr, error, selector) {
        var $field = $view.$('[name=' + attr + ']').parent();
        $field.addClass('error');

        // Remove older errors if present
        $field.find('.ui.red.pointing.label').remove();

        // Add the error field
        var $error = $('

')
            .addClass('ui red pointing above label')
            .text(error);
        $field.append($error);
    }
});


text:
{
  for (var i = 0; i < propertyNames.length; i++) {
    if (propertyNames[i] in object) return propertyNames[i];
  }
}


text:
package org.apache.kerby.kerberos.kerb;

import org.apache.kerby.kerberos.kerb.type.base.KrbError;

public class KrbErrorException extends KrbException {
    private static final long serialVersionUID = -6726737724490205771L;
    private KrbError krbError;

    public KrbErrorException(KrbError krbError) {
        super(krbError.getErrorCode().getMessage());
        this.krbError = krbError;
    }

    public KrbError getKrbError() {
        return krbError;
    }
}


text:
package apple.homekit.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NInt;

/**
 * [@enum] HMCharacteristicValueProgramMode
 * <p>
 * [@constant] HMCharacteristicValueProgramModeNotScheduled No programs scheduled.
 * [@constant] HMCharacteristicValueProgramModeScheduled Program scheduled.
 * [@constant] HMCharacteristicValueProgramModeScheduleOverriddenToManual Schedule currently overridden to manual mode.
 */
@Generated
public final class HMCharacteristicValueProgramMode {
    @Generated
    private HMCharacteristicValueProgramMode() {
    }

    @Generated @NInt public static final long NotScheduled = 0x0000000000000000L;
    @Generated @NInt public static final long Scheduled = 0x0000000000000001L;
    @Generated @NInt public static final long ScheduleOverriddenToManual = 0x0000000000000002L;
}


text:
'use strict';

var should = require('should'),
	request = require('supertest'),
	path = require('path'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	ManageContact = mongoose.model('ManageContact'),
	express = require(path.resolve('./config/lib/express'));

/**
 * Globals
 */
var app, agent, credentials, user, manageContact;

/**
 * Manage contact routes tests
 */
describe('Manage contact CRUD tests', function() {
	before(function(done) {
		// Get application
		app = express.init(mongoose);
		agent = request.agent(app);

		done();
	});

	beforeEach(function(done) {
		// Create user credentials
		credentials = {
			username: 'username',
			password: 'password'
		};

		// Create a new user
		user = new User({
			firstName: 'Full',
			lastName: 'Name',
			displayName: 'Full Name',
			email: 'test@test.com',
			username: credentials.username,
			password: credentials.password,
			provider: 'local'
		});

		// Save a user to the test db and create new Manage contact
		user.save(function() {
			manageContact = {
				name: 'Manage contact Name'
			};

			done();
		});
	});

	it('should be able to save Manage contact instance if logged in', function(done) {
		agent.post('/api/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Manage contact
				agent.post('/api/manage-contacts')
					.send(manageContact)
					.expect(200)
					.end(function(manageContactSaveErr, manageContactSaveRes) {
						// Handle Manage contact save error
						if (manageContactSaveErr) done(manageContactSaveErr);

						// Get a list of Manage contacts
						agent.get('/api/manage-contacts')
							.end(function(manageContactsGetErr, manageContactsGetRes) {
								// Handle Manage contact save error
								if (manageContactsGetErr) done(manageContactsGetErr);

								// Get Manage contacts list
								var manageContacts = manageContactsGetRes.body;

								// Set assertions
								(manageContacts[0].user._id).should.equal(userId);
								(manageContacts[0].name).should.match('Manage contact Name');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to save Manage contact instance if not logged in', function(done) {
		agent.post('/api/manage-contacts')
			.send(manageContact)
			.expect(403)
			.end(function(manageContactSaveErr, manageContactSaveRes) {
				// Call the assertion callback
				done(manageContactSaveErr);
			});
	});

	it('should not be able to save Manage contact instance if no name is provided', function(done) {
		// Invalidate name field
		manageContact.name = '';

		agent.post('/api/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Manage contact
				agent.post('/api/manage-contacts')
					.send(manageContact)
					.expect(400)
					.end(function(manageContactSaveErr, manageContactSaveRes) {
						// Set message assertion
						(manageContactSaveRes.body.message).should.match('Please fill Manage contact name');

						// Handle Manage contact save error
						done(manageContactSaveErr);
					});
			});
	});

	it('should be able to update Manage contact instance if signed in', function(done) {
		agent.post('/api/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Manage contact
				agent.post('/api/manage-contacts')
					.send(manageContact)
					.expect(200)
					.end(function(manageContactSaveErr, manageContactSaveRes) {
						// Handle Manage contact save error
						if (manageContactSaveErr) done(manageContactSaveErr);

						// Update Manage contact name
						manageContact.name = 'WHY YOU GOTTA BE SO MEAN?';

						// Update existing Manage contact
						agent.put('/api/manage-contacts/' + manageContactSaveRes.body._id)
							.send(manageContact)
							.expect(200)
							.end(function(manageContactUpdateErr, manageContactUpdateRes) {
								// Handle Manage contact update error
								if (manageContactUpdateErr) done(manageContactUpdateErr);

								// Set assertions
								(manageContactUpdateRes.body._id).should.equal(manageContactSaveRes.body._id);
								(manageContactUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should be able to get a list of Manage contacts if not signed in', function(done) {
		// Create new Manage contact model instance
		var manageContactObj = new ManageContact(manageContact);

		// Save the Manage contact
		manageContactObj.save(function() {
			// Request Manage contacts
			request(app).get('/api/manage-contacts')
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Array.with.lengthOf(1);

					// Call the assertion callback
					done();
				});

		});
	});

	it('should be able to get a single Manage contact if not signed in', function(done) {
		// Create new Manage contact model instance
		var manageContactObj = new ManageContact(manageContact);

		// Save the Manage contact
		manageContactObj.save(function() {
			request(app).get('/api/manage-contacts/' + manageContactObj._id)
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Object.with.property('name', manageContact.name);

					// Call the assertion callback
					done();
				});
		});
	});

	it('should be able to delete Manage contact instance if signed in', function(done) {
		agent.post('/api/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Manage contact
				agent.post('/api/manage-contacts')
					.send(manageContact)
					.expect(200)
					.end(function(manageContactSaveErr, manageContactSaveRes) {
						// Handle Manage contact save error
						if (manageContactSaveErr) done(manageContactSaveErr);

						// Delete existing Manage contact
						agent.delete('/api/manage-contacts/' + manageContactSaveRes.body._id)
							.send(manageContact)
							.expect(200)
							.end(function(manageContactDeleteErr, manageContactDeleteRes) {
								// Handle Manage contact error error
								if (manageContactDeleteErr) done(manageContactDeleteErr);

								// Set assertions
								(manageContactDeleteRes.body._id).should.equal(manageContactSaveRes.body._id);

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to delete Manage contact instance if not signed in', function(done) {
		// Set Manage contact user
		manageContact.user = user;

		// Create new Manage contact model instance
		var manageContactObj = new ManageContact(manageContact);

		// Save the Manage contact
		manageContactObj.save(function() {
			// Try deleting Manage contact
			request(app).delete('/api/manage-contacts/' + manageContactObj._id)
			.expect(403)
			.end(function(manageContactDeleteErr, manageContactDeleteRes) {
				// Set message assertion
				(manageContactDeleteRes.body.message).should.match('User is not authorized');

				// Handle Manage contact error error
				done(manageContactDeleteErr);
			});

		});
	});

	afterEach(function(done) {
		User.remove().exec(function(){
			ManageContact.remove().exec(function(){
				done();
			});
		});
	});
});


text:
require "spec_helper"
require "hamster/vector"

describe Hamster::Vector do
  describe "#compact" do
    it "returns a new Vector with all nils removed" do
      V[1, nil, 2, nil].compact.should eql(V[1, 2])
      V[1, 2, 3].compact.should eql(V[1, 2, 3])
      V[nil].compact.should eql(V[])
    end

    context "on an empty vector" do
      it "returns self" do
        Hamster.vector.compact.should be(Hamster.vector)
      end
    end

    it "doesn't remove false" do
      V[false].compact.should eql(V[false])
    end

    context "from a subclass" do
      it "returns an instance of the subclass" do
        subclass = Class.new(V)
        instance = subclass[1, nil, 2]
        instance.compact.class.should be(subclass)
      end
    end
  end
end


text:
#ifndef ROCKETCOREBITMAPFONTFACE_H
#define ROCKETCOREBITMAPFONTFACE_H

#include "../../../Include/Rocket/Core/FontFace.h"
#include "BitmapFontDefinitions.h"

namespace Rocket {
namespace Core {
namespace BitmapFont {

class FontFaceHandle;

/**
	@author Peter Curry
 */

class FontFace : public Rocket::Core::FontFace
{
public:
	FontFace(BitmapFontDefinitions *_face, Font::Style style, Font::Weight weight, bool release_stream);
	~FontFace();

	/// Returns a handle for positioning and rendering this face at the given size.
	/// @param[in] charset The set of characters in the handle, as a comma-separated list of unicode ranges.
	/// @param[in] size The size of the desired handle, in points.
	/// @return The shared font handle.
	Rocket::Core::FontFaceHandle* GetHandle(const String& charset, int size);

	/// Releases the face's FreeType face structure. This will mean handles for new sizes cannot be constructed,
	/// but existing ones can still be fetched.
	void ReleaseFace();

private:
	BitmapFontDefinitions *face;
};

}
}
}

#endif


text:
extern NSString* const kHistoryTableViewIdentifier;
// Accessibility identifier of the search controller search bar.
extern NSString* const kHistorySearchControllerSearchBarIdentifier;
// Accessibility identifier of the navigation controller done button.
extern NSString* const kHistoryNavigationControllerDoneButtonIdentifier;
// Accessibility identifier of the delete toolbar button.
extern NSString* const kHistoryToolbarDeleteButtonIdentifier;
// Accessibility identifier of the clear browsing data toolbar button.
extern NSString* const kHistoryToolbarClearBrowsingButtonIdentifier;
// Accessibility identifier of the edit toolbar button.
extern NSString* const kHistoryToolbarEditButtonIdentifier;
// Accessibility identifier of the cancel toolbar button.
extern NSString* const kHistoryToolbarCancelButtonIdentifier;
// Accessibility identifier for the scrim over TableView.
extern NSString* const kHistorySearchScrimIdentifier;

#endif  // IOS_CHROME_BROWSER_UI_HISTORY_HISTORY_UI_CONSTANTS_H_


text:
package org.apache.camel.reifier;

import org.apache.camel.Processor;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.model.UnmarshalDefinition;
import org.apache.camel.reifier.dataformat.DataFormatReifier;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.RouteContext;
import org.apache.camel.support.processor.UnmarshalProcessor;

public class UnmarshalReifier extends ProcessorReifier<UnmarshalDefinition> {

    UnmarshalReifier(ProcessorDefinition<?> definition) {
        super((UnmarshalDefinition) definition);
    }

    @Override
    public Processor createProcessor(RouteContext routeContext) {
        DataFormat dataFormat = DataFormatReifier.getDataFormat(routeContext.getCamelContext(), definition.getDataFormatType(), null);
        return new UnmarshalProcessor(dataFormat);
    }
}


text:
require 'rails_helper'

RSpec.describe 'search/person', type: :view do
  include PermittedDomainHelper

  before(:all) do
    clean_up_indexes_and_tables
    PermittedDomain.find_or_create_by(domain: 'digital.justice.gov.uk')
    create_list(:group, 4).each do |team|
      create(:person, :member_of, team: team, sole_membership: true)
    end
    Person.import force: true
    Person.__elasticsearch__.refresh_index!
  end

  after(:all) do
    clean_up_indexes_and_tables
  end

  let(:people_results) do
    Person.search(match_all).records
  end

  before do
    controller.singleton_class.class_eval do
      def current_user
        Person.first
      end
      helper_method :current_user
    end

    people_results.each_with_hit.with_index do |(person, hit), idx|
      render partial: 'search/person', locals: { person: person, hit: hit, index: idx, current_user: controller.current_user }
    end
  end

  shared_examples 'sets analytics attributes' do
    it "sets data-event-category correctly on links" do
      list.each do |item|
        expect(rendered).to have_selector('[data-event-category="Search result click"]', text: item)
      end
    end

    it "sets data-event-action correctly on links" do
      list.each.with_index do |item, idx|
        expect(rendered).to have_selector("[data-event-action=\"Click result 00#{idx+1}\"]", text: item)
      end
    end

    it "sets data-virtual-pageview correctly on links" do
      expect(rendered).to have_selector(".#{div} [data-virtual-pageview=\"/search-result,/top-3-search-result\"]", count: 3)
      expect(rendered).to have_selector(".#{div} [data-virtual-pageview=\"/search-result,/below-top-3-search-result\"]", count: 1)
    end
  end

  describe 'people links' do
    let(:list) { people_results.map(&:name) }
    let(:div) { 'cb-person-name' }

    include_examples 'sets analytics attributes'
  end

  describe 'team links' do
    let(:div) { 'cb-person-memberships' }
    let(:list) do
      people_results.map do |person|
        person.memberships.map do |membership|
          membership.group.name
        end
      end.flatten
    end

    include_examples 'sets analytics attributes'
  end

  describe 'email links' do
    let(:div) { 'cb-person-email' }
    let(:list) { people_results.map(&:email) }

    include_examples 'sets analytics attributes'
  end

end


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.clients.commerce.orders;

import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import org.joda.time.DateTime;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;

/**
 * Manage the results of order validation.
 *
 */
public class OrderValidationResultClient {

	/**
	 * Retrieves a list of the validation results associated with the order.
	 *

	 * MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult>> mozuClient=GetValidationResultsClient( orderId);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * OrderValidationResult orderValidationResult = client.Result();
	 *

	 * @param orderId Unique identifier of the order.
	 * @return Mozu.Api.MozuClient <List<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult>>
	 * @see com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult
	 */
	public static MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult>> getValidationResultsClient(String orderId) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.orders.OrderValidationResultUrl.getValidationResultsUrl(orderId);
		String verb = "GET";
		Class<?> clz = new ArrayList<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult>(){}.getClass();
		MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult>> mozuClient = (MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult>>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 * Add a new order validation result to a submitted order.
	 *

	 * MozuClient<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult> mozuClient=AddValidationResultClient( validationResult,  orderId);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * OrderValidationResult orderValidationResult = client.Result();
	 *

	 * @param orderId Unique identifier of the order.
	 * @param validationResult Properties of the resulting order validation performed by an order validation capability.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult>
	 * @see com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult
	 * @see com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult
	 */
	public static MozuClient<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult> addValidationResultClient(com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult validationResult, String orderId) throws Exception
	{
		return addValidationResultClient( validationResult,  orderId,  null);
	}

	/**
	 * Add a new order validation result to a submitted order.
	 *

	 * MozuClient<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult> mozuClient=AddValidationResultClient( validationResult,  orderId,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * OrderValidationResult orderValidationResult = client.Result();
	 *

	 * @param orderId Unique identifier of the order.
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param validationResult Properties of the resulting order validation performed by an order validation capability.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult>
	 * @see com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult
	 * @see com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult
	 */
	public static MozuClient<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult> addValidationResultClient(com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult validationResult, String orderId, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.orders.OrderValidationResultUrl.addValidationResultUrl(orderId, responseFields);
		String verb = "PUT";
		Class<?> clz = com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult.class;
		MozuClient<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.orders.OrderValidationResult>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(validationResult);
		return mozuClient;

	}

}


text:
int Athena_UIDrawButtons(struct Athena_ButtonList *buttons, struct Athena_Viewport *onto){
    if(!buttons){
        return 0;
    }
    else{
        onto->x = buttons->button.x;
        onto->y = buttons->button.y;
        onto->w = buttons->button.w;
        onto->h = buttons->button.h;
        Athena_DrawDefaultWindowStyle(onto);
        WriteString(GetSystemFont(), buttons->button.text, onto->image, buttons->button.x + 4, buttons->button.y + 4);

        if(buttons->button.clicked){
            buttons->button.clicked--;
            Athena_BlendViewport(onto, Athena_RGBAToRaw(0xFF>>1, 0xFF>>1, 0xFF>>1, 0xFF), Athena_RGBARawMultiply);
        }

        return Athena_UIDrawButtons(buttons->next, onto);
    }
}

int Athena_FreeButtonList(struct Athena_ButtonList *buttons){
    if(!buttons)
        return 0;
    else {
        struct Athena_ButtonList *next = buttons->next;
        Athena_FreeButtonArgList(buttons->button.arg);
        free(buttons);
        return Athena_FreeButtonList(next);
    }
}

int Athena_FreeButtonArgList(struct Athena_ButtonArgList *args){
    if(!args)
        return 0;
    else {
        struct Athena_ButtonArgList *arg = args->next;
        free(args);
        return Athena_FreeButtonArgList(arg);
    }
}

struct Athena_ButtonArgList *Athena_DefaultButtonArgList(struct Athena_GameState *arg){
    struct Athena_ButtonArgList *const arg_list = malloc(sizeof(struct Athena_ButtonArgList));
    arg_list->arg = arg;
    arg_list->next = NULL;
    arg_list->type = "game_state";
    return arg_list;
}

int Athena_AppendButtonArgList(struct Athena_ButtonArgList *list, void *arg, const char *type){
    if(list->next)
        return Athena_AppendButtonArgList(list->next, arg, type);
    else{
        list->next = malloc(sizeof(struct Athena_ButtonArgList));
        list->next->arg = arg;
        list->next->type = type;
        list->next->next = NULL;
        return 0;
    }
}

void Athena_CopyButtonArgList(struct Athena_ButtonArgList **to, struct Athena_ButtonArgList *from){
    if(!from)
        to[0] = NULL;
    else{
        to[0] = malloc(sizeof(struct Athena_ButtonArgList));
        to[0]->type= from->type;
        to[0]->arg = from->arg;
        Athena_CopyButtonArgList(&(to[0]->next), from->next);
    }
}

void *Athena_FindTypeInArgList(struct Athena_ButtonArgList *list, const char *type){
    if(!list)
        return NULL;
    else if(strcmp(type, list->type)==0)
        return list->arg;
    else
        return Athena_FindTypeInArgList(list->next, type);
}

struct Athena_Button *Athena_AppendButtonList(struct Athena_ButtonList **to, struct Athena_ButtonList *button){
    if(to[0]==NULL){
        to[0] = button;
        return &to[0]->button;
    }
    else
        return Athena_AppendButtonList(&(to[0]->next), button);
}

struct Athena_Button *Athena_AppendButton(struct Athena_ButtonList **to, struct Athena_Button button){
    struct Athena_ButtonList *const b = malloc(sizeof(struct Athena_ButtonList));
    b->button = button;
    b->next = NULL;
    return Athena_AppendButtonList(to, b);
}

static int athena_ui_process_buttons_iter(struct Athena_GameState *that, struct Athena_ButtonList *buttons, const struct Athena_Event *event, struct Athena_MessageList *messages){
    if(!buttons){
        return 0;
    }
    else{
        if(
            (buttons->button.clicked = Athena_IsWithin(buttons->button, event->x, event->y) << 2) &&
            buttons->button.callback){
            if(that && that->ui.click_sound)
                Athena_SoundPlay(that->ui.click_sound);
            buttons->button.callback(buttons->button.arg, messages);
            return 1;
        }
        return athena_ui_process_buttons_iter(that, buttons->next, event, messages);
    }
}

int Athena_ProcessButtons(struct Athena_GameState *that, struct Athena_ButtonList *buttons, const struct Athena_Event *event, struct Athena_MessageList *messages){
    return athena_ui_process_buttons_iter(that, buttons, event, messages);
}


text:
"""Coordinate transformation functions for pysat."""

import datetime as dt
import numpy as np
import pandas as pds

import pysat

logger = pysat.logger

def adjust_cyclic_data(samples, high=2.0 * np.pi, low=0.0):
    """Adjust cyclic values such as longitude to a different scale.

    Parameters
    ----------
    samples : array_like
        Input array
    high: float or int
        Upper boundary for circular standard deviation range (default=2 pi)
    low : float or int
        Lower boundary for circular standard deviation range (default=0)
    axis : int or NoneType
        Axis along which standard deviations are computed.  The default is to
        compute the standard deviation of the flattened array

    Returns
    -------
    out_samples : float
        Circular standard deviation

    """

    out_samples = np.asarray(samples)
    sample_range = high - low
    out_samples[out_samples >= high] -= sample_range
    out_samples[out_samples < low] += sample_range

    return out_samples

def update_longitude(inst, lon_name=None, high=180.0, low=-180.0):
    """Update longitude to the desired range.

    Parameters
    ----------
    inst : pysat.Instrument
        Instrument class object to be updated
    lon_name : str
        Name of the longtiude data in `inst`
    high : float
        Highest allowed longitude value (default=180.0)
    low : float
        Lowest allowed longitude value (default=-180.0)

    Note
    ----
    Updates instrument data in column provided by `lon_name`

    """
    if lon_name not in inst.variables:
        raise ValueError('unknown longitude variable name')

    inst[lon_name] = adjust_cyclic_data(inst[lon_name], high=high, low=low)

    return

def calc_solar_local_time(inst, lon_name=None, slt_name='slt',
                          apply_modulus=True, ref_date=None):
    """Append solar local time to an instrument object.

    Parameters
    ----------
    inst : pysat.Instrument
        Instrument class object to be updated
    lon_name : str
        Name of the longtiude data key (assumes data are in degrees)
    slt_name : str
        Name of the output solar local time data key (default='slt')
    apply_modulus : bool
        If True, SLT values are confined to [0, 24), if False they may be
        positive or negative based on the value of their universal time
        relative to that of the reference date `ref_date`.
        (default=True)
    ref_date : dt.datetime or NoneType
        Reference initial date. If None, will use the date found at
        `inst.date`. Only valid if apply_modulus is True. (default=None)

    Note
    ----
    Updates Instrument data in column specified by `slt_name`, as well as
    Metadata

    """
    fill_val = np.nan

    if lon_name not in inst.data.keys():
        raise ValueError('unknown longitude variable name')

    if ref_date is not None and apply_modulus:
        istr = 'Keyword `ref_date` only supported if `apply_modulus`=False.'
        logger.info(istr)

    if ref_date is None:
        # Use date information attached to Instrument object
        ref_date = pds.Timestamp(inst.date)
    else:
        # Use user supplied reference date.
        ref_date = pds.Timestamp(ref_date)

    # Convert from numpy epoch nanoseconds to UT seconds of day
    ut_hr = list()
    for nptime in inst.index.values.astype(np.int64):
        # Numpy times come out in nanoseconds and timestamp converts
        # from seconds
        dtime = dt.datetime.utcfromtimestamp(nptime * 1.0e-9)
        ut_hr.append((dtime.hour * 3600.0 + dtime.minute * 60.0
                      + dtime.second + dtime.microsecond * 1.0e-6) / 3600.0)

    ut_hr = np.array(ut_hr)

    # Account for difference in days for calculations without modulus
    if not apply_modulus:
        day_diff = inst.index - ref_date
        day_diff = np.array([diff.days for diff in day_diff])
        ut_hr += day_diff * 24.

    # Calculate solar local time
    if inst[lon_name].shape == ut_hr.shape or inst[lon_name].shape == ():
        if inst[lon_name].shape == ():
            lon = np.float64(inst[lon_name])
        else:
            lon = inst[lon_name]

        slt = ut_hr + lon / 15.0
        coords = inst.index.name
    else:
        # This can only be accessed by xarray input, but longitude may or
        # may not depend on time
        if inst.index.name in inst[lon_name].coords:
            # Initalize the new shape and coordinatesx
            coords = [ckey for ckey in inst[lon_name].dims]
            slt = np.full(shape=inst[lon_name].shape, fill_value=fill_val)

            # Calculate for each UT hr
            for i, hr in enumerate(ut_hr):
                lon = inst[lon_name][inst.index.name == inst.index[0]]
                slt[i] = hr + lon / 15.0
        else:
            # Initialize the new shape and coordinates
            sshape = list(ut_hr.shape)
            sshape.extend(list(inst[lon_name].shape))

            coords = [ckey for ckey in inst[lon_name].dims]
            coords.insert(0, inst.index.name)

            slt = np.full(shape=sshape, fill_value=fill_val)

            # Calculate for each UT hr
            for i, hr in enumerate(ut_hr):
                slt[i] = hr + inst[lon_name] / 15.0

    if apply_modulus:
        # Ensure that solar local time falls between 0 and 24 hours
        slt = np.mod(slt, 24.0)
        min_val = 0.0
        max_val = 24.0
    else:
        # No modulus applied. Values are unbounded.
        min_val = -np.inf
        max_val = np.inf

    # Add the solar local time to the instrument
    if inst.pandas_format:
        inst[slt_name] = pds.Series(slt, index=inst.index)
    else:
        inst.data = inst.data.assign({slt_name: (coords, slt.data)})

    # Add units to the metadata
    inst.meta[slt_name] = {inst.meta.labels.units: 'h',
                           inst.meta.labels.name: "Solar Local Time",
                           inst.meta.labels.desc: "Solar local time in hours",
                           inst.meta.labels.min_val: min_val,
                           inst.meta.labels.max_val: max_val,
                           inst.meta.labels.fill_val: fill_val}

    return


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Package org.apache.solr.security (Solr 6.3.0 API)</title>
<meta name="date" content="2016-11-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.apache.solr.security

Packages that use org.apache.solr.security

Package
Description

org.apache.solr.core

Core classes implementing Solr internals and the management of SolrCores

org.apache.solr.handler

Concrete implementations of SolrRequestHandler

org.apache.solr.handler.admin

SolrRequestHandler implementations for powering he Solr Admin UI

org.apache.solr.handler.component

SearchComponent implementations for
 use in SearchHandler

org.apache.solr.security

Commonly used classes for Solr security framework.

org.apache.solr.servlet

Servlet related classes for powering the Solr HTTP API

Classes in org.apache.solr.security used by org.apache.solr.core

Class and Description

AuthenticationPlugin

AuthorizationPlugin

Authorization interface that needs to be implemented to write an authorization
 plugin.

PKIAuthenticationPlugin

Classes in org.apache.solr.security used by org.apache.solr.handler

Class and Description

AuthorizationContext

Request context for Solr to be used by Authorization plugin.

PermissionNameProvider

A requestHandler should implement this interface to provide the well known permission
 at request time

PermissionNameProvider.Name

Classes in org.apache.solr.security used by org.apache.solr.handler.admin

Class and Description

AuthorizationContext

Request context for Solr to be used by Authorization plugin.

PermissionNameProvider

A requestHandler should implement this interface to provide the well known permission
 at request time

PermissionNameProvider.Name

Classes in org.apache.solr.security used by org.apache.solr.handler.component

Class and Description

AuthorizationContext

Request context for Solr to be used by Authorization plugin.

PermissionNameProvider

A requestHandler should implement this interface to provide the well known permission
 at request time

PermissionNameProvider.Name

Classes in org.apache.solr.security used by org.apache.solr.security

Class and Description

AuthenticationPlugin

AuthorizationContext

Request context for Solr to be used by Authorization plugin.

AuthorizationContext.CollectionRequest

AuthorizationContext.RequestType

AuthorizationPlugin

Authorization interface that needs to be implemented to write an authorization
 plugin.

AuthorizationResponse

BasicAuthPlugin.AuthenticationProvider

ConfigEditablePlugin

An interface to be implemented by a Plugin whose Configuration is runtime editable

HttpClientInterceptorPlugin

PermissionNameProvider.Name

Classes in org.apache.solr.security used by org.apache.solr.servlet

Class and Description

AuthorizationContext.RequestType

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
/* Task scheduling / events module for Chrome EC operating system */

#include "atomic.h"
#include "common.h"
#include "console.h"
#include "cpu.h"
#include "link_defs.h"
#include "task.h"
#include "timer.h"
#include "uart.h"
#include "util.h"

typedef union {
	struct {
		/*
		 * Note that sp must be the first element in the task struct
		 * for __switchto() to work.
		 */
		uint32_t sp;       /* Saved stack pointer for context switch */
		uint32_t events;   /* Bitmaps of received events */
		uint64_t runtime;  /* Time spent in task */
		uint32_t *stack;   /* Start of stack */
	};
} task_;

/* Value to store in unused stack */
#define STACK_UNUSED_VALUE 0xdeadd00d

/* declare task routine prototypes */
#define TASK(n, r, d, s) int r(void *);
void __idle(void);
CONFIG_TASK_LIST
CONFIG_TEST_TASK_LIST
#undef TASK

/* Task names for easier debugging */
#define TASK(n, r, d, s)  #n,
static const char * const task_names[] = {
	"<< idle >>",
	CONFIG_TASK_LIST
	CONFIG_TEST_TASK_LIST
};
#undef TASK

#ifdef CONFIG_TASK_PROFILING
static uint64_t task_start_time; /* Time task scheduling started */
static uint64_t exc_start_time;  /* Time of task->exception transition */
static uint64_t exc_end_time;    /* Time of exception->task transition */
static uint64_t exc_total_time;  /* Total time in exceptions */
static uint32_t svc_calls;       /* Number of service calls */
static uint32_t task_switches;   /* Number of times active task changed */
static uint32_t irq_dist[CONFIG_IRQ_COUNT];  /* Distribution of IRQ calls */
#endif

extern void __switchto(task_ *from, task_ *to);
extern int __task_start(int *task_stack_ready);

#ifndef CONFIG_LOW_POWER_IDLE
/* Idle task.  Executed when no tasks are ready to be scheduled. */
void __idle(void)
{
	while (1) {
		/*
		 * Wait for the next irq event.  This stops the CPU clock
		 * (sleep / deep sleep, depending on chip config).
		 */
		asm("wfi");
	}
}
#endif /* !CONFIG_LOW_POWER_IDLE */

static void task_exit_trap(void)
{
	int i = task_get_current();
	cprints(CC_TASK, "Task %d (%s) exited!", i, task_names[i]);
	/* Exited tasks simply sleep forever */
	while (1)
		task_wait_event(-1);
}

/* Startup parameters for all tasks. */
#define TASK(n, r, d, s)  {	\
	.r0 = (uint32_t)d,	\
	.pc = (uint32_t)r,	\
	.stack_size = s,	\
},
static const struct {
	uint32_t r0;
	uint32_t pc;
	uint16_t stack_size;
} const tasks_init[] = {
	TASK(IDLE, __idle, 0, IDLE_TASK_STACK_SIZE)
	CONFIG_TASK_LIST
	CONFIG_TEST_TASK_LIST
};
#undef TASK

/* Contexts for all tasks */
static task_ tasks[TASK_ID_COUNT];
/* Sanity checks about static task invariants */
BUILD_ASSERT(TASK_ID_COUNT <= sizeof(unsigned) * 8);
BUILD_ASSERT(TASK_ID_COUNT < (1 << (sizeof(task_id_t) * 8)));

/* Stacks for all tasks */
#define TASK(n, r, d, s)  + s
uint8_t task_stacks[0
		    TASK(IDLE, __idle, 0, IDLE_TASK_STACK_SIZE)
		    CONFIG_TASK_LIST
		    CONFIG_TEST_TASK_LIST
] __aligned(8);

#undef TASK

/* Reserve space to discard context on first context switch. */
uint32_t scratchpad[17];

static task_ *current_task = (task_ *)scratchpad;

/*
 * Should IRQs chain to svc_handler()?  This should be set if either of the
 * following is true:
 *
 * 1) Task scheduling has started, and task profiling is enabled.  Task
 * profiling does its tracking in svc_handler().
 *
 * 2) An event was set by an interrupt; this could result in a higher-priority
 * task unblocking.  After checking for a task switch, svc_handler() will clear
 * the flag (unless profiling is also enabled; then the flag remains set).
 */
int need_resched_or_profiling;

/*
 * Bitmap of all tasks ready to be run.
 *
 * Currently all tasks are enabled at startup.
 */
static uint32_t tasks_ready = (1<<TASK_ID_COUNT) - 1;

static int start_called;  /* Has task swapping started */

static inline task_ *__task_id_to_ptr(task_id_t id)
{
	return tasks + id;
}

void interrupt_disable(void)
{
	asm("cpsid i");
}

void interrupt_enable(void)
{
	asm("cpsie i");
}

inline int in_interrupt_context(void)
{
	int ret;
	asm("mrs %0, ipsr\n"              /* read exception number */
	    "lsl %0, #23\n" : "=r"(ret)); /* exception bits are the 9 LSB */
	return ret;
}

inline int get_interrupt_context(void)
{
	int ret;
	asm("mrs %0, ipsr\n" : "=r"(ret)); /* read exception number */
	return ret & 0x1ff;                /* exception bits are the 9 LSB */
}

task_id_t task_get_current(void)
{
	return current_task - tasks;
}

uint32_t *task_get_event_bitmap(task_id_t tskid)
{
	task_ *tsk = __task_id_to_ptr(tskid);
	return &tsk->events;
}

int task_start_called(void)
{
	return start_called;
}

/**
 * Scheduling system call
 */
task_ *__svc_handler(int desched, task_id_t resched)
{
	task_ *current, *next;
#ifdef CONFIG_TASK_PROFILING
	int exc = get_interrupt_context();
	uint64_t t;
#endif

	/* Priority is already at 0 we cannot be interrupted */

#ifdef CONFIG_TASK_PROFILING
	/*
	 * SVCall isn't triggered via DECLARE_IRQ(), so it needs to track its
	 * start time explicitly.
	 */
	if (exc == 0xb) {
		exc_start_time = get_time().val;
		svc_calls++;
	}
#endif

	current = current_task;

#ifdef CONFIG_DEBUG_STACK_OVERFLOW
	if (*current->stack != STACK_UNUSED_VALUE) {
		panic_printf("\n\nStack overflow in %s task!\n",
			     task_names[current - tasks]);
		panic_reboot();
	}
#endif

	if (desched && !current->events) {
		/*
		 * Remove our own ready bit (current - tasks is same as
		 * task_get_current())
		 */
		tasks_ready &= ~(1 << (current - tasks));
	}
	tasks_ready |= 1 << resched;

	ASSERT(tasks_ready);
	next = __task_id_to_ptr(31 - __builtin_clz(tasks_ready));

#ifdef CONFIG_TASK_PROFILING
	/* Track time in interrupts */
	t = get_time().val;
	exc_total_time += (t - exc_start_time);

	/*
	 * Bill the current task for time between the end of the last interrupt
	 * and the start of this one.
	 */
	current->runtime += (exc_start_time - exc_end_time);
	exc_end_time = t;
#else
	/*
	 * Don't chain here from interrupts until the next time an interrupt
	 * sets an event.
	 */
	need_resched_or_profiling = 0;
#endif

	/* Switch to new task */
#ifdef CONFIG_TASK_PROFILING
	if (next != current)
		task_switches++;
#endif
	current_task = next;
	return current;
}

void svc_handler(int desched, task_id_t resched)
{
	/*
	 * The layout of the this routine (and the __svc_handler companion one)
	 * ensures that we are getting the right tail call optimization from
	 * the compiler.
	 */
	task_ *prev = __svc_handler(desched, resched);
	if (current_task != prev)
		__switchto(prev, current_task);
}

void __schedule(int desched, int resched)
{
	register int p0 asm("r0") = desched;
	register int p1 asm("r1") = resched;

	asm("svc 0" : : "r"(p0), "r"(p1));
}

#ifdef CONFIG_TASK_PROFILING
void task_start_irq_handler(void *excep_return)
{
	/*
	 * Get time before checking depth, in case this handler is
	 * pre-empted.
	 */
	uint64_t t = get_time().val;
	int irq = get_interrupt_context() - 16;

	/*
	 * Track IRQ distribution.  No need for atomic add, because an IRQ
	 * can't pre-empt itself.
	 */
	if (irq < ARRAY_SIZE(irq_dist))
		irq_dist[irq]++;

	/*
	 * Continue iff a rescheduling event happened or profiling is active,
	 * and we are not called from another exception (this must match the
	 * logic for when we chain to svc_handler() below).
	 */
	if (!need_resched_or_profiling || (((uint32_t)excep_return & 0xf) == 1))
		return;

	exc_start_time = t;
}
#endif

static uint32_t __wait_evt(int timeout_us, task_id_t resched)
{
	task_ *tsk = current_task;
	task_id_t me = tsk - tasks;
	uint32_t evt;
	int ret __attribute__((unused));

	ASSERT(!in_interrupt_context());

	if (timeout_us > 0) {
		timestamp_t deadline = get_time();
		deadline.val += timeout_us;
		ret = timer_arm(deadline, me);
		ASSERT(ret == EC_SUCCESS);
	}
	while (!(evt = atomic_read_clear(&tsk->events))) {
		/*
		 * We need to ensure that the execution priority is actually
		 * decreased after the "cpsie i" in the atomic operation above
		 * else the "svc" in the __schedule call below will trigger
		 * a HardFault. Use a barrier to force it at that point.
		 */
		asm volatile("isb");
		/* Remove ourself and get the next task in the scheduler */
		__schedule(1, resched);
		resched = TASK_ID_IDLE;
	}
	if (timeout_us > 0)
		timer_cancel(me);
	return evt;
}

uint32_t task_set_event(task_id_t tskid, uint32_t event, int wait)
{
	task_ *receiver = __task_id_to_ptr(tskid);
	ASSERT(receiver);

	/* Set the event bit in the receiver message bitmap */
	atomic_or(&receiver->events, event);

	/* Re-schedule if priorities have changed */
	if (in_interrupt_context()) {
		/* The receiver might run again */
		atomic_or(&tasks_ready, 1 << tskid);
#ifndef CONFIG_TASK_PROFILING
		if (start_called)
			need_resched_or_profiling = 1;
#endif
	} else {
		if (wait) {
			return __wait_evt(-1, tskid);
		} else {
			/*
			 * We need to ensure that the execution priority is
			 * actually decreased after the "cpsie i" in the atomic
			 * operation above else the "svc" in the __schedule
			 * call below will trigger a HardFault.
			 * Use a barrier to force it at that point.
			 */
			asm volatile("isb");
			__schedule(0, tskid);
		}
	}

	return 0;
}

uint32_t task_wait_event(int timeout_us)
{
	return __wait_evt(timeout_us, TASK_ID_IDLE);
}

void task_enable_irq(int irq)
{
	CPU_NVIC_EN(0) = 1 << irq;
}

void task_disable_irq(int irq)
{
	CPU_NVIC_DIS(0) = 1 << irq;
}

void task_clear_pending_irq(int irq)
{
	CPU_NVIC_UNPEND(0) = 1 << irq;
}

void task_trigger_irq(int irq)
{
	CPU_NVIC_ISPR(0) = 1 << irq;
}

/*
 * Initialize IRQs in the NVIC and set their priorities as defined by the
 * DECLARE_IRQ statements.
 */
static void __nvic_init_irqs(void)
{
	/* Get the IRQ priorities section from the linker */
	int exc_calls = __irqprio_end - __irqprio;
	int i;

	/* Mask and clear all pending interrupts */
	CPU_NVIC_DIS(0) = 0xffffffff;
	CPU_NVIC_UNPEND(0) = 0xffffffff;

	/*
	 * Re-enable global interrupts in case they're disabled.  On a reboot,
	 * they're already enabled; if we've jumped here from another image,
	 * they're not.
	 */
	interrupt_enable();

	/* Set priorities */
	for (i = 0; i < exc_calls; i++) {
		uint8_t irq = __irqprio[i].irq;
		uint8_t prio = __irqprio[i].priority;
		uint32_t prio_shift = irq % 4 * 8 + 6;
		CPU_NVIC_PRI(irq / 4) =
				(CPU_NVIC_PRI(irq / 4) &
				 ~(0x7 << prio_shift)) |
				(prio << prio_shift);
	}
}

void mutex_lock(struct mutex *mtx)
{
	uint32_t id = 1 << task_get_current();

	ASSERT(id != TASK_ID_INVALID);
	atomic_or(&mtx->waiters, id);

	while (1) {
		/* Try to get the lock (set 2 into the lock field) */
		__asm__ __volatile__("cpsid i");
		if (mtx->lock == 0)
			break;
		__asm__ __volatile__("cpsie i");
		/* TODO(crbug.com/435612, crbug.com/435611)
		 * This discards any pending events! */
		task_wait_event(0);  /* Contention on the mutex */
	}
	mtx->lock = 2;
	__asm__ __volatile__("cpsie i");

	atomic_clear(&mtx->waiters, id);
}

void mutex_unlock(struct mutex *mtx)
{
	uint32_t waiters;
	task_ *tsk = current_task;

	__asm__ __volatile__("   ldr     %0, [%2]\n"
			     "   str     %3, [%1]\n"
			     : "=&r" (waiters)
			     : "r" (&mtx->lock), "r" (&mtx->waiters), "r" (0)
			     : "cc");
	while (waiters) {
		task_id_t id = 31 - __builtin_clz(waiters);

		/* Somebody is waiting on the mutex */
		task_set_event(id, TASK_EVENT_MUTEX, 0);
		waiters &= ~(1 << id);
	}

	/* Ensure no event is remaining from mutex wake-up */
	atomic_clear(&tsk->events, TASK_EVENT_MUTEX);
}

void task_print_list(void)
{
	int i;

	ccputs("Task Ready Name         Events      Time (s)  StkUsed\n");

	for (i = 0; i < TASK_ID_COUNT; i++) {
		char is_ready = (tasks_ready & (1<<i)) ? 'R' : ' ';
		uint32_t *sp;

		int stackused = tasks_init[i].stack_size;

		for (sp = tasks[i].stack;
		     sp < (uint32_t *)tasks[i].sp && *sp == STACK_UNUSED_VALUE;
		     sp++)
			stackused -= sizeof(uint32_t);

		ccprintf("%4d %c %-16s %08x %11.6ld  %3d/%3d\n", i, is_ready,
			 task_names[i], tasks[i].events, tasks[i].runtime,
			 stackused, tasks_init[i].stack_size);
		cflush();
	}
}

int command_task_info(int argc, char **argv)
{
#ifdef CONFIG_TASK_PROFILING
	int total = 0;
	int i;
#endif

	task_print_list();

#ifdef CONFIG_TASK_PROFILING
	ccputs("IRQ counts by type:\n");
	cflush();
	for (i = 0; i < ARRAY_SIZE(irq_dist); i++) {
		if (irq_dist[i]) {
			ccprintf("%4d %8d\n", i, irq_dist[i]);
			total += irq_dist[i];
		}
	}
	ccprintf("Service calls:          %11d\n", svc_calls);
	ccprintf("Total exceptions:       %11d\n", total + svc_calls);
	ccprintf("Task switches:          %11d\n", task_switches);
	ccprintf("Task switching started: %11.6ld s\n", task_start_time);
	ccprintf("Time in tasks:          %11.6ld s\n",
		 get_time().val - task_start_time);
	ccprintf("Time in exceptions:     %11.6ld s\n", exc_total_time);
#endif

	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(taskinfo, command_task_info,
			NULL,
			"Print task info",
			NULL);

#ifdef CONFIG_CMD_TASKREADY
static int command_task_ready(int argc, char **argv)
{
	if (argc < 2) {
		ccprintf("tasks_ready: 0x%08x\n", tasks_ready);
	} else {
		tasks_ready = strtoi(argv[1], NULL, 16);
		ccprintf("Setting tasks_ready to 0x%08x\n", tasks_ready);
		__schedule(0, 0);
	}

	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(taskready, command_task_ready,
			"[setmask]",
			"Print/set ready tasks",
			NULL);
#endif

#ifdef CONFIG_CMD_STACKOVERFLOW
static void stack_overflow_recurse(int n)
{
	ccprintf("+%d", n);

	/*
	 * Force task context switch, since that's where we do stack overflow
	 * checking.
	 */
	msleep(10);

	stack_overflow_recurse(n+1);

	/*
	 * Do work after the recursion, or else the compiler uses tail-chaining
	 * and we don't actually consume additional stack.
	 */
	ccprintf("-%d", n);
}

static int command_stackoverflow(int argc, char **argv)
{
	ccprintf("Recursing 0,");
	stack_overflow_recurse(1);
	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(stackoverflow, command_stackoverflow,
			NULL,
			"Recurse until stack overflow",
			NULL);
#endif /* CONFIG_CMD_STACKOVERFLOW */

void task_pre_init(void)
{
	uint32_t *stack_next = (uint32_t *)task_stacks;
	int i;

	/* Fill the task memory with initial values */
	for (i = 0; i < TASK_ID_COUNT; i++) {
		uint32_t *sp;
		/* Stack size in words */
		uint32_t ssize = tasks_init[i].stack_size / 4;

		tasks[i].stack = stack_next;

		/*
		 * Update stack used by first frame: 8 words for the normal
		 * stack, plus 8 for R4-R11. With FP enabled, we need another
		 * 18 words for S0-S15 and FPCSR and to align to 64-bit.
		 */
		sp = stack_next + ssize - 16;
		tasks[i].sp = (uint32_t)sp;

		/* Initial context on stack (see __switchto()) */
		sp[8] = tasks_init[i].r0;           /* r0 */
		sp[13] = (uint32_t)task_exit_trap;  /* lr */
		sp[14] = tasks_init[i].pc;          /* pc */
		sp[15] = 0x01000000;                /* psr */

		/* Fill unused stack; also used to detect stack overflow. */
		for (sp = stack_next; sp < (uint32_t *)tasks[i].sp; sp++)
			*sp = STACK_UNUSED_VALUE;

		stack_next += ssize;
	}

	/*
	 * Fill in guard value in scratchpad to prevent stack overflow
	 * detection failure on the first context switch.  This works because
	 * the first word in the scratchpad is where the switcher will store
	 * sp, so it's ok to blow away.
	 */
	((task_ *)scratchpad)->stack = (uint32_t *)scratchpad;
	*(uint32_t *)scratchpad = STACK_UNUSED_VALUE;

	/* Initialize IRQs */
	__nvic_init_irqs();
}

int task_start(void)
{
#ifdef CONFIG_TASK_PROFILING
	task_start_time = exc_end_time = get_time().val;
#endif
	start_called = 1;

	return __task_start(&need_resched_or_profiling);
}


text:
import classnames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { getDataAttributes } from '../_helpers';

export default function ToggleItem(props) {
  const {
    active,
    children,
    className,
    dataAttrs,
    handleClick,
  } = props;

  const classes = classnames(
    className,
    'ui-toggle-button__item',
    {
      'ui-toggle-button__item_active': active,
    }
  );

  return (
    <li className={classes} onClick={handleClick} {...getDataAttributes(dataAttrs)}>
      {children}
    </li>
  );
}

ToggleItem.defaultProps = {
  active: false,
  handleClick: () => null,
};

ToggleItem.propTypes = {
  /**
   * Is item active.
   */
  active: PropTypes.bool,

  /**
   * Content that will be wrapped by ToggleItem
   */
  children: PropTypes.node,

  /**
   * Custom className(s) to be concatenated with the default ones
   * on the component's root element
   */
  className: PropTypes.string,

  /**
   * Data attribute. You can use it to set up GTM key or any custom data-* attribute.
   */
  dataAttrs: PropTypes.object,

  /**
   * Specify a function that will be called when a user clicked on a given option.
   */
  handleClick: PropTypes.func.isRequired,
};


text:
/**
 * WSObject.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package rallyws.api;

public class WSObject  implements java.io.Serializable {
    private java.lang.String ref;  // attribute

    private long objectVersion;  // attribute

    private java.lang.String type;  // attribute

    private java.lang.String refObjectName;  // attribute

    private long rallyAPIMajor;  // attribute

    private long rallyAPIMinor;  // attribute

    public WSObject() {
    }

    public WSObject(
           java.lang.String ref,
           long objectVersion,
           java.lang.String type,
           java.lang.String refObjectName,
           long rallyAPIMajor,
           long rallyAPIMinor) {
           this.ref = ref;
           this.objectVersion = objectVersion;
           this.type = type;
           this.refObjectName = refObjectName;
           this.rallyAPIMajor = rallyAPIMajor;
           this.rallyAPIMinor = rallyAPIMinor;
    }

    /**
     * Gets the ref value for this WSObject.
     *
     * @return ref
     */
    public java.lang.String getRef() {
        return ref;
    }

    /**
     * Sets the ref value for this WSObject.
     *
     * @param ref
     */
    public void setRef(java.lang.String ref) {
        this.ref = ref;
    }

    /**
     * Gets the objectVersion value for this WSObject.
     *
     * @return objectVersion
     */
    public long getObjectVersion() {
        return objectVersion;
    }

    /**
     * Sets the objectVersion value for this WSObject.
     *
     * @param objectVersion
     */
    public void setObjectVersion(long objectVersion) {
        this.objectVersion = objectVersion;
    }

    /**
     * Gets the type value for this WSObject.
     *
     * @return type
     */
    public java.lang.String getType() {
        return type;
    }

    /**
     * Sets the type value for this WSObject.
     *
     * @param type
     */
    public void setType(java.lang.String type) {
        this.type = type;
    }

    /**
     * Gets the refObjectName value for this WSObject.
     *
     * @return refObjectName
     */
    public java.lang.String getRefObjectName() {
        return refObjectName;
    }

    /**
     * Sets the refObjectName value for this WSObject.
     *
     * @param refObjectName
     */
    public void setRefObjectName(java.lang.String refObjectName) {
        this.refObjectName = refObjectName;
    }

    /**
     * Gets the rallyAPIMajor value for this WSObject.
     *
     * @return rallyAPIMajor
     */
    public long getRallyAPIMajor() {
        return rallyAPIMajor;
    }

    /**
     * Sets the rallyAPIMajor value for this WSObject.
     *
     * @param rallyAPIMajor
     */
    public void setRallyAPIMajor(long rallyAPIMajor) {
        this.rallyAPIMajor = rallyAPIMajor;
    }

    /**
     * Gets the rallyAPIMinor value for this WSObject.
     *
     * @return rallyAPIMinor
     */
    public long getRallyAPIMinor() {
        return rallyAPIMinor;
    }

    /**
     * Sets the rallyAPIMinor value for this WSObject.
     *
     * @param rallyAPIMinor
     */
    public void setRallyAPIMinor(long rallyAPIMinor) {
        this.rallyAPIMinor = rallyAPIMinor;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof WSObject)) return false;
        WSObject other = (WSObject) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.ref==null && other.getRef()==null) ||
             (this.ref!=null &&
              this.ref.equals(other.getRef()))) &&
            this.objectVersion == other.getObjectVersion() &&
            ((this.type==null && other.getType()==null) ||
             (this.type!=null &&
              this.type.equals(other.getType()))) &&
            ((this.refObjectName==null && other.getRefObjectName()==null) ||
             (this.refObjectName!=null &&
              this.refObjectName.equals(other.getRefObjectName()))) &&
            this.rallyAPIMajor == other.getRallyAPIMajor() &&
            this.rallyAPIMinor == other.getRallyAPIMinor();
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getRef() != null) {
            _hashCode += getRef().hashCode();
        }
        _hashCode += new Long(getObjectVersion()).hashCode();
        if (getType() != null) {
            _hashCode += getType().hashCode();
        }
        if (getRefObjectName() != null) {
            _hashCode += getRefObjectName().hashCode();
        }
        _hashCode += new Long(getRallyAPIMajor()).hashCode();
        _hashCode += new Long(getRallyAPIMinor()).hashCode();
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(WSObject.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://rallydev.com/webservice/v1_09/domain", "WSObject"));
        org.apache.axis.description.AttributeDesc attrField = new org.apache.axis.description.AttributeDesc();
        attrField.setFieldName("ref");
        attrField.setXmlName(new javax.xml.namespace.QName("", "ref"));
        attrField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        typeDesc.addFieldDesc(attrField);
        attrField = new org.apache.axis.description.AttributeDesc();
        attrField.setFieldName("objectVersion");
        attrField.setXmlName(new javax.xml.namespace.QName("", "objectVersion"));
        attrField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        typeDesc.addFieldDesc(attrField);
        attrField = new org.apache.axis.description.AttributeDesc();
        attrField.setFieldName("type");
        attrField.setXmlName(new javax.xml.namespace.QName("", "type"));
        attrField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        typeDesc.addFieldDesc(attrField);
        attrField = new org.apache.axis.description.AttributeDesc();
        attrField.setFieldName("refObjectName");
        attrField.setXmlName(new javax.xml.namespace.QName("", "refObjectName"));
        attrField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        typeDesc.addFieldDesc(attrField);
        attrField = new org.apache.axis.description.AttributeDesc();
        attrField.setFieldName("rallyAPIMajor");
        attrField.setXmlName(new javax.xml.namespace.QName("", "rallyAPIMajor"));
        attrField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        typeDesc.addFieldDesc(attrField);
        attrField = new org.apache.axis.description.AttributeDesc();
        attrField.setFieldName("rallyAPIMinor");
        attrField.setXmlName(new javax.xml.namespace.QName("", "rallyAPIMinor"));
        attrField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        typeDesc.addFieldDesc(attrField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
from setuptools import setup, find_packages

setup(
    name='PyspotifyCtypesProxy',
    version='0.4',
    description='An embedded proxy server intended for players that cannot integrate libspotify easily.',
    author='Mikel Azkolain',
    author_email='azkotoki@gmail.com',
    url='http://forge.azkotoki.org/pyspotify-ctypes',
    package_dir = {'': 'src'},
    packages=find_packages('src'),
    include_package_data=True,
)


text:
import json
import logging
import requests

from indra import get_config
from indra.sources.indra_db_rest.exceptions import IndraDBRestAPIError

logger = logging.getLogger(__name__)

def submit_query_request(end_point, *args, **kwargs):
    """Low level function to format the query string."""
    ev_limit = kwargs.pop('ev_limit', 10)
    best_first = kwargs.pop('best_first', True)
    tries = kwargs.pop('tries', 2)
    # This isn't handled by requests because of the multiple identical agent
    # keys, e.g. {'agent': 'MEK', 'agent': 'ERK'} which is not supported in
    # python, but is allowed and necessary in these query strings.
    # TODO because we use the API Gateway, this feature is not longer needed.
    # We should just use the requests parameters dict.
    query_str = '?' + '&'.join(['%s=%s' % (k, v) for k, v in kwargs.items()
                                if v is not None]
                               + list(args))
    return submit_statement_request('get', end_point, query_str,
                                    ev_limit=ev_limit, best_first=best_first,
                                    tries=tries)

def submit_statement_request(meth, end_point, query_str='', data=None,
                             tries=2, **params):
    """Even lower level function to make the request."""
    full_end_point = 'statements/' + end_point.lstrip('/')
    return make_db_rest_request(meth, full_end_point, query_str, data, params, tries)

def make_db_rest_request(meth, end_point, query_str, data=None, params=None, tries=2):
    if params is None:
        params = {}

    if end_point is None:
        logger.error("Exception in submit request with args: %s"
                     % str([meth, end_point, query_str, data, params, tries]))
        raise ValueError("end_point cannot be None.")
    url_path = get_url_base(end_point)
    api_key = get_config('INDRA_DB_REST_API_KEY', failure_ok=True)
    url_path += query_str
    headers = {}
    if data:
        # This is an assumption which applies to our use cases for now, but may
        # not generalize.
        headers['content-type'] = 'application/json'
        json_data = json.dumps(data)
    else:
        json_data = None
    params['api_key'] = api_key
    logger.info('url and query string: %s',
                url_path.replace(str(api_key), '[api-key]'))
    logger.info('headers: %s', str(headers).replace(str(api_key), '[api-key]'))
    logger.info('data: %s', str(data).replace(str(api_key), '[api-key]'))
    logger.info('params: %s', str(params).replace(str(api_key), '[api-key]'))
    method_func = getattr(requests, meth.lower())
    while tries > 0:
        tries -= 1
        resp = method_func(url_path, headers=headers, data=json_data,
                           params=params)
        if resp.status_code == 200:
            return resp
        elif resp.status_code == 504 and tries > 0:
            logger.warning("Endpoint timed out. Trying again...")
        else:
            raise IndraDBRestAPIError(resp)

def get_url_base(end_point):
    url = get_config('INDRA_DB_REST_URL', failure_ok=False)
    url_path = url.rstrip('/') + '/' + end_point.lstrip('/')
    return url_path


text:
package unit.com.bitdubai.fermat_osa_addon.layer.android.database_system.developer.bitdubai.version_1.structure.AndroidDatabase;

import android.app.Activity;
import android.content.Context;
import android.support.v13.BuildConfig;

import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_osa_addon.layer.android.database_system.developer.bitdubai.version_1.structure.AndroidDatabase;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import java.util.UUID;

import static com.googlecode.catchexception.CatchException.catchException;
import static com.googlecode.catchexception.CatchException.caughtException;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.robolectric.Shadows.shadowOf;
import unit.com.bitdubai.fermat_osa_addon.layer.android.database_system.developer.bitdubai.version_1.CustomBuildConfig;

/**
 * Created by jorgegonzalez on 2015.06.27..
 */
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = CustomBuildConfig.class)
public class CreateDatabaseTest {

    private Activity mockActivity;
    private Context mockContext;

    private AndroidDatabase testDatabase;
    private String testDatabaseName = "testDatabase";

    @Before
    public void CreateDatabase_TheDatabaseHasNotBeenCreated_MethodInvokedSuccessfully() throws Exception{
        mockActivity = Robolectric.setupActivity(Activity.class);
        mockContext = shadowOf(mockActivity).getApplicationContext();

        testDatabase = new AndroidDatabase(mockContext, UUID.randomUUID(), testDatabaseName);
        catchException(testDatabase).createDatabase(testDatabaseName);
        assertThat(caughtException()).isNull();
    }

    @Test
    public void CreateDatabase_TheDatabaseHasAlreadyBeenCreated_ThrowsCantCreateDatabaseException() throws Exception{
        mockActivity = Robolectric.setupActivity(Activity.class);
        mockContext = shadowOf(mockActivity).getApplicationContext();

        testDatabase = new AndroidDatabase(mockContext, UUID.randomUUID(), testDatabaseName);
        testDatabase.createDatabase(testDatabaseName);
        catchException(testDatabase).createDatabase(testDatabaseName);
        assertThat(caughtException()).isInstanceOf(CantCreateDatabaseException.class);

    }
}


text:
namespace Microsoft.Azure.Management.LabServices
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// OperationResultsOperations operations.
    /// </summary>
    internal partial class OperationResultsOperations : IServiceOperations<LabServicesClient>, IOperationResultsOperations
    {
        /// <summary>
        /// Initializes a new instance of the OperationResultsOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        internal OperationResultsOperations(LabServicesClient client)
        {
            if (client == null)
            {
                throw new System.ArgumentNullException("client");
            }
            Client = client;
        }

        /// <summary>
        /// Gets a reference to the LabServicesClient
        /// </summary>
        public LabServicesClient Client { get; private set; }

        /// <summary>
        /// Get an azure operation result.
        /// </summary>
        /// <remarks>
        /// Returns an azure operation result.
        /// </remarks>
        /// <param name='operationResultId'>
        /// The operation result ID / name.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<OperationResult>> GetWithHttpMessagesAsync(string operationResultId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (Client.ApiVersion != null)
            {
                if (Client.ApiVersion.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1);
                }
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (Client.SubscriptionId != null)
            {
                if (Client.SubscriptionId.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1);
                }
            }
            if (operationResultId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "operationResultId");
            }
            if (operationResultId != null)
            {
                if (operationResultId.Length > 100)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "operationResultId", 100);
                }
                if (operationResultId.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "operationResultId", 1);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(operationResultId, "^[-\\w\\\\._\\\\(\\\\)]+$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "operationResultId", "^[-\\w\\\\._\\\\(\\\\)]+$");
                }
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("operationResultId", operationResultId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.LabServices/operationResults/{operationResultId}").ToString();
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{operationResultId}", System.Uri.EscapeDataString(operationResultId));
            List<string> _queryParameters = new List<string>();
            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }

            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200 && (int)_statusCode != 204)
            {
                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    ErrorResponse _errorBody =  Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<OperationResult>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationResult>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

    }
}