text:
from django.core.management import call_command
from django.test import TransactionTestCase
from django.core.exceptions import ValidationError
from .. import models

import logging
logging.disable(logging.ERROR)

class CredentialTests(TransactionTestCase):
    def setUp(self):
        call_command('registerplugins')
        self.http = models.Plugin.objects.get(name='http')
        self.smb = models.Plugin.objects.get(name='smb')
        self.service1 = models.Service.objects.create(
            name='Service1', subnet_host=1, port=80, plugin=self.http)
        self.service2 = models.Service.objects.create(
            name='Service2', subnet_host=2, port=38, plugin=self.smb)
        self.team1 = models.Team.objects.create(
            name='Team1', subnet='192.168.1.0', netmask='255.255.255.0')
        self.team2 = models.Team.objects.create(
            name='Team2', subnet='192.168.2.0', netmask='255.255.255.0')

    def test_malformed_credential(self):
        """Should not be able to create credentials with malformed data"""
        # Too little data
        with self.assertRaises(ValidationError):
            models.Credential.objects.create()
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(team=None)
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(default=None)
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(username='tom')
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(password='test')
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(team=None, default=None)
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(team=None, username='tom')
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(team=None, password='toor')
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(default=None, username='john')
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(default=None, password='john')
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(
                team=None, default=None, username='john')
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(
                team=None, default=None, password='john')

        # Malformed arguments
        ## Team
        with self.assertRaises(ValueError): # Team is not a model or None
            models.Credential.objects.create(
                team='Team1', default=None, username='tom', password='john')
        ## Default
        with self.assertRaises(ValueError): # Default is not a Credential
            models.Credential.objects.create(
                team=None, default=5, username='tom', password='john')
        # Username
        with self.assertRaises(ValidationError): # Username is None
            models.Credential.objects.create(
                team=None, default=None, username=None, password='john')
        with self.assertRaises(ValidationError): # Username is empty string
            models.Credential.objects.create(
                team=None, default=None, username='', password='john')
        with self.assertRaises(ValidationError): # Username is too long
            models.Credential.objects.create(
                team=None, default=None, username='a'*21, password='john')
        # Password
        with self.assertRaises(ValidationError): # Password is None
            models.Credential.objects.create(
                team=None, default=None, username='tom', password=None)
        with self.assertRaises(ValidationError): # Password is empty string
            models.Credential.objects.create(
                team=None, default=None, username='tom', password='')
        with self.assertRaises(ValidationError): # Password is too long
            models.Credential.objects.create(
                team=None, default=None, username='tom', password='b'*41)

    def test_credentials_same_team_username_service(self):
        """Credentials with the same team and username, and an overlapping
           set of services are not allowed"""
        models.Credential.objects.create(
            team=self.team1, default=None, username='what', password='krit',
            services=[self.service1])
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(
                team=self.team1, default=None, username='what', password='lbah',
                services=[self.service1])

        models.Credential.objects.create(
            team=None, default=None, username='kruft', password='krit',
            services=[self.service1, self.service2])
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(
                team=None, default=None, username='kruft', password='lbah',
                services=[self.service1])
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(
                team=None, default=None, username='kruft', password='lbah',
                services=[self.service2])
        with self.assertRaises(ValidationError):
            models.Credential.objects.create(
                team=None, default=None, username='kruft', password='lbah',
                services=[self.service1, self.service2])

    def test_credentials_correct(self):
        """Credentials with the correct arguments are allowed"""
        self.assertEqual(models.Credential.objects.count(), 0)
        models.Credential.objects.create(
            team=self.team1, default=None, username='what', password='krit')
        self.assertEqual(models.Credential.objects.count(), 1)
        models.Credential.objects.create(
            team=self.team2, default=None, username='kdls', password='kdl')
        self.assertEqual(models.Credential.objects.count(), 2)
        models.Credential.objects.create(
            team=None, default=None, username='test', password='toor')
        self.assertEqual(models.Credential.objects.count(), 5)
        # With services
        models.Credential.objects.create(
            team=self.team1, default=None, username='lol', password='what',
            services=[self.service1])
        self.assertEqual(models.Credential.objects.count(), 6)
        models.Credential.objects.create(
            team=None, default=None, username='john', password='lkf',
            services=[self.service1, self.service2])
        self.assertEqual(models.Credential.objects.count(), 9)

    def test_credential_services(self):
        """Credential services should be properly assigned when created"""
        c = models.Credential.objects.create(
            team=self.team1, default=None, username='lol', password='what',
            services=[self.service1])
        self.assertEqual(models.Credential.objects.count(), 1)
        self.assertEqual(set(c.services.all()), set([self.service1]))

        c = models.Credential.objects.create(
            team=None, default=None, username='john', password='lkf',
            services=[self.service1, self.service2])
        self.assertEqual(models.Credential.objects.count(), 4)
        self.assertEqual(set(c.services.all()),
                         set([self.service1, self.service2]))
        self.assertEqual(c.assoc_creds.count(), 2)
        for cred in c.assoc_creds.all():
            self.assertEqual(set(cred.services.all()),
                             set([self.service1, self.service2]))

    def test_default_credentials_populate_teams(self):
        """When a default credential is added, copies are populated to
           all teams"""
        self.assertEqual(models.Credential.objects.count(), 0)
        c = models.Credential.objects.create(
            team=None, default=None, username='test', password='toor')
        self.assertEqual(models.Credential.objects.count(), 3)
        self.assertEqual(c.assoc_creds.count(), 2)
        for cred in c.assoc_creds.all():
            self.assertEqual(cred.default, c)

    def test_default_credential_delete_cascade(self):
        """When a default credential is deleted, its associated
           credentials are also deleted"""
        cred = models.Credential.objects.create(
            team=None, default=None, username='test', password='toor')
        self.assertEqual(models.Credential.objects.count(), 3)
        cred.delete()
        self.assertEqual(models.Credential.objects.count(), 0)

    def test_team_delete_cascade(self):
        """When a team is deleted, its associated
           credentials are also deleted"""
        models.Credential.objects.create(
            team=self.team1, default=None, username='test', password='toor')
        models.Credential.objects.create(
            team=self.team1, default=None, username='what', password='toor')
        self.assertEqual(models.Credential.objects.count(), 2)
        self.team1.delete()
        self.assertEqual(models.Credential.objects.count(), 0)

    def test_credential_malformed_edit(self):
        """Credentials should raise errors when edited with malformed data"""
        c = models.Credential.objects.create(
            team=self.team1, default=None, username='what', password='ever',
            services=[self.service1])

        ## Team
        with self.assertRaises(ValueError): # Team is not a model or None
            c.team = 'Team1'
            c.save()
        ## Default
        with self.assertRaises(ValueError): # Default is not a Credential
            c.default = 5
            c.save()
        # Username
        with self.assertRaises(ValidationError): # Username is None
            c.username = None
            c.save()
        with self.assertRaises(ValidationError): # Username is empty string
            c.username = ''
            c.save()
        with self.assertRaises(ValidationError): # Username is too long
            c.username = 'a'*21
            c.save()
        # Password
        with self.assertRaises(ValidationError): # Password is None
            c.password = None
            c.save()
        with self.assertRaises(ValidationError): # Password is empty string
            c.password = ''
            c.save()
        with self.assertRaises(ValidationError): # Password is too long
            c.password = 'b'*41
            c.save()

    def test_credentials_edit_same_team_username_service(self):
        """Credentials with the same team and username, and an overlapping
           set of services are not allowed when editing"""
        models.Credential.objects.create(
            team=self.team1, default=None, username='what', password='krit',
            services=[self.service1])
        c = models.Credential.objects.create(
            team=self.team1, default=None, username='what', password='lbah',
            services=[self.service2])
        with self.assertRaises(ValidationError):
            c.services=[self.service1]
            c.save()

        c.username = 'huh'
        c.services = [self.service1]
        c.save()

        with self.assertRaises(ValidationError):
            c.username='what'
            c.save()

        models.Credential.objects.create(
            team=None, default=None, username='kruft', password='krit',
            services=[self.service1, self.service2])
        c = models.Credential.objects.create(
            team=None, default=None, username='kruft', password='lbah',
            services=[])
        with self.assertRaises(ValidationError):
            c.services = [self.service1]
            c.save()
        with self.assertRaises(ValidationError):
            c.services = [self.service2]
            c.save()
        with self.assertRaises(ValidationError):
            c.services = [self.service1, self.service2]
            c.save()

    def test_credential_edit(self):
        """Credentials should be properly updated when edited"""
        c = models.Credential.objects.create(
            team=self.team1, default=None, username='what', password='ever',
            services=[self.service1])
        c.team = self.team2
        c.save()
        c = models.Credential.objects.get(pk=c.pk) # Reload from DB
        self.assertEqual(c.team, self.team2)

        c.username='blah'
        c.save()
        c = models.Credential.objects.get(pk=c.pk) # Reload from DB
        self.assertEqual(c.username, 'blah')

        c.password='blop'
        c.save()
        c = models.Credential.objects.get(pk=c.pk) # Reload from DB
        self.assertEqual(c.password, 'blop')

        c.services=[self.service1, self.service2]
        c.save()
        c = models.Credential.objects.get(pk=c.pk) # Reload from DB
        self.assertEqual(set(c.services.all()),
                         set([self.service1, self.service2]))

        c.services=[]
        c.save()
        c = models.Credential.objects.get(pk=c.pk) # Reload from DB
        self.assertEqual(set(c.services.all()), set())

        def_cred = models.Credential.objects.create(
            team=None, default=None, username='blah', password='blop',
            services=[])
        c.default=def_cred
        c.save()
        c = models.Credential.objects.get(pk=c.pk) # Reload from DB
        self.assertEqual(c.default, def_cred)
        self.assertIn(c, def_cred.assoc_creds.all())

    def test_default_cred_edit_propagation(self):
        """When default credentials are edited, its associated credentials
           should also be updated"""
        def_cred = models.Credential.objects.create(
            team=None, default=None, username='test', password='toor',
            services=[self.service1])

        def_cred.username = 'what'
        def_cred.save()
        for c in def_cred.assoc_creds.all():
            self.assertEqual(c.username, 'what')

        def_cred.password = 'blah'
        def_cred.save()
        for c in def_cred.assoc_creds.all():
            self.assertEqual(c.password, 'blah')

        def_cred.services = [self.service1, self.service2]
        def_cred.save()
        for c in def_cred.assoc_creds.all():
            self.assertEqual(set(c.services.all()),
                             set([self.service1, self.service2]))

        def_cred.services = []
        def_cred.save()
        for c in def_cred.assoc_creds.all():
            self.assertEqual(set(c.services.all()), set())

    def test_edit_cred_remove_default(self):
        """When a credential associated with a default credential is edited,
           its default field is set to NULL"""
        models.Team.objects.create(
            name='Team3', subnet='192.168.3.0', netmask='255.255.255.0')

        def_cred = models.Credential.objects.create(
            team=None, default=None, username='test', password='toor',
            services=[self.service1])
        self.assertEqual(def_cred.assoc_creds.count(), 3)

        assoc = list(def_cred.assoc_creds.all())
        assoc[0].username = 'what'
        assoc[0].save()
        self.assertEqual(def_cred.username, 'test')
        self.assertEqual(assoc[0].username, 'what')
        self.assertIs(assoc[0].default, None)
        self.assertEqual(def_cred.assoc_creds.count(), 2)

        assoc[1].password = 'ever'
        assoc[1].save()
        self.assertEqual(def_cred.password, 'toor')
        self.assertEqual(assoc[1].password, 'ever')
        self.assertIs(assoc[1].default, None)
        self.assertEqual(def_cred.assoc_creds.count(), 1)

        assoc[2].services = [self.service1, self.service2]
        assoc[2].save()
        self.assertEqual(set(def_cred.services.all()), set([self.service1]))
        self.assertEqual(set(assoc[2].services.all()),
                         set([self.service1, self.service2]))
        self.assertIs(assoc[2].default, None)
        self.assertEqual(def_cred.assoc_creds.count(), 0)


text:
Mail collector and server with security in mind

## Modules
* api
* connector (mail)
* config (stores config)
* controller (core)
* UI (CLI, GUI, WUI)
*

redpajama_set_name: RedPajamaGithub


text:
package org.motechproject.mobileforms.api.service;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.motechproject.mobileforms.api.domain.Form;
import org.motechproject.mobileforms.api.domain.FormGroup;
import org.motechproject.mobileforms.api.repository.AllMobileForms;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static junit.framework.Assert.assertEquals;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

public class MobileFormsServiceImplTest {

    private MobileFormsService mobileFormsService;

    @Mock
    private AllMobileForms allMobileForms;

    @Before
    public void setUp() {
        initMocks(this);
        mobileFormsService = new MobileFormsServiceImpl(allMobileForms);
    }

    @Test
    public void shouldFetchTheListOfFromGroupsAvailable() {

        String groupOneName = "Group-1";
        String groupTwoName = "Group-2";
        when(allMobileForms.getAllFormGroups()).thenReturn(Arrays.asList(new FormGroup(groupOneName, Arrays.asList(new Form("Form-1", "Form-1.xml"))),
                new FormGroup(groupTwoName, Arrays.asList(new Form("From-2", "Form-2.xml")))));

        List<Object[]> returnedFormGroups = mobileFormsService.getAllFormGroups();

        assertThat(returnedFormGroups.size(), is(equalTo(2)));

        assertThat((Integer) returnedFormGroups.get(0)[0], is(equalTo(0)));
        assertThat((String) returnedFormGroups.get(0)[1], is(equalTo(groupOneName)));

        assertThat((Integer) returnedFormGroups.get(1)[0], is(equalTo(1)));
        assertThat((String) returnedFormGroups.get(1)[1], is(equalTo(groupTwoName)));
    }

    @Test
    public void shouldReturnContextOfFormsThatBelongsToTheGroupGivenTheIndexOfTheGroup() {
        String formOneContent = "Form-1-content";
        String formTwoContent = "Form-2-content";
        String formThreeContent = "Form-3-content";
        String formGroupOneName = "FormGroup-1";
        String formGroupTwoName = "FormGroup-2";

        final FormGroup formGroupOne = new FormGroup(formGroupOneName, Arrays.asList(new Form("From-1", "Form-1.xml", formOneContent, null, null, null, Collections.<String>emptyList()), new Form("Form-2", "Form-2.xml", formTwoContent, null, null, null, Collections.<String>emptyList())));
        final FormGroup formGroupTwo = new FormGroup(formGroupTwoName, Arrays.asList(new Form("From-3", "Form-3.xml", formThreeContent, null, null, null, Collections.<String>emptyList())));
        when(allMobileForms.getFormGroup(0)).thenReturn(formGroupOne);
        when(allMobileForms.getFormGroup(1)).thenReturn(formGroupTwo);

        assertThat(mobileFormsService.getForms(0), is(equalTo(formGroupOne)));
        assertThat(mobileFormsService.getForms(1), is(equalTo(formGroupTwo)));

    }

    @Test
    public void shouldReturnFormDefinitionMap() {
        Form form1 = makeTestForm(1, "f1_content");
        Form form2 = makeTestForm(2, "f2_content");
        Form form3 = makeTestForm(3, "f3_content");
        Form form4 = makeTestForm(4, "f4_content");
        FormGroup group1 = new FormGroup("g1", Arrays.asList(form1, form2));
        FormGroup group2 = new FormGroup("g2", Arrays.asList(form3, form4));
        when(allMobileForms.getAllFormGroups()).thenReturn(Arrays.asList(group1, group2));

        Map<Integer, String> formDefinitionMap = mobileFormsService.getFormIdMap();

        assertEquals("f1_content", formDefinitionMap.get(1));
        assertEquals("f2_content", formDefinitionMap.get(2));
        assertEquals("f3_content", formDefinitionMap.get(3));
        assertEquals("f4_content", formDefinitionMap.get(4));
    }

    private Form makeTestForm(Integer formId, String content) {
        Form form = mock(Form.class);
        when(form.id()).thenReturn(formId);
        when(form.content()).thenReturn(content);
        return form;
    }
}


text:
(function (window, HttpClient) {

	'use strict';

	var HttpRequestState = {
		Uninitialized : 0,
		Opened : 1,
		Sent : 2,
		HeadersReceived : 3,
		Loading : 4,
		Done : 5,
		Aborted : 6,
		Errored : 7,
		TimedOut : 8,
	};

	var ProgressEvent = function ProgressEvent(loaded, total, lengthComputable) {
		Object.defineProperties(this, {
			'total' : { value: total },
			'loaded' : { value: loaded },
			'lengthComputable' : { value: lengthComputable }
		});
	};

	var fuseXMLHttpRequest = function fuseXMLHttpRequest() {
		var a = Object.create(fuseXMLHttpRequest.prototype);
		var propertyDescriptors = new Object();

		propertyDescriptors._fuseHttpClient = {
			value: new HttpClient()
		};

		propertyDescriptors._fuseHttpRequest = {
			value: null,
			writable: true
		};

		propertyDescriptors.status = {
			get: function () {
				if(this._fuseHttpRequest === null) return 0;
				return this._fuseHttpRequest.getResponseStatus();
			}
		};

		propertyDescriptors.statusText = {
			get: function () {
				if(this._fuseHttpRequest === null) return "";
				return this._fuseHttpRequest.getResponseReasonPhrase();
			}
		};

		propertyDescriptors.response = {
			get: function () {
				if(this._fuseHttpRequest === null) return "";
				if(this._fuseHttpRequest.getResponseType() == 1)
					return this._fuseHttpRequest.getResponseContentByteArray();
				else
					return this._fuseHttpRequest.getResponseContentString();
			}
		};

		propertyDescriptors.responseText = {
			get: function () {
				if(this._fuseHttpRequest === null) return "";
				return this._fuseHttpRequest.getResponseContentString();
			}
		};

		propertyDescriptors.responseType = {
			get: function () {
				if(this._fuseHttpRequest === null) return "text";
				return this._fuseHttpRequest.getResponseType() == 1 ? 'arraybuffer' : 'text';
			},
			set: function (value) {
				if(this._fuseHttpRequest === null) return;
				this._fuseHttpRequest.setResponseType((value.toLowerCase() == 'arraybuffer') ? 1 : 0);
			}
		};

		propertyDescriptors.readyState = {
			get: function() {
				if(this._fuseHttpRequest === null) return 0;

				var state = this._fuseHttpRequest.getState();
				if(state <= HttpRequestState.Uninitialized) return fuseXMLHttpRequest.UNSENT;
				if(state == HttpRequestState.Opened) return fuseXMLHttpRequest.OPENED;
				if(state == HttpRequestState.HeadersReceived) return fuseXMLHttpRequest.HEADERS_RECEIVED;
				if(state == HttpRequestState.Loading) return fuseXMLHttpRequest.LOADING;
				if(state >= HttpRequestState.Done) return fuseXMLHttpRequest.DONE;
				return fuseXMLHttpRequest.UNSENT;
			}
		};

		Object.defineProperties(a, propertyDescriptors);
		return a;
	};

	fuseXMLHttpRequest.UNSENT = 0;
	fuseXMLHttpRequest.OPENED = 1;
	fuseXMLHttpRequest.HEADERS_RECEIVED = 2;
	fuseXMLHttpRequest.LOADING = 3;
	fuseXMLHttpRequest.DONE = 4;

	fuseXMLHttpRequest.onloadstart = null;
	fuseXMLHttpRequest.onprogress = null;
	fuseXMLHttpRequest.onabort = null;
	fuseXMLHttpRequest.onerror = null;
	fuseXMLHttpRequest.onload = null;
	fuseXMLHttpRequest.ontimeout = null;
	fuseXMLHttpRequest.onloadend = null;

	fuseXMLHttpRequest.prototype.onreadystatechange = null;
	fuseXMLHttpRequest.prototype.timeout = 0;
	fuseXMLHttpRequest.prototype.withCredentials = false;
	fuseXMLHttpRequest.prototype.upload = null;

	fuseXMLHttpRequest.prototype.open = function(method, url, async, username, password) {
		var self = this;
		var progressEvent = new ProgressEvent(0, 0, false);
		var contentLength = 0;

		if(self._fuseHttpRequest !== null)
			self._fuseHttpRequest.abort();

		self._fuseHttpRequest = self._fuseHttpClient.createRequest(method, url);
		self._fuseHttpRequest.enableCache(true);
		self._fuseHttpRequest.setResponseType(0);

		if (self._fuseHttpRequest.getState() === HttpRequestState.Opened) {
			dispatch.call(self, 'readystatechange');
		}

		self._fuseHttpRequest.onstatechanged = function(state) {
			if (state === HttpRequestState.HeadersReceived) {
				dispatch.call(self, 'readystatechange');

				var cl = parseInt(self.getResponseHeader('Content-Length'));
				contentLength = (cl === NaN) ? 0 : cl;
				progressEvent = new ProgressEvent(0, contentLength, contentLength > 0);
				dispatch.call(self, 'loadstart', progressEvent);
			} else if (state === HttpRequestState.Loading || state === HttpRequestState.Done) {
				dispatch.call(self, 'readystatechange');
			}
		};
		self._fuseHttpRequest.ondone = function() {
			dispatch.call(self, 'load');
			dispatch.call(self, 'loadend', progressEvent);
		};
		self._fuseHttpRequest.onabort = function() {
			dispatch.call(self, 'abort');
			dispatch.call(self, 'loadend', progressEvent);
		};
		self._fuseHttpRequest.onerror = function(error) {
			dispatch.call(self, 'error', new Error(error));
			dispatch.call(self, 'loadend', progressEvent);
		};
		self._fuseHttpRequest.onprogress = function(current, total, hastotal) {
			progressEvent = new ProgressEvent(current, total, hastotal);
			dispatch.call(self, 'progress', progressEvent);
		};
		self._fuseHttpRequest.ontimeout = function() {
			dispatch.call(self, 'timeout');
			dispatch.call(self, 'loadend', progressEvent);
		};
	}

	fuseXMLHttpRequest.prototype.send = function(data) {
		if(this._fuseHttpRequest !== null){
			this._fuseHttpRequest.setTimeout(this.timeout);
			this._fuseHttpRequest.sendAsync(data);
		}
		else
			throw "InvalidStateError";
	}

	fuseXMLHttpRequest.prototype.setRequestHeader = function(header, value) {
		if(this._fuseHttpRequest === null) return;
		return this._fuseHttpRequest.setHeader(header, value + "");
	}

	fuseXMLHttpRequest.prototype.abort = function() {
		if(this._fuseHttpRequest === null) return;
		return this._fuseHttpRequest.abort();
	}

	fuseXMLHttpRequest.prototype.getResponseHeader = function(header) {
		if(this._fuseHttpRequest === null) return;
		return this._fuseHttpRequest.getResponseHeader(header);
	}

	fuseXMLHttpRequest.prototype.overrideMimeType = function(mime) {
		// Ignore
	}

	fuseXMLHttpRequest.prototype.getAllResponseHeaders = function() {
		if(this._fuseHttpRequest === null) return;
		return this._fuseHttpRequest.getResponseHeaders();
	}

	if(window.EventTarget != 'undefined') {
		fuseXMLHttpRequest.prototype.addEventListener = window.EventTarget.prototype.addEventListener;
		fuseXMLHttpRequest.prototype.removeEventListener = window.EventTarget.prototype.removeEventListener;
		fuseXMLHttpRequest.prototype.dispatchEvent = window.EventTarget.prototype.dispatchEvent;
	}

	function isAnyObject(value) {
		return value != null && (typeof value === 'object' || typeof value === 'function');
	}

	function dispatch(eventName, arg) {
		if(typeof this.dispatchEvent === 'function') {
			if(typeof arg === 'undefined')
				arg = {};

			if(isAnyObject(arg))
				arg.type = eventName;
			else
				throw new Error("Invalid event object");

			this.dispatchEvent(arg);
		}

		if(typeof this['on' + eventName] === 'function') {
			if(typeof arg === 'undefined')
				this['on' + eventName]();
			else
				this['on' + eventName](arg);
		}
	}

	window.XMLHttpRequest = fuseXMLHttpRequest;

})(window, require('FuseJS/Http'));

XMLHttpRequest = window.XMLHttpRequest;


text:
:sparkling_heart: First things first, thank you for contributing. :sparkling_heart: We know
it takes a lot of time and effort. Everything in this document is meant
to provide you with as much insight as possible with regards to our
contribution standards. As you read it, it is important to remember that
these are just __guidelines__ and not rules. Please use your best
judgement when applying them.

#### Table of Contents

1. [I'm new, anything I should know?](#im-new-anything-i-should-know)
1. [Behaving yourself](#behaving-yourself)
1. [Environmnet setup](#environment-setup)
1. [Contributing workflow](#contributing-workflow)
1. [Making changes](#making-changes)
1. [How do I get in touch?](#how-do-i-get-in-touch)
1. [License](#license)

## I'm new, anything I should know?

:wave: Hello and welcome. :wave: The first thing you should do is _read_ the [README](./README.md).
We've put a lot of love and care in writing it and it should provide you with the context you need
for contributing to this project. Really, you should read it.

The next thing you should do is take a look at the [Architecture of this extension](./docs/ARCHITECTURE.md).

## Behaving yourself

In the interest of making the Augury project a safe and friendly
place for people from diverse backgrounds, we'll be adhering to a [Contributor Code of Conduct](./CODE_OF_CONDUCT.md). As a contributor, you'll be expected to
uphold this code as well as report unacceptable behaviour to
[augury@rangle.io](mailto:augury@rangle.io).

## Environment setup

### Download

1. Fork the repo and create your branch from master.
1. Add rangle/augury to your remotes git remote add upstream git@github.com:rangle/augury.git.
1. After cloning to local directory, create your own branch.

### Using Git

Here at Rangle we strive to adhere to the following guidelines. It is expected that any PR that is made will be branched off a forked rangle/augury master and have a sensible name with a "feature/bug/chore" prefix (e.g. feature-colour-picker).

Run `git fetch upstream` - if there are changes to rangle/augury.
Run `git rebase upstream/master` - to fast forward your local branch to upstream.

Don't forget to squash your commits. [git-scm.com](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History)

### Building and testing

1. Run `npm install`.
1. Run `npm run build` (errors related to typing files conflicts can be ignored for now).
1. Navigate to chrome://extensions and enable Developer Mode.
1. Choose "Load unpacked extension".
1. In the dialog, open your augury directory.

You can test out the extension with a quick example app. In a different terminal window:

1. Navigate to augury/example-apps/kitchen-sink-example.
1. Run `npm install`.
1. Run `npm start` on the kitchen-sink-example root folder.

### Coding style

* Use semicolons;
* Commas last,
* 2 spaces for indentation (no tabs)
* Prefer `'` over `"`
* 120 character line length
* ...

### Recommendations

* Augury `npm start` script sets up webpack to run with a watcher on your files, so when you make changes, you don't have to rebuild the extension (it'll do it for you).
* If the app becomes unresponsive, or a change is not visible, you might need to close and reopen chrome's dev tools.
* Failing the above, you might have to go to chrome://extensions and click on the Reload button.
* You can ignore some chrome warnings for now.

## Contributing workflow

Remember, no contribution is too small and no issue is too trivial. If you see a typo, we'd love to get a PR. We actually hate typos...they're the worst.

### Bugs

:beetle: We are using [GitHub Issues](https://github.com/rangle/augury/issues) for our public bugs. We will keep track on this and will to make it clear when we have an internal fix in progress. Before filing for a new task, try to make sure your problem doesn't already exist.

If you do find a new issue, the best way to get a bug fixed is to provide a test case with either one of the example apps bundled in the repo, or by making your own Angular 2.0 application illustrating the reduced use case. Don't forget to include the version of Angular 2.0 app you're using!

At the moment, we offer limited backwards compatibility until Angular 2.0 stabilizes. Please check [README](./README.md#supported-version) for the version Augury currently supports.

### Pull requests

:shipit: The core team will be monitoring for pull requests.

*Before* submitting a pull request, please make sure the following is done...

1. Fork the repo and create your branch from `dev`.
2. If you've added code that should be tested, add tests.
3. If you've changed APIs, development workflow or aspects of the architecture, update the corresponding documentation.
4. TypeScript linter is part of our build task, make sure your code lints before submitting your PRs.

More information can be found in `tslint.json` file of this repository.

TypeScript linter is part of our build task and will run in either `npm run build` or `npm start`

## Making changes

So you want to make some changes to the application. Again, we recommend taking a look at the [Augury Architecture](./docs/ARCHITECTURE.md) before trying to make changes to the app, as it will give you a better idea of where to find things.

### Front-End

So you want to develop on the front-end (make some logic or visual changes to the extension). This is a self contained Angular2 app running as an extension, so getting acquainted with [Angular2](https://angular.io/) is a good idea. We are using a [Flux](https://facebook.github.io/flux/) style application architecture with the help of [RxJS](https://github.com/Reactive-Extensions/RxJS).

_frontend structure overview_
* Actions
  * example-actions
* Components
  * example-component
    * example-controller
    * example-template
* Stores
  * example-store

#### Components

The extension is separated into various components, which can be found in batarangle/frontend/components. If you want to make changes to specific parts of the application, you have to figure out what component they belong to.

#### Controllers

Each of these components will have their .ts file containing the component class and Angular 2 decorators (like @Component or @View). If you want to modify any logic that deals with interaction with the component, this is most likely where you would find it. Most of the logic, constructor, dependencies and related actions are placed within the component class. Any necessary actions, stores or other classes can be imported into the file.

#### Templates

If you want to modify the front-end extension or the application's styles, this is where you would do it. If the inline HTML from @View in the controller is too large (or simply due to preference), you can move the templates to their own file within the component.

#### Actions

Flux defines an action as a method exposed by the dispatcher that allows us to trigger a dispatch to the stores, and to include a payload of data. There is a place where application actions are defined in various lists, due to separation of concerns (e.g. user and backend actions). These are meant to be imported into controllers to take care of any actions that specific component might want to accomplish (especially those using the Rx dispatcher).

#### Stores

*Stores contain the application state and logic.*

They are meant to manage the application state, as opposed to simply keeping a record of data, or managing collections of data. Similar to the model in traditional MVC, stores manage the state for a particular domain within the application, meaning they are associated with keeping, storing, and sending of that particular domain's data.

## How do I get in touch?

We are using Slack for all of our communication. If you want to contribute or need help getting started, join us on [Slack](https://augury-slack.herokuapp.com/).

## License

[MIT](LICENSE)


text:
#include <chipmunk/chipmunk.h>
#include <functional>
#include <unordered_map>
#include <vector>
#include "IScene.h"

enum class ShapeType : uint32_t {
  Circle,
  Segment,
  Poly,
};

class CpManager {
 public:
  static CpManager& getInstance();

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

  void clearSpace(cpSpace* space);
  cpSpace* SpaceNew(IScene::Type type);
  cpBody* BodyNew(cpSpace* space, const cpFloat& mass, const cpFloat& moment);
  cpShape* SegmentShapeNew(cpBody* body, const cpVect& a, const cpVect& b,
                           const cpFloat& radius);
  cpShape* CircleShapeNew(cpBody* body, const cpFloat& radius,
                          const cpVect& offset);
  cpConstraint* PivotJointNew(cpBody* a, cpBody* b, const cpVect& pivot);
  cpConstraint* PivotJointNew2(cpBody* a, cpBody* b, const cpVect& anchr1,
                               const cpVect& anchr2);
  void free(cpBody* body);
  void free(cpConstraint* constraint);
  cpBody* getStaticBody(cpSpace* space) const {
    return cpSpaceGetStaticBody(space);
  }

 private:
  std::unordered_map<IScene::Type, cpSpace*> mSpaces;
  std::unordered_map<cpSpace*, std::vector<cpBody*>> mBodies;
  std::unordered_map<cpSpace*, std::vector<cpShape*>> mShapes;
  std::unordered_map<cpSpace*, std::vector<cpConstraint*>> mConstraints;
  std::unordered_map<uint32_t, std::function<void()>> mLaterFuncs;
  uint32_t mPostStepId;

  CpManager();
  ~CpManager();
  friend void postStep(cpSpace* space, void* key, void* data);

  void clearSpace_(cpSpace* space);
  void free_(cpBody* body, cpSpace* space);
  void free_(cpConstraint* constraint, cpSpace* space);
};


text:
module GrapeClient
  module HasMany
    def has_many(property, options = {})
      define_method(property) do
        clazz = class_from_name(options[:class_name] || property.to_s.singularize)
        case @attributes[property]
        when Collection then @attributes[property]
        when nil
          @attributes[property] = clazz.where(:"#{self.class.entity_name}_id" => id)
        else
          @attributes[property].map! do |element|
            next element unless element.is_a? Hash
            clazz.new(element)
          end
        end
      end

      define_method(:"#{property}=") do |array|
        @attributes[property] = array
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Up::Application</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />

            Class
            Up::Application

                <

                    Object

lib/up.rb

Methods

N

new

Q

quit!

Class Public methods

                    new(dir)

                        Source: show

                        | on GitHub

    # File lib/up.rb, line 23
23:     def self.new(dir)
24:       Rack::Builder.new do
25:         run Rack::Directory.new(dir)
26:       end
27:     end

                    quit!(server)

                        Source: show

                        | on GitHub

    # File lib/up.rb, line 17
17:     def self.quit!(server)
18:       ## Use thins' hard #stop! if available, otherwise just #stop
19:       server.respond_to?(:stop!) ? server.stop! : server.stop
20:       puts "\n== Up has stopped"
21:     end


text:
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const helpers = require('./helpers');

module.exports = {
	entry : {
		'polyfills' : './src/polyfills.ts',
		'vendor' : './src/vendor.ts',
		'app' : './src/main.ts'
	},

	resolve : {
		extensions: ['.ts', '.js'],
		modules: [
            'node_modules'
        ]
	},

	module : {
		loaders : [
			{
	        	test: /\.ts$/,
	        	loaders: ['awesome-typescript-loader', 'angular2-template-loader']
			},
			{
		        test: /\.html$/,
		        loader: 'html'
			},
			{
		        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
		        loader: 'file?name=assets/[name].[hash].[ext]'
			},
			{
				test: /\.css$/,
				exclude: helpers.root('src', 'app'),
				loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css?sourceMap' })
			},
			{
				test: /\.css$/,
				include: helpers.root('src', 'app'),
				loader: 'raw'
			}
		]
	},

	plugins : [
		new HtmlWebpackPlugin({
	      template: 'src/index.html'
	    }),

	    new webpack.optimize.CommonsChunkPlugin({
	      name: ['app', 'vendor', 'polyfills']
	    }),

	    new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,__dirname)
	]
}


text:
@media (min-width: 992px) {
   .navbar-collapse {
       display: none !important;
   }
}

.video-container {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 30px; height: 0; overflow: hidden;
}

.video-container iframe,
.video-container object,
.video-container embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

.chart {
  position: relative;
  width: 100%;
  height: 500px
}

.smalltxt {
  font-size: 0.9rem;
}

.mem-icon {
  height: 1em;
}

.navb-icon {
  height: 1.8em;
}

.navbar {
  margin-bottom: 20px;
}

.welcomefont {
  font-size: 1.5em;
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}

/*
body {
  padding-top: 60px;
  padding-bottom: 40px;
}

/*
.navbar-default {
  background-color: #052049;
  border-color: #668a75;
}

.navbar-default .navbar-brand {
  font-family: "Lucida Bright", Georgia, serif;

  color: #f6f6f6;
}

.navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus {
  color: #fdfdfd;
}
.navbar-default .navbar-text {
  color: #f6f6f6;
}
.navbar-default .navbar-nav > li > a {
  color: #f6f6f6;
}
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
  color: #fdfdfd;
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus {
  color: #fdfdfd;
  background-color: #668a75;
}
.navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:hover, .navbar-default .navbar-nav > .open > a:focus {
  color: #fdfdfd;
  background-color: #668a75;
}
.navbar-default .navbar-toggle {
  border-color: #668a75;
}
.navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus {
  background-color: #668a75;
}
.navbar-default .navbar-toggle .icon-bar {
  background-color: #f6f6f6;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
  border-color: #f6f6f6;
}
.navbar-default .navbar-link {
  color: #f6f6f6;
}
.navbar-default .navbar-link:hover {
  color: #fdfdfd;
}

@media (max-width: 767px) {
  .navbar-default .navbar-nav .open .dropdown-menu > li > a {
    color: #f6f6f6;
  }
  .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
    color: #fdfdfd;
  }
  .navbar-default .navbar-nav .open .dropdown-menu > .active > a, .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
    color: #fdfdfd;
    background-color: #668a75;
  }
}
*/


text:
package io.hekate.spring.bean.internal;

import io.hekate.cluster.seed.jdbc.JdbcSeedNodeProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertFalse;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:xsd-test/test-seed-jdbc.xml")
public class XsdSeedJdbcTest extends XsdTestBase {
    @Test
    public void testExpectedProvider() {
        assertFalse(spring.getBeansOfType(JdbcSeedNodeProvider.class).isEmpty());
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Prototype</title>
    <link href="../../base-assets/_assets/css/main.css" media="all" rel="stylesheet" type="text/css">
    <link href="../../base-assets/styles/layout.css" rel="stylesheet" media="all">
    <link href="../../base-assets/css/custom.css" media="all" rel="stylesheet" type="text/css">
    <link href="site.css" media="all" rel="stylesheet" type="text/css">
    <link href="signpost.css" media="all" rel="stylesheet" type="text/css">

                Where you might need to go to get help

                <input type="text" class="search left rounded" id="searchTags" placeholder="Change question id">

            <input type="button" class="go button" value="GO" onclick="javascript: changeQuestion();" >

Migraine

A severe headache usually felt on the side or front of the head.

Migraine headaches often have other symptoms such as nausea, vomiting or increased sensitivity to light, sound or smells.


text:
package org.olat.shibboleth;

/**
 * Description:

 * TODO: Lavinia Dumitrescu Class Description for ShibbolethException
 *
 *

 * Initial Date:  31.10.2007

 * @author Lavinia Dumitrescu
 */
public class ShibbolethException extends Exception {

	//error codes
	public static final int GENERAL_SAML_ERROR = 0;
	public static final int UNIQUE_ID_NOT_FOUND = 1;
	public static final int INSUFFICIENT_ATTRIBUTES = 2;

	private int errorCode;
	private String contactPersonEmail;

	public ShibbolethException(int errorCode, String msg) {
		super(msg);
		this.errorCode = errorCode;
	}

	public ShibbolethException(int errorCode, Throwable throwable) {
		super(throwable.getMessage());
		this.errorCode = errorCode;
	}

	public ShibbolethException(int errorCode, String contactPersonEmail, Throwable throwable) {
		this(errorCode, throwable);
		this.contactPersonEmail = contactPersonEmail;
	}

	public int getErrorCode() {
		return errorCode;
	}

	public String getContactPersonEmail() {
		return contactPersonEmail;
	}

	public void setContactPersonEmail(String contactPersonEmail) {
		this.contactPersonEmail = contactPersonEmail;
	}
}


text:
import java.util.List;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

import swing2swt.layout.BorderLayout;

import com.justep.studio.data.DataColumn;
import com.justep.studio.data.DataRecord;
import com.justep.studio.data.DataSet;
import com.justep.studio.ui.editors.xui.W3cDocumentHelper;
import com.justep.studio.ui.editors.xui.XuiElement;
import com.justep.studio.ui.exjface.DataSetTableViewer;
import com.justep.studio.ui.exjface.DatasetTableLabelProvider;

public class EditDataDialog extends Dialog {
	private String title;
	private Table table;
	private DataSet dataset;
	private DataSetTableViewer tableViewer;
	private XuiElement currentElement;
	private String[] columns;

	/**
	 * Create the dialog
	 * @param parentShell
	 */
	public EditDataDialog(Shell parentShell) {
		super(parentShell);
	}

	public EditDataDialog(Shell parentShell, String title) {
		super(parentShell);
		this.title = title;
	}

	public EditDataDialog(Shell parentShell, String title, XuiElement element) {
		super(parentShell);
		this.title = title;
		currentElement = element;
	}

	public void setProperty(String propName, String propValue) {
		if (propName.equals("columnids")) {
			if (propValue != null && !propValue.equals("")) {
				String[] headers = propValue.split(",");
				for (String header : headers) {
					dataset.addColumn(header).setLength(150).setDataType("String").setHeader(header).setEditable(true).setEditor("TextCellEditor");
				}
			}
			tableViewer.reloadDataSet(dataset);
		}
	}

	/**
	 * Create contents of the dialog
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		container.setLayout(new BorderLayout(0, 0));

		//工具条
		final ToolBar toolBar = new ToolBar(container, SWT.NONE);
		toolBar.setLayoutData(BorderLayout.NORTH);
		final ToolItem newItemToolItem_2 = new ToolItem(toolBar, SWT.PUSH);
		newItemToolItem_2.setText("增加行");
		newItemToolItem_2.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (tableViewer.getTable().getColumnCount() <= 0) {
					return;
				}
				Object[] values = new Object[] { "" };
				dataset.addRecord(values);
			}
		});

		final ToolItem newItemToolItem_3 = new ToolItem(toolBar, SWT.PUSH);
		newItemToolItem_3.setText("删除行");

		newItemToolItem_3.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				List<DataRecord> list = dataset.getSelectedRecord();
				if (list.size() > 0) {
					dataset.deleteRecord(dataset.getSelectedRecord().get(0));
				}
			}
		});

		//表格
		tableViewer = new DataSetTableViewer(container, SWT.BORDER | SWT.FULL_SELECTION);
		tableViewer.setLabelProvider(new DatasetTableLabelProvider(tableViewer) {
			public Color getBackground(Object element, int columnIndex) {
				Color color = new Color(null, 211, 226, 243);
				return color;
			}
		});
		table = tableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		initParamTable();
		setTableData();
		return container;
	}

	private void setTableData() {
		XuiElement lastRowsElement = currentElement.getChildByTagName("rows");
		if (lastRowsElement == null) {
			return;
		}
		List<XuiElement> rowList = lastRowsElement.getChildListByTagName("row");
		if (rowList == null || rowList.size() <= 0) {
			return;
		}
		String[] vals = new String[columns.length];
		for (int i = 0; i < rowList.size(); i++) {
			XuiElement row = rowList.get(i);
			List<XuiElement> cells = row.getChildListByTagName("cell");
			List<DataColumn> list = dataset.getDataColumns();
			if (list != null && list.size() > 0) {
				for (int j = 0; j < list.size(); j++) {
					try {
						XuiElement cell = cells.get(j);
						vals[j] = W3cDocumentHelper.getText(cell.getOriginElement());
					} catch (Exception e) {
						vals[j] = "";
					}
				}
				dataset.addRecord(vals);
			}
		}
	}

	/**
	 * Create contents of the button bar
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, "确定", true);
		createButton(parent, IDialogConstants.CANCEL_ID, "取消", false);
	}

	public void editData() {
	}

	/**
	 * Return the initial size of the dialog
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(500, 400);
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText(this.title);
	}

	public List<DataRecord> getRecord() {
		return this.dataset.getData();
	}

	public String[] getTableColumnCount() {
		return columns;
	}

	private void initParamTable() {
		columns = currentElement.getProperyValue("columns").split(",");
		dataset = new DataSet();
		for (int i = 0; i < columns.length; i++) {
			if (!columns[i].equals("")) {
				dataset.addColumn(columns[i], columns[i], "string").setLength(150).setEditor("TextCellEditor");
			}
		}
		tableViewer.setDataSet(dataset);
	}

}


text:
namespace ckb_ar {

// The id of this IME/keyboard.
extern const char* kId;

// Whether this keyboard layout is a 102 or 101 keyboard.
extern bool kIs102;

// The key mapping definitions under various modifier states.
extern const char** kKeyMap[8];

}  // namespace ckb_ar

#endif  // CHROMEOS_SERVICES_IME_PUBLIC_CPP_RULEBASED_DEF_CKB_AR_H_


text:
(function() {
  'use strict';

  describe('Service: Create', function() {
    var subject,
        $window,
        $location,
        Assessment;
    beforeEach(function() {
      module('PDRClient', function($provide) {
        $provide.value('$stateParams', {id: 1});
      });
      inject(function(_$window_, _$location_, _$injector_) {
        $window = _$window_;
        $location = _$location_;
        Assessment = _$injector_.get('Assessment');

        subject = _$injector_.get('CreateService');
      });
    });

    describe('on initialization', function() {
      it('sets alertError to false', function() {
        expect(subject.alertError).toEqual(false);
      });
    });

    describe('#formattedDate', function() {
      it('uses the right format provided to MomentJS', function() {
        var result = subject.formattedDate(new Date('01/01/2001'));
        expect(result).toEqual('Jan 1, 2001');
      });
    });

    describe('#loadDistrict', function() {
      it('sets a value in the service', function() {
        expect(subject.district).toBeUndefined();
        subject.district = {id: 1};
        expect(subject.district).not.toBeUndefined();
      });
    });

    describe('#loadScope', function() {
      it('sets a value in the service', function() {
        expect(subject.scope).toBeUndefined();
        subject.scope = {id: 1};
        expect(subject.scope).not.toBeUndefined();
      });
    });

    describe('#toggleSavingState', function() {
      var $scope;
      beforeEach(function() {
        inject(function(_$rootScope_) {
          $scope = _$rootScope_.$new(true);
        });
        spyOn($scope, '$emit');
        subject.scope = $scope;
      });

      it('emits the correct event', function() {
        subject.toggleSavingState();
        expect($scope.$emit).toHaveBeenCalledWith('toggle-saving-state');
      });
    });

    describe('#emitSuccess', function() {
      var $scope;
      beforeEach(function() {
        inject(function(_$rootScope_) {
          $scope = _$rootScope_.$new(true);
        });
        spyOn($scope, '$emit');
        subject.scope = $scope;
      });

      it('emits the correct event', function() {
        subject.emitSuccess('w00t');
        expect($scope.$emit).toHaveBeenCalledWith('add-assign-alert', {type: 'success', msg: 'w00t'});
      });
    });

    describe('#emitError', function() {
      var $scope;
      beforeEach(function() {
        inject(function(_$rootScope_) {
          $scope = _$rootScope_.$new(true);
        });
        spyOn($scope, '$emit');
        subject.scope = $scope;
      });

      it('emits the correct event', function() {
        subject.emitError('oh n0ez');
        expect($scope.$emit).toHaveBeenCalledWith('add-assign-alert', {type: 'danger', msg: 'oh n0ez'});
      });
    });

    describe('#assignAndSaveAssessment', function() {
      var $httpBackend;
      beforeEach(function() {
        inject(function(_$httpBackend_) {
          $httpBackend = _$httpBackend_;
        });
      });

      describe('when the assessment message is null', function() {
        var assessment = {message: null};

        it('sets alertError to true', function() {
          subject.assignAndSaveAssessment(assessment);
          expect(subject.alertError).toBe(true);
        });
      });

      describe('when the assessment message is blank', function() {
        var assessment = {message: ''};

        it('sets alertError to true', function() {
          subject.assignAndSaveAssessment(assessment);
          expect(subject.alertError).toBe(true);
        });
      });

      describe('when the alert dialog is not accepted', function() {
        var assessment = {message: 'This is a test!'};
        var $window;
        beforeEach(function() {
          inject(function(_$window_) {
            $window = _$window_;
          });
          subject.$window = $window;
          spyOn($window, 'confirm').and.returnValue(false);
          spyOn(subject, 'saveAssessment');
        });

        it('does not invoke #saveAssessment', function() {
          subject.assignAndSaveAssessment(assessment);
          expect(subject.saveAssessment).not.toHaveBeenCalled();
        });
      });

      describe('when the alert dialog is accepted', function() {
        var assessment = {message: 'This is a test!'};
        var $window;
        beforeEach(function() {
          inject(function(_$window_) {
            $window = _$window_;
          });
          subject.$window = $window;
          spyOn($window, 'confirm').and.returnValue(true);
          spyOn(subject, 'saveAssessment').and.returnValue({
            then: function(callback) {
              callback();
            }
          });
        });

        it('does call the save method on the scope', function() {
          subject.assignAndSaveAssessment(assessment);
          expect(subject.saveAssessment).toHaveBeenCalled();
        });

        it('sets the location to /assessments', function() {
          subject.assignAndSaveAssessment(assessment);
          expect($location.path()).toEqual('/assessments');
        });
      });
    });

    describe('#saveAssessment', function() {
      describe('when the assessment name is blank', function() {
        beforeEach(function() {
          var assessment = {name: ''};
          spyOn(subject, 'emitError');
          subject.saveAssessment(assessment, true);
        });

        it('invokes #emitError', function() {
          expect(subject.emitError).toHaveBeenCalledWith('Assessment needs a name!');
        });
      });

      describe('when the assessment name is not blank', function() {
        var assessment,
            inputField,
            $scope;

        beforeEach(function() {
          assessment = {id: 1, name: 'This is a test'};
          inject(function(_$rootScope_, _$compile_) {
            $scope = _$rootScope_.$new(true);
            inputField = angular.element('<input class="form-control" id="due-date" data-format="dd/MM/yyyy" name="due-date">');
            angular.element(document.body).append(inputField);
            inputField.val('08/01/1997');
            _$compile_(inputField)($scope);
          });
          subject.district = {id: 1};
          subject.scope = $scope;
        });

        it('pulls the date value from the input form', function() {
          subject.saveAssessment(assessment, true);
          expect(assessment.due_date).toEqual(moment('08/01/1997', 'MM/DD/YYYY').toISOString());
        });

        describe('when assign is true', function() {
          it('sets assessment.assign to true', function() {
            subject.saveAssessment(assessment, true);
            expect(assessment.assign).toEqual(true);
          });
        });

        describe('when assign is false', function() {
          it('leaves assessment.assign undefined', function() {
            subject.saveAssessment(assessment, false);
            expect(assessment.assign).toBeUndefined();
          });
        });

        describe('when the save is successful', function() {
          var successfulAssessment,
              $httpBackend;

          beforeEach(function() {
            successfulAssessment = {
              id: 1,
              name: 'This is a test',
              district_id: 19,
              due_date: moment('08/01/1997', 'MM/DD/YYYY').toISOString(),
              assign: true
            };

            inject(function(_$httpBackend_) {
              $httpBackend = _$httpBackend_;
            });

            subject.district = {id: 1};

            $httpBackend.expect('PUT', '/v1/assessments/1', successfulAssessment).respond(201);
          });

          it('invokes #emitSuccess function with the correct parameter', function() {
            spyOn(subject, 'emitSuccess');
            subject.saveAssessment(successfulAssessment, true);
            $httpBackend.flush();
            expect(subject.emitSuccess).toHaveBeenCalledWith('Assessment Saved!');
          });

          afterEach(function() {
            $httpBackend.verifyNoOutstandingRequest();
            $httpBackend.verifyNoOutstandingExpectation();
          });
        });

        describe('when the save is unsuccessful', function() {
          var unsuccessfulAssessment,
              $httpBackend;

          beforeEach(function() {

            unsuccessfulAssessment = {
              id: 1,
              name: 'This is a test',
              district_id: 19,
              due_date: moment('08/01/1997', 'MM/DD/YYYY').toISOString(),
              assign: true
            };

            inject(function(_$httpBackend_) {
              $httpBackend = _$httpBackend_;
            });

            subject.district = {id: 1};

            $httpBackend.expect('PUT', '/v1/assessments/1', unsuccessfulAssessment).respond(400);
          });

          it('invokes #emitError function with the correct parameter', function() {
            spyOn(subject, 'emitError');
            subject.saveAssessment(unsuccessfulAssessment, true);
            $httpBackend.flush();
            expect(subject.emitError).toHaveBeenCalledWith('Could not save assessment');
          });

          afterEach(function() {
            $httpBackend.verifyNoOutstandingRequest();
            $httpBackend.verifyNoOutstandingExpectation();
          });
        });

        afterEach(function() {
          inputField.remove();
        });
      });
    });

    describe('#save', function() {
      describe('when the context is set to assessment', function() {
        beforeEach(function() {
          subject.context = 'assessment';
          spyOn(subject, 'saveAssessment');

          subject.save({});
        });

        it('calls #saveAssessment', function() {
          expect(subject.saveAssessment).toHaveBeenCalled();
        });
      });

      describe('when the context is set to inventory', function() {
        beforeEach(function() {
          subject.context = 'inventory';
          spyOn(subject, 'saveInventory');

          subject.save({});
        });

        it('calls #saveInventory', function() {
          expect(subject.saveInventory).toHaveBeenCalled();
        });
      });
    });
  });
})();


text:
    Digging program.
    Written by Daniel Keep.

    Copyright 2012.
    Released under the MIT license.
  ]]

--[[
    Usage: dig [OPTIONS] [front] [up] [down]
  ]]

local args = {...}
local VERSION = 0.1

local GRAVITY_WAIT = 0.4

local front = false
local up = false
local down = false
local gravity = false

if #args == 0 then
    front = true
end

for _,arg in ipairs(args) do
    if arg == 'up' or arg == 'u' then
        up = true
    elseif arg == 'down' or arg == 'd' then
        down = true
    elseif arg == 'front' or arg == 'f' then
        front = true
    elseif arg == '-gravity' or arg == '-g' then
        gravity = true
    else
        error "invalid argument"
    end
end

if down then
    if turtle.detectDown() then turtle.digDown() end
end

if up then
    while turtle.detectUp() do
        turtle.digUp()
        if gravity then
            os.sleep(GRAVITY_WAIT)
        end
    end
end

if front then
    while turtle.detect() do
        turtle.dig()
        if gravity then
            os.sleep(GRAVITY_WAIT)
        end
    end
end


text:
import math
import random
import sys
import datetime
import time

from . import trampoline
from . import type_utilities
from . import string_utilities
from . import options
from . import function_type
from . import list_utilities
from . import input_utilities
from . import bitwise_operations
from . import utilities
from . import error

CLOSURE_TRAMPOLINE_WRAPPER = utilities.make_arguments_processor(
    trampoline.closure_trampoline,
)
BUILTIN_FUNCTIONS = {
    'nil': function_type.make_type([], handler=lambda: None),
    'false': function_type.make_type([], handler=lambda: 0.0),
    'true': function_type.make_type([], handler=lambda: 1.0),
    'bool': function_type.make_type([1], handler=lambda x: 1.0 if x else 0.0),
    'num': function_type.make_type(
        [1],
        handler=lambda x: float(string_utilities.make_string_from_list(x)),
    ),
    'type': function_type.make_type(
        [1],
        handler=lambda x: string_utilities.make_list_from_string(
            type_utilities.get_type_name(x),
        ),
    ),
    '!': function_type.make_type([1], handler=lambda x: float(not x)),
    '&&': function_type.make_type(
        [2],
        handler=lambda x, y: trampoline.closure_trampoline(x) and y,
    ),
    '||': function_type.make_type(
        [2],
        handler=lambda x, y: trampoline.closure_trampoline(x) or y,
    ),
    '==': function_type.make_type([2], handler=lambda x, y: float(x == y)),
    '!=': function_type.make_type([2], handler=lambda x, y: float(x != y)),
    '<': function_type.make_type([2], handler=lambda x, y: float(x < y)),
    '<=': function_type.make_type([2], handler=lambda x, y: float(x <= y)),
    '>': function_type.make_type([2], handler=lambda x, y: float(x > y)),
    '>=': function_type.make_type([2], handler=lambda x, y: float(x >= y)),
    '_': function_type.make_type([1], handler=lambda x: -x),
    '++': function_type.make_type([1], handler=lambda x: x + 1),
    '--': function_type.make_type([1], handler=lambda x: x - 1),
    '-': function_type.make_type([2], handler=lambda x, y: x - y),
    '*': function_type.make_type([2], handler=lambda x, y: x * y),
    '/': function_type.make_type([2], handler=lambda x, y: x / y),
    '%': function_type.make_type([2], handler=lambda x, y: x % y),
    '&': function_type.make_type([2], handler=bitwise_operations.bitwise_and),
    '|': function_type.make_type([2], handler=bitwise_operations.bitwise_or),
    '^': function_type.make_type([2], handler=bitwise_operations.bitwise_xor),
    '<<': function_type.make_type(
        [2],
        handler=bitwise_operations.bitwise_left_shift,
    ),
    '>>': function_type.make_type(
        [2],
        handler=bitwise_operations.bitwise_arithmetic_right_shift,
    ),
    '>>>': function_type.make_type(
        [2],
        handler=bitwise_operations.bitwise_logical_right_shift,
    ),
    '~': function_type.make_type([1], handler=bitwise_operations.bitwise_not),
    'floor': function_type.make_type(
        [1],
        handler=lambda x: float(math.floor(x)),
    ),
    'ceil': function_type.make_type([1], handler=lambda x: float(math.ceil(x))),
    'trunc': function_type.make_type(
        [1],
        handler=lambda x: float(math.trunc(x)),
    ),
    'round': function_type.make_type([1], handler=lambda x: float(round(x))),
    'sin': function_type.make_type([1], handler=math.sin),
    'cos': function_type.make_type([1], handler=math.cos),
    'tn': function_type.make_type([1], handler=math.tan),
    'arcsin': function_type.make_type([1], handler=math.asin),
    'arccos': function_type.make_type([1], handler=math.acos),
    'arctn': function_type.make_type([1], handler=math.atan),
    'angle': function_type.make_type(
        [2],
        handler=lambda x, y: math.atan2(y, x),
    ),
    'pow': function_type.make_type([2], handler=math.pow),
    'sqrt': function_type.make_type([1], handler=math.sqrt),
    'exp': function_type.make_type([1], handler=math.exp),
    'ln': function_type.make_type([1], handler=math.log),
    'lg': function_type.make_type([1], handler=math.log10),
    'abs': function_type.make_type([1], handler=math.fabs),
    'nan': function_type.make_type([], handler=lambda: math.nan),
    'inf': function_type.make_type([], handler=lambda: math.inf),
    'is_nan': function_type.make_type(
        [1],
        handler=lambda x: float(math.isnan(x)),
    ),
    'pi': function_type.make_type([], handler=lambda: math.pi),
    'e': function_type.make_type([], handler=lambda: math.e),
    'seed': function_type.make_type([1], handler=random.seed),
    'random': function_type.make_type([], handler=random.random),
    '[]': function_type.make_type([], handler=lambda: ()),
    ',': function_type.make_type([2], handler=lambda x, y: (x, y)),
    'head': function_type.make_type(
        [1],
        handler=lambda value: value[0] if value != () else None,
    ),
    'tail': function_type.make_type(
        [1],
        handler=lambda value: value[1] if value != () else None,
    ),
    '{}': function_type.make_type([], handler=lambda: {}),
    '#': function_type.make_type(
        [3],
        handler=lambda new_key, new_value, hash_: {
            **hash_,
            new_key: new_value,
        } if new_value is not None else {
            key: value
            for key, value in hash_.items()
            if key != new_key
        },
    ),
    'keys': function_type.make_type(
        [1],
        handler=lambda hash_: list_utilities.reduce_list(list(hash_.keys())),
    ),
    '??': function_type.make_type(
        [2],
        handler=lambda value, default: value if value is not None else default,
    ),
    'if': function_type.make_type(
        [3],
        handler=lambda condition, true, false: \
            true if trampoline.closure_trampoline(condition) else false,
    ),
    '+': function_type.make_type([2], handler=type_utilities.combine),
    'size': function_type.make_type(
        [1],
        handler=lambda value: float(type_utilities.get_size(value)),
    ),
    '.': function_type.make_type(
        [2],
        handler=lambda index, collection: type_utilities.get_item(
            collection,
            index,
        ),
    ),
    '>@': function_type.make_type([1], handler=lambda value: (value,)),
    '<@': function_type.make_type([1], handler=lambda value: value[0]),
    '<<@': function_type.make_type([1], handler=trampoline.pack_trampoline),
    'str': function_type.make_type(
        [1],
        handler=lambda x: string_utilities.make_list_from_string(
            string_utilities.get_representation(x),
        ),
    ),
    'strb': function_type.make_type(
        [1],
        handler=lambda x: string_utilities.make_list_from_string(
            'true' if x else 'false',
        ),
    ),
    'strs': function_type.make_type(
        [1],
        handler=lambda x: string_utilities.make_list_from_string(
            string_utilities.get_string_representation(x),
        ),
    ),
    'strl': function_type.make_type(
        [1],
        handler=lambda x: string_utilities.make_list_from_string(
            string_utilities.get_list_representation(
                x,
                string_utilities.get_string_representation,
            ),
        ),
    ),
    'strh': function_type.make_type(
        [1],
        handler=lambda x: string_utilities.make_list_from_string(
            string_utilities.get_hash_representation(
                x,
                string_utilities.get_string_representation,
            ),
        ),
    ),
    'strhh': function_type.make_type(
        [1],
        handler=lambda x: string_utilities.make_list_from_string(
            string_utilities.get_hash_representation(
                x,
                string_utilities.get_string_representation,
                string_utilities.get_string_representation,
            ),
        ),
    ),
    'env': function_type.make_type(
        [1],
        handler=options.get_environment_variable,
    ),
    'time': function_type.make_type(
        [],
        handler=lambda: \
            datetime.datetime.now(datetime.timezone.utc).timestamp(),
    ),
    'sleep': function_type.make_type([1], handler=lambda x: time.sleep(x)),
    'in': function_type.make_type([1], handler=input_utilities.read_input),
    'inln': function_type.make_type(
        [1],
        handler=input_utilities.read_input_line,
    ),
    'out': function_type.make_type(
        [1],
        handler=lambda x: print(
            string_utilities.make_string_from_list(x),
            end='',
        ),
    ),
    'outln': function_type.make_type(
        [1],
        handler=lambda x: print(string_utilities.make_string_from_list(x)),
    ),
    'err': function_type.make_type(
        [1],
        handler=lambda x: sys.stderr.write(
            string_utilities.make_string_from_list(x),
        ),
    ),
    'errln': function_type.make_type(
        [1],
        handler=lambda x: sys.stderr.write(
            string_utilities.make_string_from_list(x) + '\n',
        ),
    ),
    'exit': function_type.make_type([1], handler=error.exit),
    'load': function_type.make_type([1]), # dummy
    'is_main': function_type.make_type([]), # dummy
    'args': function_type.make_type([]), # dummy
}

_NOT_TRAMPOLINED_FUNCTIONS = ['&&', '||', 'if', '>@']

for name, entity_type in BUILTIN_FUNCTIONS.items():
    if name not in _NOT_TRAMPOLINED_FUNCTIONS and entity_type.arity > 0:
        entity_type.handler = CLOSURE_TRAMPOLINE_WRAPPER(entity_type.handler)


text:
import { throwPb } from '../../errors/props.js'
import { getLimits } from '../../limits.js'

import { validateString } from './validate.js'

export const parseOrigin = function ({
  protocolAdapter,
  protocolAdapter: { getUrl, getOrigin },
  specific,
  config,
}) {
  // Only used to validate URL length
  const url = getUrl({ specific })

  validateString(url, 'url', protocolAdapter)
  validateUrl({ url, config })

  const origin = getOrigin({ specific })

  validateString(origin, 'origin', protocolAdapter)

  return { origin }
}

const validateUrl = function ({ url, config }) {
  const { maxUrlLength } = getLimits({ config })

  if (url.length <= maxUrlLength) {
    return
  }

  throwPb({
    reason: 'URL_LIMIT',
    extra: { value: url.length, limit: maxUrlLength },
  })
}


text:
import {Component, forwardRef, Inject, Input, Optional} from '@angular/core';
import {GalleryComponent} from './gallery.component';

@Component({
  selector: 'vcl-gallery-thumbnails',
  templateUrl: 'gallery-thumbnails.component.html',
})
export class GalleryThumbnailsComponent {

  @Input()
  galleryTitle: string;
  @Input()
  vertical: boolean;
  @Input()
  target: GalleryComponent;

  constructor(@Optional() parent: GalleryComponent) {
    if (this.target == null) {
      this.target = parent;
    }
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Jard. Bot. État 14: 84 (1936)

#### Original name
Russula xylophila Beeli

### Remarks
null


text:
namespace Farmhand
{
    /// <summary>
    ///     Contains the variable possible states of a Mod
    /// </summary>
    public enum ModState
    {
        /// <summary>
        ///     Unloaded mods have not yet been loaded by the ModLoader
        /// </summary>
        Unloaded,

        /// <summary>
        ///     Loaded mods are activate and should be functioning
        /// </summary>
        Loaded,

        /// <summary>
        ///     Deactivated mods are ones which were manually deactivated
        /// </summary>
        Deactivated,

        /// <summary>
        ///     This mod was found to have a missing dependency by the ModLoader
        /// </summary>
        MissingDependency,

        /// <summary>
        ///     A required dependency of this mod failed on entry.
        /// </summary>
        DependencyLoadError,

        /// <summary>
        ///     This mod threw an exception and was forcibly unloaded by the ModLoader
        /// </summary>
        Errored,

        /// <summary>
        ///     This mod did not have a valid manifest. Typically this is caused by things such as invalid UniqueIDs or Content
        ///     issues.
        /// </summary>
        InvalidManifest
    }
}


text:
<?php

/**
 * CompetencyTranslation form base class.
 *
 * @method CompetencyTranslation getObject() Returns the current form's model object
 *
 * @package    alumni
 * @subpackage form
 * @author     E.R. Nurwijayadi <epsi.rns@gmail.com>
 * @version    SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $
 */
abstract class BaseCompetencyTranslationForm extends BaseFormDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'competency_id' => new sfWidgetFormInputHidden(),
      'competency'    => new sfWidgetFormInputText(),
      'lang'          => new sfWidgetFormInputHidden(),
    ));

    $this->setValidators(array(
      'competency_id' => new sfValidatorChoice(array('choices' => array($this->getObject()->get('competency_id')), 'empty_value' => $this->getObject()->get('competency_id'), 'required' => false)),
      'competency'    => new sfValidatorString(array('max_length' => 30)),
      'lang'          => new sfValidatorChoice(array('choices' => array($this->getObject()->get('lang')), 'empty_value' => $this->getObject()->get('lang'), 'required' => false)),
    ));

    $this->validatorSchema->setPostValidator(
      new sfValidatorDoctrineUnique(array('model' => 'CompetencyTranslation', 'column' => array('competency')))
    );

    $this->widgetSchema->setNameFormat('competency_translation[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'CompetencyTranslation';
  }

}


text:
function microwatch(isDouble) {
	self       = this
	microtime  = require('microtime')
	_double    = (isDouble)
	_begin     = 0

	self.start = function() {
		_begin = (_double) ? microtime.nowDouble()          : microtime.now()
	}

	self.now = function() {
		duration = (_double) ? microtime.nowDouble() - _begin : microtime.now() - _begin
		return duration
	}
}

module.exports = microwatch


text:
var keyMirror = require('react/lib/keyMirror');

module.exports = {

  ActionTypes: keyMirror({
    CREATE_BAR: null,
    RECEIVE_RAW_BARS: null
  }),

  PayloadSources: keyMirror({
    SERVER_ACTION: null,
    VIEW_ACTION: null
  })

};


text:
<?php

namespace MDW\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use MDW\DemoBundle\Entity\Articles;
use MDW\DemoBundle\Form\ArticleType;

class ArticulosController extends Controller
{
	public function listarAction()
	{
            $em = $this->getDoctrine()->getEntityManager();

            $articulos = $em->getRepository('MDWDemoBundle:Articles')->findAll();
            $comentarios = $em->getRepository('MDWDemoBundle:Comments')->findAll();

            //return $this->render('MDWDemoBundle:Articulos:listar.html.twig', array('articulos' => $articulos));
            return $this->render('MDWDemoBundle:Articulos:listar.html.twig', array('articulos' => $articulos, 'comentarios' => $comentarios));
	}

	public function crearAction()
	{
            $articulo = new Articles();
            //$articulo->setTitle('Prueba');
            $articulo->setAuthor('Rafa Nadal');
            $articulo->setContent('Contenido');
            $articulo->setTags('ejemplo');
            $articulo->setCreated(new \DateTime());
            $articulo->setUpdated(new \DateTime());
            $articulo->setSlug('articulo-de-ejemplo-3');
            $articulo->setCategory('ejemplo');

            $errores = $this->get('validator')->validate($articulo);

            if(!empty($errores)) {
                foreach($errores as $error)
                    echo $error->getMessage();

                return new Response();
            }

            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($articulo);
            $em->flush();

            return $this->render('MDWDemoBundle:Articulos:articulo.html.twig', array('articulo' => $articulo));
	}

	public function editarAction($id)
	{
            $em = $this->getDoctrine()->getEntityManager();

            $articulo = $em->getRepository('MDWDemoBundle:Articles')->find($id);

            $articulo->setTitle('Articulo de ejemplo 1 - modificado');
            $articulo->setAuthor('Israel Romo');
            $articulo->setUpdated(new \DateTime());

            $em->persist($articulo);
            $em->flush();

            return $this->render('MDWDemoBundle:Articulos:articulo.html.twig', array('articulo' => $articulo));
	}

	public function borrarAction($id)
	{
            $em = $this->getDoctrine()->getEntityManager();

            $articulo = $em->getRepository('MDWDemoBundle:Articles')->find($id);

            $em->remove($articulo);
            $em->flush();

            return $this->redirect(
                $this->generateUrl('articulo_listar'));

	}

	public function newAction()
        {
            //-- Obtenemos el request que contendráos datos
            $request = $this->getRequest();

            $articulo = new Articles();
            $form = $this->createForm(new ArticleType(), $articulo);

            //-- En caso de que el request haya sido invocado por POST
            //   procesaremos el formulario
            if($request->getMethod() == 'POST')
            {
                //-- Pasamos el request el médo bindRequest() del objeto
                //   formulario el cual obtiene los datos del formulario
                //   y los carga dentro del objeto Article que estáontenido
                //   tambiédentro del objeto Type
                $form->bindRequest($request);

                //-- Con esto nuestro formulario ya es capaz de decirnos si
                //   los dato son vádos o no y en caso de ser asi
                if($form->isValid())
                {
                   //-- Procesamos los datos que ya estáautomácamente
                   //   cargados dentro de nuestra variable $articulo, ya sea
                   //   grabáolos en la base de datos, enviando un mail, etc
                   $em = $this->getDoctrine()->getManager();
                   $em->persist($articulo);
                   $em->flush();

                   //-- Finalmente, al finalizar el procesamiento, siempre es
                   //   importante realizar una redireccióara no tener el
                   //   problema de que al intentar actualizar el navegador
                   //   nos dice que lo datos se deben volver a reenviar. En
                   //   este caso iremos a la pána del listado de artílos
                   return $this->redirect($this->generateURL('articulo_listar'));
               }
           }
           return $this->render('MDWDemoBundle:Articulos:new.html.twig', array('form' => $form->createView(),));
        }
}


text:
  <link rel="stylesheet" href="maven-theme.css">
  <title>AppSecInc. MSI Extensions</title>

Main Page

Related Pages

Namespaces

Classes

Files

File List

File Members

src

WixExtensions

CommonUiExtension

wixext

Xsd

Namespaces

CommonUi.xsd File Reference

Namespaces

 	Wix::Extensions::CommonUi

     © Application Security Inc. - All Rights Reserved

     http://msiext.codeplex.com

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


text:
XcodeEnv
========

A simple app that create Xcode's env.txt file and show it on the view.

Why
---

I wanted to know where are macros like **$(PROJECT_ROOT)** and how many. I did in this project.

1. Create run script at TARGETS > Buid Phases
2. Register script below.

`env > env.txt`

Additionally, to show it on the app, I added some script which is not essential.

Example
-------

Just run and then the env.txt file will be created in the project root directory. After that the app shows the content of it.

Author
------

- [@morizotter](http://twitter.com/morizotter)
- [Morita Naoki](http://moritanaoki.org/about/)


text:
package org.metaja.compiler;

import java.net.URI;
import java.net.URISyntaxException;

public class JavaClassName {

    public final String simple;
    public final String pack;
    public final String full;

    public JavaClassName(String simple, String pack) {
        this.simple = validateSimpleClassName(simple);
        this.pack = validatePackageName(pack);
        this.full = pack.equals("") ? simple : pack + "." + simple;
    }

    public JavaClassName(String className) {
        int dot = className.lastIndexOf(".");
        if (dot >= 0) {
            this.simple = className.substring(dot);
            this.pack = className.substring(0, dot);
        } else {
            this.simple = className;
            this.pack = "";
        }
        this.full = className;
    }

    public URI toURI() {
        try {
            return new URI(full);
        } catch (URISyntaxException e) {
            throw new Error();
        }
    }

    public static String validateSimpleClassName(String simpleClassName) throws IllegalArgumentException {
        if (simpleClassName == null ) {
            throw new NullPointerException();
        }

        // todo: implement by JLS

        if (simpleClassName.contains(".")) {
            throw new IllegalArgumentException();
        }
        return simpleClassName;
    }

    public static String validatePackageName(String packageName) throws IllegalArgumentException {
        if (packageName == null ) {
            throw new NullPointerException();
        }

        // todo: implement by JLS

        return packageName;
    }
}


text:
<?php
/**
 * The custom background script.
 *
 * @package WordPress
 * @subpackage Administration
 */

/**
 * The custom background class.
 *
 * @since 3.0.0
 * @package WordPress
 * @subpackage Administration
 */
class Custom_Background {

	/**
	 * Callback for administration header.
	 *
	 * @var callback
	 * @since unknown
	 * @access private
	 */
	var $admin_header_callback;

	/**
	 * Callback for header div.
	 *
	 * @var callback
	 * @since 3.0.0
	 * @access private
	 */
	var $admin_image_div_callback;

	/**
	 * Holds the page menu hook.
	 *
	 * @var string
	 * @since 3.0.0
	 * @access private
	 */
	var $page = '';

	/**
	 * PHP4 Constructor - Register administration header callback.
	 *
	 * @since 3.0.0
	 * @param callback $admin_header_callback
	 * @param callback $admin_image_div_callback Optional custom image div output callback.
	 * @return Custom_Background
	 */
	function Custom_Background($admin_header_callback = '', $admin_image_div_callback = '') {
		$this->admin_header_callback = $admin_header_callback;
		$this->admin_image_div_callback = $admin_image_div_callback;
	}

	/**
	 * Set up the hooks for the Custom Background admin page.
	 *
	 * @since 3.0.0
	 */
	function init() {
		if ( ! current_user_can('edit_theme_options') )
			return;

		$this->page = $page = add_theme_page(__('Background'), __('Background'), 'edit_theme_options', 'custom-background', array(&$this, 'admin_page'));

		add_action("load-$page", array(&$this, 'admin_load'));
		add_action("load-$page", array(&$this, 'take_action'), 49);
		add_action("load-$page", array(&$this, 'handle_upload'), 49);

		if ( $this->admin_header_callback )
			add_action("admin_head-$page", $this->admin_header_callback, 51);
	}

	/**
	 * Set up the enqueue for the CSS & JavaScript files.
	 *
	 * @since 3.0.0
	 */
	function admin_load() {
		add_contextual_help( $this->page, '
' . __( 'You can customize the look of your site without touching any of your theme’s code by using a custom background. Your background can be an image or a color.' ) . '
' .
		'
' . __( 'To use a background image, simply upload it, then choose your display options below. You can display a single instance of your image, or tile it to fill the screen. You can have your background fixed in place, so your site content moves on top of it, or you can have it scroll with your site.' ) . '
' .
		'
' . __( 'You can also choose a background color. If you know the hexadecimal code for the color you want, enter it in the Color field. If not, click on the Select a Color link, and a color picker will allow you to choose the exact shade you want.' ) . '
' .
		'
' . __( 'Don’t forget to click on the Save Changes button when you are finished.' ) . '
' .
		'
' . __( 'For more information:' ) . '
' .
		'
' . __( 'Documentation on Custom Background' ) . '
' .
		'
' . __( 'Support Forums' ) . '
' );
		wp_enqueue_script('custom-background');
		wp_enqueue_style('farbtastic');
	}

	/**
	 * Execute custom background modification.
	 *
	 * @since 3.0.0
	 */
	function take_action() {

		if ( empty($_POST) )
			return;

		if ( isset($_POST['reset-background']) ) {
			check_admin_referer('custom-background-reset', '_wpnonce-custom-background-reset');
			remove_theme_mod('background_image');
			remove_theme_mod('background_image_thumb');
			$this->updated = true;
			return;
		}

		if ( isset($_POST['remove-background']) ) {
			// @TODO: Uploaded files are not removed here.
			check_admin_referer('custom-background-remove', '_wpnonce-custom-background-remove');
			set_theme_mod('background_image', '');
			set_theme_mod('background_image_thumb', '');
			$this->updated = true;
			return;
		}

		if ( isset($_POST['background-repeat']) ) {
			check_admin_referer('custom-background');
			if ( in_array($_POST['background-repeat'], array('repeat', 'no-repeat', 'repeat-x', 'repeat-y')) )
				$repeat = $_POST['background-repeat'];
			else
				$repeat = 'repeat';
			set_theme_mod('background_repeat', $repeat);
		}

		if ( isset($_POST['background-position-x']) ) {
			check_admin_referer('custom-background');
			if ( in_array($_POST['background-position-x'], array('center', 'right', 'left')) )
				$position = $_POST['background-position-x'];
			else
				$position = 'left';
			set_theme_mod('background_position_x', $position);
		}

		if ( isset($_POST['background-attachment']) ) {
			check_admin_referer('custom-background');
			if ( in_array($_POST['background-attachment'], array('fixed', 'scroll')) )
				$attachment = $_POST['background-attachment'];
			else
				$attachment = 'fixed';
			set_theme_mod('background_attachment', $attachment);
		}

		if ( isset($_POST['background-color']) ) {
			check_admin_referer('custom-background');
			$color = preg_replace('/[^0-9a-fA-F]/', '', $_POST['background-color']);
			if ( strlen($color) == 6 || strlen($color) == 3 )
				set_theme_mod('background_color', $color);
			else
				set_theme_mod('background_color', '');
		}

		$this->updated = true;
	}

	/**
	 * Display the custom background page.
	 *
	 * @since 3.0.0
	 */
	function admin_page() {
?>

<?php screen_icon(); ?>

<?php _e('Custom Background'); ?>

<?php if ( !empty($this->updated) ) { ?>

<?php printf( __( 'Background updated. Visit your site to see how it looks.' ), home_url( '/' ) ); ?>

<?php }

	if ( $this->admin_image_div_callback ) {
		call_user_func($this->admin_image_div_callback);
	} else {
?>

<?php _e('Background Image'); ?>

<?php _e('Preview'); ?>

<?php
$background_styles = '';
if ( $bgcolor = get_background_color() )
	$background_styles .= 'background-color: #' . $bgcolor . ';';

if ( get_background_image() ) {
	// background-image URL must be single quote, see below
	$background_styles .= ' background-image: url(\'' . get_theme_mod('background_image_thumb', '') . '\');'
		. ' background-repeat: ' . get_theme_mod('background_repeat', 'repeat') . ';'
		. ' background-position: top ' . get_theme_mod('background_position_x', 'left');
}
?>
<div id="custom-background-image" style="<?php echo $background_styles; ?>"><?php // must be double quote, see above ?>
<?php if ( get_background_image() ) { ?>
<img class="custom-background-image" src="<?php echo get_theme_mod('background_image_thumb', ''); ?>" style="visibility:hidden;" alt="" />

<img class="custom-background-image" src="<?php echo get_theme_mod('background_image_thumb', ''); ?>" style="visibility:hidden;" alt="" />
<?php } ?>

<?php } ?>

<?php if ( get_background_image() ) : ?>

<?php _e('Remove Image'); ?>

<form method="post" action="">
<?php wp_nonce_field('custom-background-remove', '_wpnonce-custom-background-remove'); ?>
<input type="submit" class="button" name="remove-background" value="<?php esc_attr_e('Remove Background Image'); ?>" />

<?php _e('This will remove the background image. You will not be able to restore any customizations.') ?>
</form>

<?php endif; ?>

<?php if ( defined( 'BACKGROUND_IMAGE' ) ) : // Show only if a default background image exists ?>

<?php _e('Restore Original Image'); ?>

<form method="post" action="">
<?php wp_nonce_field('custom-background-reset', '_wpnonce-custom-background-reset'); ?>
<input type="submit" class="button" name="reset-background" value="<?php esc_attr_e('Restore Original Image'); ?>" />

<?php _e('This will restore the original background image. You will not be able to restore any customizations.') ?>
</form>

<?php endif; ?>

<?php _e('Upload Image'); ?>
<form enctype="multipart/form-data" id="upload-form" method="post" action="">
<?php _e('Choose an image from your computer:'); ?>
<input type="file" id="upload" name="import" />
<input type="hidden" name="action" value="save" />
<?php wp_nonce_field('custom-background-upload', '_wpnonce-custom-background-upload') ?>
<input type="submit" class="button" value="<?php esc_attr_e('Upload'); ?>" />

</form>

<?php _e('Display Options') ?>

<form method="post" action="">

<?php if ( get_background_image() ) : ?>

<?php _e( 'Position' ); ?>
<fieldset><legend class="screen-reader-text"><?php _e( 'Background Position' ); ?></legend>

<input name="background-position-x" type="radio" value="left"<?php checked('left', get_theme_mod('background_position_x', 'left')); ?> />
<?php _e('Left') ?>

<input name="background-position-x" type="radio" value="center"<?php checked('center', get_theme_mod('background_position_x', 'left')); ?> />
<?php _e('Center') ?>

<input name="background-position-x" type="radio" value="right"<?php checked('right', get_theme_mod('background_position_x', 'left')); ?> />
<?php _e('Right') ?>

</fieldset>

<?php _e( 'Repeat' ); ?>
<fieldset><legend class="screen-reader-text"><?php _e( 'Background Repeat' ); ?></legend>
<input type="radio" name="background-repeat" value="no-repeat"<?php checked('no-repeat', get_theme_mod('background_repeat', 'repeat')); ?>> <?php _e('No Repeat'); ?></option>
	<input type="radio" name="background-repeat" value="repeat"<?php checked('repeat', get_theme_mod('background_repeat', 'repeat')); ?>> <?php _e('Tile'); ?></option>
	<input type="radio" name="background-repeat" value="repeat-x"<?php checked('repeat-x', get_theme_mod('background_repeat', 'repeat')); ?>> <?php _e('Tile Horizontally'); ?></option>
	<input type="radio" name="background-repeat" value="repeat-y"<?php checked('repeat-y', get_theme_mod('background_repeat', 'repeat')); ?>> <?php _e('Tile Vertically'); ?></option>
</fieldset>

<?php _e( 'Attachment' ); ?>
<fieldset><legend class="screen-reader-text"><?php _e( 'Background Attachment' ); ?></legend>

<input name="background-attachment" type="radio" value="scroll" <?php checked('scroll', get_theme_mod('background_attachment', 'scroll')); ?> />
<?php _e('Scroll') ?>

<input name="background-attachment" type="radio" value="fixed" <?php checked('fixed', get_theme_mod('background_attachment', 'scroll')); ?> />
<?php _e('Fixed') ?>

</fieldset>

<?php endif; // get_background_image() ?>

<?php _e( 'Color' ); ?>
<fieldset><legend class="screen-reader-text"><?php _e( 'Background Color' ); ?></legend>
<input type="text" name="background-color" id="background-color" value="#<?php echo esc_attr(get_background_color()) ?>" />
<?php _e('Select a Color'); ?>

</fieldset>

<?php wp_nonce_field('custom-background'); ?>

<input type="submit" class="button-primary" name="save-background-options" value="<?php esc_attr_e('Save Changes'); ?>" />

</form>

<?php
	}

	/**
	 * Handle a Image upload for the background image.
	 *
	 * @since 3.0.0
	 */
	function handle_upload() {

		if ( empty($_FILES) )
			return;

		check_admin_referer('custom-background-upload', '_wpnonce-custom-background-upload');
		$overrides = array('test_form' => false);
		$file = wp_handle_upload($_FILES['import'], $overrides);

		if ( isset($file['error']) )
			wp_die( $file['error'] );

		$url = $file['url'];
		$type = $file['type'];
		$file = $file['file'];
		$filename = basename($file);

		// Construct the object array
		$object = array(
			'post_title' => $filename,
			'post_content' => $url,
			'post_mime_type' => $type,
			'guid' => $url
		);

		// Save the data
		$id = wp_insert_attachment($object, $file);

		// Add the meta-data
		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );

		set_theme_mod('background_image', esc_url($url));

		$thumbnail = wp_get_attachment_image_src( $id, 'thumbnail' );
		set_theme_mod('background_image_thumb', esc_url( $thumbnail[0] ) );

		do_action('wp_create_file_in_uploads', $file, $id); // For replication
		$this->updated = true;
	}

}
?>


text:
Wlpp for Muzei (WlppforMuzei)
========

[Wlppr.com](http://wlppr.com) art source for [Muzei](https://play.google.com/store/apps/details?id=net.nurik.roman.muzei) that displays a random wallpaper every day.
All wallpapers are provided by the wlppr.com. They can be shared and downloaded directly from Muzei app.

**[Now available on Google Play](https://play.google.com/store/apps/details?id=com.zenstyle.muzei.wlppr)**

Author
=======

Thomas Bouron - [tbouron@gmail.com](mailto:tbouron@gmail.com) - [Google+](https://plus.google.com/u/0/104567775398355774153/posts)

License
=======

    Copyright 2014 Thomas Bouron.

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

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

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


text:
@class YR_SearchArticleListModel,YR_SearchArticleUserModel;

@interface YR_SearchArticleModel : YR_BaseModel

@property (nonatomic, strong) NSNumber *code;

@property (nonatomic, strong) NSArray<YR_SearchArticleListModel *> *list;

@property (nonatomic, strong) NSNumber *last_id;

@property (nonatomic, copy) NSString *q;

@end


text:
caro
====

Caro game with nodejs