text:
declare module Moosetrail {
    class Module {
        app: ng.IModule;
        constructor(name: string, modules: Array<string>);
        addController(name: string, controller: Function): void;
        addDirective(name: string, directive: ng.IDirectiveFactory): void;
        addService(name: string, service: Function): void;
    }
}
declare module Moosetrail.Core.Authentication {
    class Authenticator {
        authData: Authentication.TokenAuthorization;
        http: DataAccess.HttpDataFactory;
        q: ng.IQService;
        localStroage: ng.local.storage.ILocalStorageService;
        static $inject: string[];
        constructor($q: ng.IQService, localStorage: ng.local.storage.ILocalStorageService, factory: DataAccess.HttpDataFactory);
        private clearAuthData();
        login(username: string, password: string): ng.IPromise<DataAccess.DataResult>;
        private setAuthentication(username, result, def);
        private setAuthData(authData);
        private handleFailedLogin(reason, def);
        logout(): void;
        setPremision(roles: UserRole[]): void;
        fillAuthData(): UserCredentials;
        hasAuthorizationFor(role: UserRole): boolean;
    }
}
declare module Moosetrail.Core.Authentication {
    class AuthenticatorInterceptor {
        private localStorage;
        private $q;
        static $inject: string[];
        constructor($q: ng.IQService, localStorage: ng.local.storage.ILocalStorageService);
        request: (config: any) => any;
        responseError: (rejection: any) => ng.IPromise<any>;
    }
}
declare module Moosetrail.Core.Authentication {
    class TokenAuthorization implements UserCredentials {
        isAuthenticated: boolean;
        username: string;
        token: string;
        password: string;
        roles: UserRole[];
        constructor(username: string, token: string);
        setRoles(roles: UserRole[]): void;
        private cleanUpRoles();
    }
}
declare module Moosetrail.Core.Authentication {
    interface UserCredentials {
        isAuthenticated: boolean;
        username: string;
        password: string;
        roles: UserRole[];
    }
}
declare module Moosetrail.Core.Authentication {
    enum UserRole {
        User = 0,
        Admin = 1,
    }
}
declare module Moosetrail.Core {
    interface IConfig {
        apiUrl: string;
    }
}
declare module Moosetrail.Core.DataAccess {
    class CombinedDataFactory {
        protected q: angular.IQService;
        private httpFactory;
        private localFactory;
        constructor(localFactory: LocalDataFactory, httpFactory: HttpDataFactory, $q: ng.IQService);
        protected getData(getLocal: Function, getHttp: Function): ng.IPromise<DataResult>;
    }
}
declare module Moosetrail.Core.DataAccess {
    class DataResult {
        data: any;
        httpResponse: HttpResponse;
        source: DataSource;
        constructor(data: any, code: number, source: DataSource);
    }
}
declare module Moosetrail.Core.DataAccess {
    enum DataSource {
        LocalStorage = 0,
        Http = 1,
    }
}
declare module Moosetrail.Core.DataAccess {
    class HttpDataFactory {
        http: ng.IHttpService;
        q: ng.IQService;
        private baseUrl;
        static $inject: string[];
        constructor($http: ng.IHttpService, $q: ng.IQService, config: IConfig);
        getData(url: string): ng.IPromise<DataResult>;
        getWithParams(url: string, params: any): ng.IPromise<DataResult>;
        getWithData(url: string, data: any): ng.IPromise<DataResult>;
        post(url: string, sendData: any): ng.IPromise<DataResult>;
        postWithHeader(url: string, sendData: any, headers: any): ng.IPromise<DataResult>;
        postWithParams(url: string, sendData: any, params: any): ng.IPromise<DataResult>;
        postWithParamsWithoutData(url: string, params: any): ng.IPromise<DataResult>;
        put(url: string, sendData: any): ng.IPromise<DataResult>;
        putWithParams(url: string, params: any, data: any): ng.IPromise<DataResult>;
        deleteData(url: string): ng.IPromise<DataResult>;
        private createUrl(url);
        protected encodeUrl(url: string): string;
    }
}
declare module Moosetrail.Core.DataAccess {
    class HttpResponse {
        code: number;
        constructor(code: number);
    }
}
declare module Moosetrail.Core.DataAccess {
    class LocalDataFactory {
        private prefix;
        protected q: ng.IQService;
        private localStorage;
        static $inject: string[];
        constructor($q: ng.IQService, local: angular.local.storage.ILocalStorageService);
        protected getDataWithKey(key: string): ng.IPromise<DataResult>;
        protected setDataWithKey(key: string, data: any): void;
        protected getPlainData(identifier: string): any;
    }
}
declare module Moosetrail.Core.Design {
    class Layout {
        isPhone: boolean;
        isTablet: boolean;
        isDesktop: boolean;
        width: number;
        static $inject: string[];
        constructor(window: ng.IWindowService);
        private calculateViewType();
        static create(width: number): Layout;
    }
}
declare module Moosetrail.Core.Design {
    class ResponsiveImageCtrl {
        private layoutData;
        src: string;
        alt: string;
        class: string;
        dimensions: string;
        width: string;
        height: string;
        static $inject: string[];
        constructor(scope: ResponsiveImageScope, layout: Layout);
        private setSource(scope);
        private setDimensions();
        private setDynamicDimensions(scope);
    }
}
declare module Moosetrail.Core.Design {
    function responsiveImageDirective(): ng.IDirective;
}
declare module Moosetrail.Core.Design {
    interface ResponsiveImageScope extends ng.IScope {
        src: string;
        phoneSrc: string;
        tabletSrc: string;
        desktopSrc: string;
        alt: string;
        imgClass: string;
        width: number;
        height: number;
        phoneWidth: number;
        tabletWidth: number;
        desktopWidth: number;
        phoneHeight: number;
        tabletHeight: number;
        desktopHeight: number;
    }
}
declare module Moosetrail.Core.Mathematics {
    class RandomGenerator {
        getRandomInt(min: any, max: any): number;
    }
}
declare module Moosetrail.Core.Authentication {
}
declare module Moosetrail.Core.DataAccess {
}
declare module Moosetrail.Core.Design {
}
declare module Moosetrail.Core.Mathematics {
}
declare module Moosetrail.Core {
}


text:
package de.altimos.util.res.basic.locators;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import de.altimos.util.res.ResourceKey;
import de.altimos.util.res.basic.AbstractResourceInfo;
import de.altimos.util.res.basic.BasicResourceManager;

/**
 *
 * @author Jan Graichen
 * @version $Id$
 */
public class ZipResourceInfo extends AbstractResourceInfo {

	private ZipFile archive;
	private ZipEntry ze;

	public ZipResourceInfo(BasicResourceManager mgr, ResourceKey key, ZipFile archive, ZipEntry ze) {
		super(mgr, key);
		this.archive = archive;
		this.ze = ze;
	}

	@Override
	public InputStream openStream() throws IOException {
		return archive.getInputStream(ze);
	}
}

redpajama_set_name: RedPajamaGithub


text:
using Xunit;

namespace System.Runtime.InteropServices.Tests
{
    public class AutomationProxyAttributeTests
    {
        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void Ctor_Val(bool val)
        {
            var attribute = new AutomationProxyAttribute(val);
            Assert.Equal(val, attribute.Value);
        }
    }
}


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

<TITLE>
All Classes (classes)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

ColorChooser

DigitalPicture

FileChooser

ImageDisplay

IntArrayWorker

IntArrayWorkerTester

Picture

PictureExplorer

PictureFrame

PictureTester

Pixel

SimplePicture


text:
from django.core.urlresolvers import reverse
from django import http
from django.template.defaultfilters import filesizeformat  # noqa
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables  # noqa

from horizon import exceptions
from horizon import forms
from horizon import messages

from gbpui import client

PROTOCOLS = [('tcp', _('TCP')),
             ('udp', _('UDP')),
             ('icmp', _('ICMP')),
             ('http', _('HTTP')),
             ('https', _('HTTPS')),
             ('smtp', _('SMTP')),
             ('dns', _('DNS')),
             ('ftp', _('FTP')),
             ('any', _('ANY'))
             ]
DIRECTIONS = [('in', _('IN')),
              ('out', _('OUT')),
              ('bi', _('BI'))]
POLICY_ACTION_TYPES = [('allow', _('ALLOW')),
                       ('redirect', _('REDIRECT')),
                       ('copy', _('COPY')),
                       ('log', _('LOG')),
                       ('qos', _('QoS'))]

class UpdatePolicyRuleSetForm(forms.SelfHandlingForm):
    name = forms.CharField(label=_("Name"))
    description = forms.CharField(label=_("Description"), required=False)
    rules = forms.MultipleChoiceField(label=_("Policy Rules"),)
    shared = forms.BooleanField(label=_("Shared"), required=False)

    def __init__(self, request, *args, **kwargs):
        super(UpdatePolicyRuleSetForm, self).__init__(request, *args, **kwargs)
        rules = []
        try:
            items = client.policyrule_list(request)
            rules = [(p.id, p.name) for p in items]
            policy_rule_set = client.policy_rule_set_get(
                request, self.initial['policy_rule_set_id'])
            if policy_rule_set:
                self.fields['name'].initial = policy_rule_set.name
                self.fields[
                    'description'].initial = policy_rule_set.description
                self.fields['shared'].initial = policy_rule_set.shared
                existing = [item for item in policy_rule_set.policy_rules]
                self.fields['rules'].initial = existing
        except Exception:
            exceptions.handle(request, _('Unable to retrieve policy rules'))
        self.fields['rules'].choices = rules

    def handle(self, request, context):
        try:
            policy_rule_set_id = self.initial['policy_rule_set_id']
            client.policy_rule_set_update(request,
                                          policy_rule_set_id,
                                          name=context['name'],
                                          description=context[
                                              'description'],
                                          policy_rules=context['rules'],
                                          shared=context['shared'],
                                          )
            messages.success(request, _('PolicyRuleSet successfully updated.'))
            url = reverse('horizon:project:application_policy:index')
            return http.HttpResponseRedirect(url)
        except Exception:
            redirect = reverse('horizon:project:policy_rule_sets:index')
            exceptions.handle(
                request, _("Unable to update policy_rule_set."),
                redirect=redirect)

class AddPolicyActionForm(forms.SelfHandlingForm):
    name = forms.CharField(label=_("Name"))
    description = forms.CharField(label=_("Description"),
                                  required=False)
    action_type = forms.ChoiceField(label=_("Action"),
                                    choices=POLICY_ACTION_TYPES,
                                    widget=forms.Select(attrs={
                                        'class': 'switchable',
                                        'data-slug': 'source'
                                    }))
    action_value = forms.ChoiceField(label=_("Service Chain Spec"),
                                     required=False,
                                     choices=[],
                                     widget=forms.Select(attrs={
                                         'class': 'switched',
                                         'data-switch-on': 'source',
                                         'data-source-redirect':
                                         _('Service Chain Spec')
                                     }))
    shared = forms.BooleanField(label=_("Shared"),
                                initial=False, required=False)

    def __init__(self, request, *args, **kwargs):
        super(AddPolicyActionForm, self).__init__(request, *args, **kwargs)
        url = reverse('horizon:project:application_policy:index')
        try:
            sc_specs = client.servicechainspec_list(request)
            self.fields['action_value'].choices = \
                [(spec.id,
                  (spec.name if spec.name is not None else "") + ":" + spec.id)
                 for spec in sc_specs]
        except Exception:
            exceptions.handle(
                request, _("Unable to retrieve action values."), redirect=url)

    def handle(self, request, context):
        url = reverse('horizon:project:application_policy:index')
        try:
            if not context['action_value']:
                del context['action_value']
            action = client.policyaction_create(request, **context)
            messages.success(request, _('Policy Action successfully created.'))
            return action
        except Exception:
            exceptions.handle(
                request, _("Unable to create policy action."), redirect=url)

class UpdatePolicyActionForm(forms.SelfHandlingForm):
    name = forms.CharField(label=_("Name"))
    description = forms.CharField(label=_("Description"),
                                  required=False)
    shared = forms.BooleanField(label=_("Shared"), required=False)

    def __init__(self, request, *args, **kwargs):
        super(UpdatePolicyActionForm, self).__init__(request, *args, **kwargs)

        try:
            policyaction_id = self.initial['policyaction_id']
            pa = client.policyaction_get(request, policyaction_id)
            self.fields['name'].initial = pa.name
            self.fields['description'].initial = pa.description
            self.fields['shared'].initial = pa.shared
        except Exception:
            pass

    def handle(self, request, context):
        url = reverse('horizon:project:application_policy:index')
        try:
            policyaction_id = self.initial['policyaction_id']
            client.policyaction_update(request, policyaction_id, **context)
            messages.success(request, _('Policy Action successfully updated.'))
            return http.HttpResponseRedirect(url)
        except Exception:
            exceptions.handle(
                request, _("Unable to update policy action."), redirect=url)

class AddPolicyClassifierForm(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"), required=False)
    protocol = forms.ChoiceField(label=_("Protocol"), choices=PROTOCOLS,
                widget=forms.Select(attrs={'class': 'switchable',
                                           'data-slug': 'source'}))
    port_range = forms.CharField(max_length=80, label=_("Port/Range(min:max)"),
                    required=False,
                    widget=forms.TextInput(attrs={'class': 'switched',
                                'data-switch-on': 'source',
                                'data-source-tcp': _("Port/Range(min:max)"),
                                'data-source-udp': _("Port/Range(min:max)"),
                                'data-source-http': _("Port/Range(min:max)"),
                                'data-source-https': _("Port/Range(min:max)"),
                                'data-source-smtp': _("Port/Range(min:max)"),
                                'data-source-dns': _("Port/Range(min:max)"),
                                'data-source-ftp': _("Port/Range(min:max)"),
                                'data-source-any': _("Port/Range(min:max)")}))
    direction = forms.ChoiceField(label=_("Direction"),
        choices=[('in', _('IN')),
                 ('out', _('OUT')),
                 ('bi', _('BI'))])
    shared = forms.BooleanField(label=_("Shared"),
                                initial=False, required=False)

    def __init__(self, request, *args, **kwargs):
        super(AddPolicyClassifierForm, self).__init__(request, *args, **kwargs)

    def handle(self, request, context):
        url = reverse('horizon:project:application_policy:index')
        try:
            if not bool(context['port_range']):
                context['port_range'] = None
            classifier = client.policyclassifier_create(request, **context)
            messages.success(
                request, _('Policy Classifier successfully created.'))
            return classifier
        except Exception:
            exceptions.handle(
                request, _("Unable to create policy classifier."),
                redirect=url)

class UpdatePolicyClassifierForm(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"), required=False)
    description = forms.CharField(label=_("Description"), required=False)
    protocol = forms.ChoiceField(label=_("Protocol"), choices=PROTOCOLS)
    port_range = forms.CharField(max_length=80, label=_("Port/Range(min:max)"),
            required=False)
    direction = forms.ChoiceField(label=_("Direction"), choices=DIRECTIONS)
    shared = forms.BooleanField(label=_("Shared"), required=False)

    def __init__(self, request, *args, **kwargs):
        super(UpdatePolicyClassifierForm, self).__init__(
            request, *args, **kwargs)
        try:
            policyclassifier_id = self.initial['policyclassifier_id']
            classifier = client.policyclassifier_get(
                request, policyclassifier_id)
            for item in ['name', 'description',
                         'protocol', 'port_range', 'direction', 'shared']:
                self.fields[item].initial = getattr(classifier, item)
        except Exception:
            exceptions.handle(
                request, _("Unable to retrive policy classifier details."))

    def handle(self, request, context):
        url = reverse('horizon:project:application_policy:index')
        try:
            policyclassifier_id = self.initial['policyclassifier_id']
            if not bool(context['port_range']):
                context['port_range'] = None
            client.policyclassifier_update(self.request,
                    policyclassifier_id, **context)
            messages.success(
                request, _('Policy classifier successfully updated.'))
            return http.HttpResponseRedirect(url)
        except Exception:
            exceptions.handle(
                request, _("Unable to update policy classifier."),
                redirect=url)

class UpdatePolicyRuleForm(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"), required=False)
    description = forms.CharField(label=_("Description"), required=False)
    policy_classifier_id = forms.ChoiceField(label=_("Policy Classifier"))
    policy_actions = forms.MultipleChoiceField(label=_("Policy Actions"))
    shared = forms.BooleanField(label=_("Shared"), required=False)

    def __init__(self, request, *args, **kwargs):
        super(UpdatePolicyRuleForm, self).__init__(request, *args, **kwargs)
        try:
            policyrule_id = self.initial['policyrule_id']
            rule = client.policyrule_get(request, policyrule_id)
            for item in ['name', 'description',
                         'policy_classifier_id', 'policy_actions', 'shared']:
                self.fields[item].initial = getattr(rule, item)
            actions = client.policyaction_list(request)
            action_list = [a.id for a in actions]
            for action in actions:
                action.set_id_as_name_if_empty()
            actions = sorted(actions, key=lambda action: action.name)
            action_list = [(a.id, a.name) for a in actions]
            self.fields['policy_actions'].choices = action_list
            classifiers = client.policyclassifier_list(request)
            classifier_list = [(c.id, c.name) for c in classifiers]
            self.fields['policy_classifier_id'].choices = classifier_list
        except Exception:
            exceptions.handle(
                request, _("Unable to retrive policy rule details."))

    def handle(self, request, context):
        url = reverse('horizon:project:application_policy:index')
        try:
            prid = self.initial['policyrule_id']
            client.policyrule_update(request, prid, **context)
            messages.success(request, _('Policy rule successfully updated.'))
            return http.HttpResponseRedirect(url)
        except Exception as e:
            msg = _("Unable to update policy rule. %s") % (str(e))
            exceptions.handle(request, msg, redirect=url)


text:
<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->

	<Resource name="jdbc/cas-db" auth="Container"
        type="javax.sql.DataSource"
        driverClassName="org.h2.Driver"
        url="jdbc:h2:mem:employee"
        username="sa" password=""
        maxActive="20" maxIdle="10" maxWait="-1"
        description="Datasource to user database"  />

</Context>


text:
using System;
using System.Text.RegularExpressions;

namespace CymaticLabs.InfluxDB.Data
{
    /// <summary>
    /// Static helper class for InfluxDB-related operations.
    /// </summary>
    public static class InfluxDbHelper
    {
        #region Fields

        //public const string

        /// <summary>
        /// The string units for seconds in InfluxDB.
        /// </summary>
        public const string SecondsUnit = "s";

        /// <summary>
        /// The string units for milliseconds in InfluxDB.
        /// </summary>
        public const string MillisecondsUnit = "ms";

        /// <summary>
        /// The string units for microseconds in InfluxDB.
        /// </summary>
        public const string MicrosecondsUnit = "u";

        /// <summary>
        /// Regex used to validate time interval strings: 1h, 15m, 30s, etc.
        /// </summary>
        public static readonly Regex IntervalRegex = new Regex("([0-9\\.]+)(.)");

        #endregion Fields

        #region Properties

        #endregion Properties

        #region Constructors

        #endregion Constructors

        #region Methods

        /// <summary>
        /// Determine whether or not an InfluxDB time interval string is valid:
        /// "1h", "30m", "15s", etc.
        /// </summary>
        /// <param name="timeInterval">The time interval string to validate.</param>
        /// <returns>True if the string is a valid time interval, False if not.</returns>
        public static bool IsTimeIntervalValid(string timeInterval)
        {
            // Null string
            if (string.IsNullOrWhiteSpace(timeInterval)) return false;

            // Make sure the leading character is a number
            var fc = timeInterval[0];

            if (fc != '0' && fc != '1' && fc != '2' && fc != '3' && fc != '4' && fc != '5' && fc != '6' && fc != '7' && fc != '8' && fc != '9')
                return false;

            // Make sure the last character is a valid time unit character
            var lc = timeInterval[timeInterval.Length - 1];

            if (lc != 's' && lc != 'u' && lc != 'm' && lc != 'h' && lc != 'd' && lc != 'w')
                return false;

            // Otherwise parse with regex
            var matches = IntervalRegex.Match(timeInterval);

            // We should have just one match
            if (matches.Captures.Count != 1) return false;

            // We should have 3 groups: combined match, value match, units match ("10m", "10", "m")
            if (matches.Groups.Count != 3) return false;

            // Validate numeric value
            var rawValue = matches.Groups[1].Value;

            // Attempt to parse the value
            uint value;
            if (!uint.TryParse(rawValue, out value)) return false;

            // Validate units
            var units = matches.Groups[2].Value;
            return ConvertTimeUnit(units) != InfluxDbTimeUnits.None;
        }

        /// <summary>
        /// Converts a string time unit ("s", "m", "h", "d", etc.) into a <see cref="InfluxDbTimeUnits"/> value.
        /// </summary>
        /// <param name="unit">The string unit to convert.</param>
        /// <param name="throwIfInvalid">Whether or not the method will throw an exception if an invalid unit value is provided.</param>
        /// <returns>The matching enumeration value.
        /// <see cref="InfluxDbTimeUnits.None"/> if an invalid value is supplied and 'throwIfInvalid' is false.</returns>
        public static InfluxDbTimeUnits ConvertTimeUnit(string unit, bool throwIfInvalid = false)
        {
            if (string.IsNullOrWhiteSpace(unit)) throw new ArgumentNullException("unit");

            switch (unit.ToLower())
            {
                case "u":
                    return InfluxDbTimeUnits.Microseconds;

                case "ms":
                    return InfluxDbTimeUnits.Milliseconds;

                case "s":
                    return InfluxDbTimeUnits.Seconds;

                case "m":
                    return InfluxDbTimeUnits.Minutes;

                case "h":
                    return InfluxDbTimeUnits.Hours;

                case "d":
                    return InfluxDbTimeUnits.Days;

                case "w":
                    return InfluxDbTimeUnits.Weeks;
            }

            // Throw if requested
            if (throwIfInvalid) throw new ArgumentException("invalid time unit string: " + unit);

            // Otherwise just return "None"
            return InfluxDbTimeUnits.None;
        }

        /// <summary>
        /// Converts a <see cref="InfluxDbTimeUnits"/> value into its matching InfluxDB time unit string:
        /// "m", "s", "h", "d", etc.
        /// </summary>
        /// <param name="unit"></param>
        /// <returns></returns>
        public static string ConvertTimeUnit(InfluxDbTimeUnits unit)
        {
            switch (unit)
            {
                case InfluxDbTimeUnits.Days:
                    return "d";

                case InfluxDbTimeUnits.Hours:
                    return "h";

                case InfluxDbTimeUnits.Microseconds:
                    return "u";

                case InfluxDbTimeUnits.Milliseconds:
                    return "ms";

                case InfluxDbTimeUnits.Minutes:
                    return "m";

                case InfluxDbTimeUnits.Seconds:
                    return "s";

                case InfluxDbTimeUnits.Weeks:
                    return "w";
            }

            throw new NotSupportedException("Unsupported time unit value: " + unit.ToString());
        }

        #endregion Methods
    }
}


text:
var gdal = require('../lib/gdal.js');

// gc tracing
try {
	gdal.startLogging(__dirname + '/artifacts/log.txt');
} catch (e) {
	/* ignore */
}

// seg fault handler
var SegfaultHandler;
try {
	SegfaultHandler = require('segfault-handler');
	SegfaultHandler.registerHandler();
} catch (err) {
	/* ignore */
}


text:
<?php

echo "Creature.php\n";
class Creature {

}


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

<title>AbstractOutput</title>
<meta name="date" content="2015-09-10">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

weka.classifiers.evaluation.output.prediction

Class AbstractOutput

java.lang.Object

weka.classifiers.evaluation.output.prediction.AbstractOutput

All Implemented Interfaces:

java.io.Serializable, OptionHandler

Direct Known Subclasses:

CSV, HTML, Null, PlainText, XML

public abstract class AbstractOutput
extends java.lang.Object
implements java.io.Serializable, OptionHandler

A superclass for outputting the classifications of a classifier.

 Basic use with a classifier and a test set:

 Classifier classifier = ... // trained classifier
 Instances testset = ... // the test set to output the predictions for
 StringBuffer buffer = ... // the string buffer to add the output to
 AbstractOutput output = new FunkyOutput();
 output.setHeader(...);
 output.printClassifications(classifier, testset);

 Basic use with a classifier and a data source:

 Classifier classifier = ... // trained classifier
 DataSource testset = ... // the data source to obtain the test set from to output the predictions for
 StringBuffer buffer = ... // the string buffer to add the output to
 AbstractOutput output = new FunkyOutput();
 output.setHeader(...);
 output.printClassifications(classifier, testset);

 In order to make the output generation easily integrate into GUI components,
 one can output the header, classifications and footer separately:

 Classifier classifier = ... // trained classifier
 Instances testset = ... // the test set to output the predictions for
 StringBuffer buffer = ... // the string buffer to add the output to
 AbstractOutput output = new FunkyOutput();
 output.setHeader(...);
 // print the header
 output.printHeader();
 // print the classifications one-by-one
 for (int i = 0; i < testset.numInstances(); i++) {
   output.printClassification(classifier, testset.instance(i), i);
   // output progress information
   if ((i+1) % 100 == 0)
     System.out.println((i+1) + "/" + testset.numInstances());
 }
 // print the footer
 output.printFooter();

Version:

$Revision: 11958 $

Author:

fracpete (fracpete at waikato dot ac dot nz)

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

AbstractOutput()

Initializes the output class.

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
attributesTipText()

Returns the tip text for this property.

static AbstractOutput
fromCommandline(java.lang.String cmdline)

Returns a fully configured object from the given commandline.

boolean
generatesOutput()

Returns whether regular output is generated or not.

java.lang.String
getAttributes()

Returns the range of attributes to output.

java.lang.StringBuffer
getBuffer()

Returns the current buffer.

int
getDefaultNumDecimals()

Returns the default number of digits to output after the decimal point.

abstract java.lang.String
getDisplay()

Returns a short display text, to be used in comboboxes.

Instances
getHeader()

Returns the header of the dataset.

int
getNumDecimals()

Returns the number of digits to output after the decimal point.

java.lang.String[]
getOptions()

Gets the current option settings for the OptionHandler.

boolean
getOutputDistribution()

Returns whether to output the class distribution as well.

java.io.File
getOutputFile()

Returns the output file to write to.

boolean
getSuppressOutput()

Returns whether to the regular output is suppressed in case the output is
 stored in a file.

abstract java.lang.String
globalInfo()

Returns a string describing the output generator.

java.util.Enumeration<Option>
listOptions()

Returns an enumeration of all the available options..

java.lang.String
numDecimalsTipText()

Returns the tip text for this property.

java.lang.String
outputDistributionTipText()

Returns the tip text for this property.

java.lang.String
outputFileTipText()

Returns the tip text for this property.

void
print(Classifier classifier,
     ConverterUtils.DataSource testset)

Prints the header, classifications and footer to the buffer.

void
print(Classifier classifier,
     Instances testset)

Prints the header, classifications and footer to the buffer.

void
printClassification(Classifier classifier,
                   Instance inst,
                   int index)

Prints the classification to the buffer.

void
printClassification(double[] dist,
                   Instance inst,
                   int index)

Prints the classification to the buffer.

void
printClassifications(Classifier classifier,
                    ConverterUtils.DataSource testset)

Prints the classifications to the buffer.

void
printClassifications(Classifier classifier,
                    Instances testset)

Prints the classifications to the buffer.

void
printFooter()

Prints the footer to the buffer.

void
printHeader()

Prints the header to the buffer.

void
setAttributes(java.lang.String value)

Sets the range of attributes to output.

void
setBuffer(java.lang.StringBuffer value)

Sets the buffer to use.

void
setHeader(Instances value)

Sets the header of the dataset.

void
setNumDecimals(int value)

Sets the number of digits to output after the decimal point.

void
setOptions(java.lang.String[] options)

Sets the OptionHandler's options using the given list.

void
setOutputDistribution(boolean value)

Sets whether to output the class distribution or not.

void
setOutputFile(java.io.File value)

Sets the output file to write to.

void
setSuppressOutput(boolean value)

Sets whether to the regular output is suppressed in case the output is
 stored in a file.

java.lang.String
suppressOutputTipText()

Returns the tip text for this property.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AbstractOutput

public AbstractOutput()

Initializes the output class.

Method Detail

globalInfo

public abstract java.lang.String globalInfo()

Returns a string describing the output generator.

Returns:

a description suitable for displaying in the GUI

getDisplay

public abstract java.lang.String getDisplay()

Returns a short display text, to be used in comboboxes.

Returns:

a short display text

listOptions

public java.util.Enumeration<Option> listOptions()

Returns an enumeration of all the available options..

Specified by:

listOptions in interface OptionHandler

Returns:

an enumeration of all available options.

setOptions

public void setOptions(java.lang.String[] options)
                throws java.lang.Exception

Sets the OptionHandler's options using the given list. All options will be
 set (or reset) during this call (i.e. incremental setting of options is not
 possible).

Specified by:

setOptions in interface OptionHandler

Parameters:

options - the list of options as an array of strings

Throws:

java.lang.Exception - if an option is not supported

getOptions

public java.lang.String[] getOptions()

Gets the current option settings for the OptionHandler.

Specified by:

getOptions in interface OptionHandler

Returns:

the list of current option settings as an array of strings

setHeader

public void setHeader(Instances value)

Sets the header of the dataset.

Parameters:

value - the header

getHeader

public Instances getHeader()

Returns the header of the dataset.

Returns:

the header

setBuffer

public void setBuffer(java.lang.StringBuffer value)

Sets the buffer to use.

Parameters:

value - the buffer

getBuffer

public java.lang.StringBuffer getBuffer()

Returns the current buffer.

Returns:

the buffer, can be null

setAttributes

public void setAttributes(java.lang.String value)

Sets the range of attributes to output.

Parameters:

value - the range

getAttributes

public java.lang.String getAttributes()

Returns the range of attributes to output.

Returns:

the range

attributesTipText

public java.lang.String attributesTipText()

Returns the tip text for this property.

Returns:

tip text for this property suitable for displaying in the GUI

setOutputDistribution

public void setOutputDistribution(boolean value)

Sets whether to output the class distribution or not.

Parameters:

value - true if the class distribution is to be output as well

getOutputDistribution

public boolean getOutputDistribution()

Returns whether to output the class distribution as well.

Returns:

true if the class distribution is output as well

outputDistributionTipText

public java.lang.String outputDistributionTipText()

Returns the tip text for this property.

Returns:

tip text for this property suitable for displaying in the GUI

getDefaultNumDecimals

public int getDefaultNumDecimals()

Returns the default number of digits to output after the decimal point.

Returns:

the default number of digits

setNumDecimals

public void setNumDecimals(int value)

Sets the number of digits to output after the decimal point.

Parameters:

value - the number of digits

getNumDecimals

public int getNumDecimals()

Returns the number of digits to output after the decimal point.

Returns:

the number of digits

numDecimalsTipText

public java.lang.String numDecimalsTipText()

Returns the tip text for this property.

Returns:

tip text for this property suitable for displaying in the GUI

setOutputFile

public void setOutputFile(java.io.File value)

Sets the output file to write to. A directory disables this feature.

Parameters:

value - the file to write to or a directory

getOutputFile

public java.io.File getOutputFile()

Returns the output file to write to. A directory if turned off.

Returns:

the file to write to or a directory

outputFileTipText

public java.lang.String outputFileTipText()

Returns the tip text for this property.

Returns:

tip text for this property suitable for displaying in the GUI

setSuppressOutput

public void setSuppressOutput(boolean value)

Sets whether to the regular output is suppressed in case the output is
 stored in a file.

Parameters:

value - true if the regular output is to be suppressed

getSuppressOutput

public boolean getSuppressOutput()

Returns whether to the regular output is suppressed in case the output is
 stored in a file.

Returns:

true if the regular output is to be suppressed

suppressOutputTipText

public java.lang.String suppressOutputTipText()

Returns the tip text for this property.

Returns:

tip text for this property suitable for displaying in the GUI

generatesOutput

public boolean generatesOutput()

Returns whether regular output is generated or not.

Returns:

true if regular output is generated

printHeader

public void printHeader()

Prints the header to the buffer.

printClassification

public void printClassification(Classifier classifier,
                       Instance inst,
                       int index)
                         throws java.lang.Exception

Prints the classification to the buffer.

Parameters:

classifier - the classifier to use for printing the classification

inst - the instance to print

index - the index of the instance

Throws:

java.lang.Exception - if check fails or error occurs during printing of
           classification

printClassification

public void printClassification(double[] dist,
                       Instance inst,
                       int index)
                         throws java.lang.Exception

Prints the classification to the buffer.

Parameters:

dist - the distribution from classifier for the supplied instance

inst - the instance to print

index - the index of the instance

Throws:

java.lang.Exception - if check fails or error occurs during printing of
           classification

printClassifications

public void printClassifications(Classifier classifier,
                        ConverterUtils.DataSource testset)
                          throws java.lang.Exception

Prints the classifications to the buffer.

Parameters:

classifier - the classifier to use for printing the classifications

testset - the data source to obtain the test instances from

Throws:

java.lang.Exception - if check fails or error occurs during printing of
           classifications

printClassifications

public void printClassifications(Classifier classifier,
                        Instances testset)
                          throws java.lang.Exception

Prints the classifications to the buffer.

Parameters:

classifier - the classifier to use for printing the classifications

testset - the test instances

Throws:

java.lang.Exception - if check fails or error occurs during printing of
           classifications

printFooter

public void printFooter()
                 throws java.lang.Exception

Prints the footer to the buffer. This will also store the generated output
 in a file if an output file was specified.

Throws:

java.lang.Exception - if check fails

print

public void print(Classifier classifier,
         ConverterUtils.DataSource testset)
           throws java.lang.Exception

Prints the header, classifications and footer to the buffer.

Parameters:

classifier - the classifier to use for printing the classifications

testset - the data source to obtain the test instances from

Throws:

java.lang.Exception - if check fails or error occurs during printing of
           classifications

print

public void print(Classifier classifier,
         Instances testset)
           throws java.lang.Exception

Prints the header, classifications and footer to the buffer.

Parameters:

classifier - the classifier to use for printing the classifications

testset - the test instances

Throws:

java.lang.Exception - if check fails or error occurs during printing of
           classifications

fromCommandline

public static AbstractOutput fromCommandline(java.lang.String cmdline)

Returns a fully configured object from the given commandline.

Parameters:

cmdline - the commandline to turn into an object

Returns:

the object or null in case of an error

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Fixtures\Tools;

class TestEntity
{
    public function getName()
    {
    }

    public function setName()
    {
    }

    public function addName()
    {
    }

    public function isName()
    {
    }

    public function setDefaultName()
    {
    }

    public function addSomeField()
    {
    }
}


text:
import '../../stylus/components/_speed-dial.styl'

import Toggleable from '../../mixins/toggleable'
import Positionable from '../../mixins/positionable'
import Transitionable from '../../mixins/transitionable'

import ClickOutside from '../../directives/click-outside'

/* @vue/component */
export default {
  name: 'v-speed-dial',

  directives: { ClickOutside },

  mixins: [Positionable, Toggleable, Transitionable],

  props: {
    direction: {
      type: String,
      default: 'top',
      validator: val => {
        return ['top', 'right', 'bottom', 'left'].includes(val)
      }
    },
    openOnHover: Boolean,
    transition: {
      type: String,
      default: 'scale-transition'
    }
  },

  computed: {
    classes () {
      return {
        'v-speed-dial': true,
        'v-speed-dial--top': this.top,
        'v-speed-dial--right': this.right,
        'v-speed-dial--bottom': this.bottom,
        'v-speed-dial--left': this.left,
        'v-speed-dial--absolute': this.absolute,
        'v-speed-dial--fixed': this.fixed,
        [`v-speed-dial--direction-${this.direction}`]: true
      }
    }
  },

  render (h) {
    let children = []
    const data = {
      'class': this.classes,
      directives: [{
        name: 'click-outside',
        value: () => (this.isActive = false)
      }],
      on: {
        click: () => (this.isActive = !this.isActive)
      }
    }

    if (this.openOnHover) {
      data.on.mouseenter = () => (this.isActive = true)
      data.on.mouseleave = () => (this.isActive = false)
    }

    if (this.isActive) {
      let btnCount = 0
      children = (this.$slots.default || []).map((b, i) => {
        if (b.tag && typeof b.componentOptions !== 'undefined' && b.componentOptions.Ctor.options.name === 'v-btn') {
          btnCount++
          return h('div', {
            style: {
              transitionDelay: btnCount * 0.05 + 's'
            },
            key: i
          }, [b])
        } else {
          b.key = i
          return b
        }
      })
    }

    const list = h('transition-group', {
      'class': 'v-speed-dial__list',
      props: {
        name: this.transition,
        mode: this.mode,
        origin: this.origin,
        tag: 'div'
      }
    }, children)

    return h('div', data, [this.$slots.activator, list])
  }
}


text:
class Pila(object):
	def __init__(self):
		self.items=[]

	def apilar(self, dato):
		self.items.append(dato)

	def desapilar(self):
		if self.esta_vacia():
			return None
		else:
			return self.items.pop()

	def esta_vacia(self):
		if len(self.items)==0:
			return True
		else:
			return False

class Cola(object):

	def __init__(self):
		self.items=[]

	def encolar(self,x):
		self.items.append(x)

	def esta_vacia(self):
		if len(self.items)==0:
			return True
		else:
			return False

	def desencolar(self):
		if self.esta_vacia():
			return None
		else:
			return self.items.pop(0)

def recepcion():
	cola1=Cola()
	print "Bienvenido"
	while True:
		print "1-Agregar Nuevo Paciente"
		print "2-Llamar al prox Paciente"
		print "3-Cantidad de pacientes"
		print "4-salir"
		x=raw_input(" ?")
		x=int(x)
		if x==1:
			paciente=raw_input("nombre del paciente? ")
			cola1.encolar(paciente)
		elif x==2:
			print cola1.desencolar()
		elif x==3:
			print len(cola1.items)
		elif x==4:
			break
		else:
			print "ingrese una opcion valida"

recepcion()


text:
cask 'gnucash' do
  version '2.6.13-1,a'
  sha256 '722182df86530337b98ff8876a1836b21ecaa5453646ad9e711b02592de1323b'

  # github.com/Gnucash/gnucash was verified as official when first introduced to the cask
  url "https://github.com/Gnucash/gnucash/releases/download/#{version.major_minor_patch}#{version.after_comma}/Gnucash-Intel-#{version.before_comma}.dmg"
  appcast 'https://github.com/Gnucash/gnucash/releases.atom',
          checkpoint: '186ebe2f93a3a6f6a1673d0f0e597e5eda375e881b10d0121938d8e0007ddbed'
  name 'GnuCash'
  homepage 'https://www.gnucash.org/'
  license :gpl

  app 'Gnucash.app'
  app 'FinanceQuote Update.app'

  zap delete: [
                '~/Library/Application Support/Gnucash',
                '~/Library/Preferences/org.gnucash.Gnucash.plist',
                '~/Library/Saved Application State/org.gnucash.Gnucash.savedState',
              ]
end


text:
<?xml version="1.0" ?>
<Testcase>
        <Details>
            <Name>tc_json_usage_1</Name>
            <Title>Testcase for browser functions with data only in the json file</Title>
            <ExpectedResults>PASS</ExpectedResults>
            <Category/>
            <Engineer>Sanika Kulkarni</Engineer>
            <Time/>
            <default_onError action = 'next'  />
            <InputDataFile>../../../data/selenium_func_tests/data_json_usage_1.xml</InputDataFile>
            <Datatype>Custom</Datatype>
            <Logsdir/>
            <Resultsdir/>
        </Details>
       <Requirements>
           <Requirement>requirement-001</Requirement>
           <Requirement>requirement-002</Requirement>
       </Requirements>
        <Steps>
			<step TS= '1' Driver='selenium_driver' Keyword='browser_launch' > <!-- Will launch or open a new browser in window -->
				<Arguments>
					<argument name="system_name" value="search_element"/>
				</Arguments>
			</step>
			<step TS= '2' Driver='selenium_driver' Keyword='browser_maximize' > <!-- Will maximize a browser window -->
				<Arguments>
					<argument name="system_name" value="search_element"/>
				</Arguments>
			</step>
			<step TS= '2' Driver='selenium_driver' Keyword='navigate_to_url' > <!-- Will maximize a browser window -->
				<Arguments>
					<argument name="system_name" value="search_element"/>
					<argument name="element_tag" value="next_tag"/>
				</Arguments>
			</step>
			<step TS= '3' Driver='selenium_driver' Keyword='set_window_size' > <!-- Will minimize a browser window -->
				<Arguments>
					<argument name="system_name" value="search_element"/>
					<argument name="element_tag" value="trial_tag"/>
				</Arguments>
			</step>
			<step TS= '4' Driver='selenium_driver' Keyword='set_window_position' > <!-- Will minimize a browser window -->
				<Arguments>
					<argument name="system_name" value="search_element"/>
					<argument name="element_tag" value="trial_tag"/>
				</Arguments>
			</step>
			<step TS= '5' Driver='selenium_driver' Keyword='browser_close' > <!-- Will minimize a browser window -->
				<Arguments>
					<argument name="system_name" value="search_element"/>
				</Arguments>
			</step>
		</Steps>
</Testcase>


text:
import 'babel-polyfill';
import React from 'react';
import expect from 'expect';
import sinon from 'sinon';
import { mount } from 'enzyme';
import { SigninPage } from '../../../src/components/auth/SigninPage';

describe('<SigninPage/>', () => {
  // create a spy function for signupAction
  const signinAction = sinon.spy();
  // spy on handleSubmit of SIgnup Page
  sinon.spy(SigninPage.prototype, 'handleSubmit');
  // spy on handleChange of SIgnup Page
  sinon.spy(SigninPage.prototype, 'handleChange');
  const props = {
    signinState: {},
    signinAction
  };
  const wrapper = mount(<SigninPage {...props} />);

  it('should check if all FormFields are defined', () => {
    expect(wrapper.find('FormField').at(0).props().name).toBe('username');
    expect(wrapper.find('FormField').at(1).props().name).toBe('password');
  });

  it('Should check that number of form fields is equal to 2',
    () => {
      expect(wrapper.find('FormField').length).toBe(2);
    });

  it('Should check that IndexHeader is defined',
    () => {
      expect(wrapper.find('IndexHeader').length).toBe(1);
    });

  it('Should check that IndexFooter is defined',
    () => {
      expect(wrapper.find('IndexFooter').length).toBe(1);
    });

  it('Should check that handleSubmit is called', () => {
    // trigger an event by Signup form
    wrapper.find('form').simulate('submit');
    // handleSubmit is called
    expect(SigninPage.prototype.handleSubmit.calledOnce).toBe(true);
  });

  it('Should check that there is login submit button', () => {
    const button = wrapper.find('button');
    expect(button.props().type).toEqual('submit');
    expect(button.text()).toEqual('Login now');
  });

  it('Should check that signinAction is called', () => {
    // trigger an event by Signup form
    wrapper.find('form').simulate('submit');
    // singinAction inside handleSubmit is called
    expect(signinAction.called).toBe(true);
  });

  it('Should check that ErrorComponent exists when error is thrown', () => {
    const signinState = {
      fails: 'invalid username'
    };
    wrapper.setProps({ signinState });
    // singinAction inside handleSubmit is called
    expect(wrapper.find('ErrorComponent').length).toBe(1);
  });
});


text:
package org.hisp.dhis.security.oidc.provider;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.hisp.dhis.external.conf.DhisConfigurationProvider;
import org.hisp.dhis.security.oidc.DhisOidcClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;

import com.google.common.collect.ImmutableList;

/**
 * @author Morten Svanæs <msvanaes@dhis2.org>
 */
public class GenericOidcProviderBuilder extends AbstractOidcProvider
{
    private GenericOidcProviderBuilder()
    {
        throw new IllegalStateException( "Utility class" );
    }

    public static DhisOidcClientRegistration build( Map<String, String> config,
        Map<String, Map<String, String>> externalClients )
    {
        Objects.requireNonNull( config, "DhisConfigurationProvider is missing!" );

        String providerId = config.get( PROVIDER_ID );
        String clientId = config.get( CLIENT_ID );
        String clientSecret = config.get( CLIENT_SECRET );

        if ( providerId.isEmpty() || clientId.isEmpty() )
        {
            return null;
        }

        if ( clientSecret.isEmpty() )
        {
            throw new IllegalArgumentException( providerId + " client secret is missing!" );
        }

        return DhisOidcClientRegistration.builder()
            .clientRegistration( buildClientRegistration( config, providerId, clientId, clientSecret ) )
            .mappingClaimKey( StringUtils.defaultIfEmpty( config.get( MAPPING_CLAIM ), DEFAULT_MAPPING_CLAIM ) )
            .loginIcon( StringUtils.defaultIfEmpty( config.get( LOGIN_IMAGE ), "" ) )
            .loginIconPadding( StringUtils.defaultIfEmpty( config.get( LOGIN_IMAGE_PADDING ), "0px 0px" ) )
            .loginText( StringUtils.defaultIfEmpty( config.get( DISPLAY_ALIAS ), providerId ) )
            .externalClients( externalClients )
            .build();
    }

    private static ClientRegistration buildClientRegistration( Map<String, String> config, String providerId,
        String clientId, String clientSecret )
    {
        ClientRegistration.Builder builder = ClientRegistration.withRegistrationId( providerId );
        builder.clientName( providerId );
        builder.clientId( clientId );
        builder.clientSecret( clientSecret );
        builder.clientAuthenticationMethod( ClientAuthenticationMethod.BASIC );
        builder.authorizationGrantType( AuthorizationGrantType.AUTHORIZATION_CODE );
        builder.authorizationUri( config.get( AUTHORIZATION_URI ) );
        builder.tokenUri( config.get( TOKEN_URI ) );
        builder.jwkSetUri( config.get( JWK_URI ) );
        builder.issuerUri( config.get( ISSUER_URI ) );
        builder.userInfoUri( config.get( USERINFO_URI ) );
        builder.redirectUri( StringUtils.defaultIfEmpty(
            config.get( REDIRECT_URL ),
            DEFAULT_REDIRECT_TEMPLATE_URL ) );
        builder.userInfoAuthenticationMethod( AuthenticationMethod.HEADER );
        builder.userNameAttributeName( IdTokenClaimNames.SUB );
        builder.scope( ImmutableList.<String> builder()
            .add( DEFAULT_SCOPE )
            .add( StringUtils.defaultIfEmpty( config.get( SCOPES ), "" ).split( " " ) ).build() );

        builder.providerConfigurationMetadata( parseMetaData( config ) );

        return builder.build();
    }

    private static Map<String, Object> parseMetaData( Map<String, String> config )
    {
        final Map<String, Object> metadata = new HashMap<>();

        metadata.put( EXTRA_REQUEST_PARAMETERS, getExtraRequestParameters( config ) );

        if ( DhisConfigurationProvider.isOn( config.get( ENABLE_LOGOUT ) ) )
        {
            metadata.put( END_SESSION_ENDPOINT,
                StringUtils.defaultIfEmpty( config.get( END_SESSION_ENDPOINT ), "" ) );
        }

        if ( DhisConfigurationProvider.isOn( config.get( ENABLE_PKCE ) ) )
        {
            metadata.put( ENABLE_PKCE, Boolean.TRUE.toString() );
        }

        return metadata;
    }

    /**
     * Extra req. params has to be in this form: acr_value 4, test_param five
     * (trailing (PARAM1_NAME VALUE1,PARAM2_NAME VALUE2...)
     *
     * @param config
     * @return
     */
    public static Map<String, String> getExtraRequestParameters( Map<String, String> config )
    {
        String params = StringUtils.defaultIfEmpty( config.get( EXTRA_REQUEST_PARAMETERS ), "" );

        return Arrays
            .stream( params.split( "," ) )
            .filter( s -> s.trim().split( "\\s+" ).length == 2 )
            .map( s -> Pair.of(
                s.trim().split( "\\s+" )[0],
                s.trim().split( "\\s+" )[1] ) )
            .collect( Collectors.toMap( Pair::getLeft, Pair::getRight ) );
    }
}


text:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Jasmine Spec Runner</title>

  <link rel="stylesheet" type="text/css" href=".grunt/grunt-contrib-jasmine/jasmine.css">

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

  <script src=".grunt/grunt-contrib-jasmine/phantom-polyfill.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/jasmine.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/jasmine-html.js"></script>

  <script src="spec/jasmine-jquery.js"></script>

  <script src="libs/jquery/jquery-1.10.1.js"></script>

  <script src="src/reddebox.js"></script>

  <script src="spec/javascripts/frame_Spec.js"></script>

  <script src="spec/javascripts/reddebox_Spec.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/reporter.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/jasmine-helper.js"></script>

</head>
<body>
</body>
</html>


text:
package cshared_test

import (
	"bytes"
	"debug/elf"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"testing"
	"unicode"
)

// C compiler with args (from $(go env CC) $(go env GOGCCFLAGS)).
var cc []string

// ".exe" on Windows.
var exeSuffix string

var GOOS, GOARCH, GOROOT string
var installdir, androiddir string
var libSuffix, libgoname string

func TestMain(m *testing.M) {
	os.Exit(testMain(m))
}

func testMain(m *testing.M) int {
	log.SetFlags(log.Lshortfile)
	flag.Parse()
	if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
		fmt.Printf("SKIP - short mode and $GO_BUILDER_NAME not set\n")
		os.Exit(0)
	}

	GOOS = goEnv("GOOS")
	GOARCH = goEnv("GOARCH")
	GOROOT = goEnv("GOROOT")

	if _, err := os.Stat(GOROOT); os.IsNotExist(err) {
		log.Fatalf("Unable able to find GOROOT at '%s'", GOROOT)
	}

	androiddir = fmt.Sprintf("/data/local/tmp/testcshared-%d", os.Getpid())
	if runtime.GOOS != GOOS && GOOS == "android" {
		args := append(adbCmd(), "exec-out", "mkdir", "-p", androiddir)
		cmd := exec.Command(args[0], args[1:]...)
		out, err := cmd.CombinedOutput()
		if err != nil {
			log.Fatalf("setupAndroid failed: %v\n%s\n", err, out)
		}
		defer cleanupAndroid()
	}

	cc = []string{goEnv("CC")}

	out := goEnv("GOGCCFLAGS")
	quote := '\000'
	start := 0
	lastSpace := true
	backslash := false
	s := string(out)
	for i, c := range s {
		if quote == '\000' && unicode.IsSpace(c) {
			if !lastSpace {
				cc = append(cc, s[start:i])
				lastSpace = true
			}
		} else {
			if lastSpace {
				start = i
				lastSpace = false
			}
			if quote == '\000' && !backslash && (c == '"' || c == '\'') {
				quote = c
				backslash = false
			} else if !backslash && quote == c {
				quote = '\000'
			} else if (quote == '\000' || quote == '"') && !backslash && c == '\\' {
				backslash = true
			} else {
				backslash = false
			}
		}
	}
	if !lastSpace {
		cc = append(cc, s[start:])
	}

	switch GOOS {
	case "darwin":
		// For Darwin/ARM.
		// TODO(crawshaw): can we do better?
		cc = append(cc, []string{"-framework", "CoreFoundation", "-framework", "Foundation"}...)
	case "android":
		cc = append(cc, "-pie")
	}
	libgodir := GOOS + "_" + GOARCH
	switch GOOS {
	case "darwin":
		if GOARCH == "arm64" {
			libgodir += "_shared"
		}
	case "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris", "illumos":
		libgodir += "_shared"
	}
	cc = append(cc, "-I", filepath.Join("pkg", libgodir))

	if GOOS == "windows" {
		exeSuffix = ".exe"
	}

	// Copy testdata into GOPATH/src/testcshared, along with a go.mod file
	// declaring the same path.

	GOPATH, err := ioutil.TempDir("", "cshared_test")
	if err != nil {
		log.Panic(err)
	}
	defer os.RemoveAll(GOPATH)
	os.Setenv("GOPATH", GOPATH)

	modRoot := filepath.Join(GOPATH, "src", "testcshared")
	if err := overlayDir(modRoot, "testdata"); err != nil {
		log.Panic(err)
	}
	if err := os.Chdir(modRoot); err != nil {
		log.Panic(err)
	}
	os.Setenv("PWD", modRoot)
	if err := ioutil.WriteFile("go.mod", []byte("module testcshared\n"), 0666); err != nil {
		log.Panic(err)
	}

	// Directory where cgo headers and outputs will be installed.
	// The installation directory format varies depending on the platform.
	output, err := exec.Command("go", "list",
		"-buildmode=c-shared",
		"-installsuffix", "testcshared",
		"-f", "{{.Target}}",
		"./libgo").CombinedOutput()
	if err != nil {
		log.Panicf("go list failed: %v\n%s", err, output)
	}
	target := string(bytes.TrimSpace(output))
	libgoname = filepath.Base(target)
	installdir = filepath.Dir(target)
	libSuffix = strings.TrimPrefix(filepath.Ext(target), ".")

	return m.Run()
}

func goEnv(key string) string {
	out, err := exec.Command("go", "env", key).Output()
	if err != nil {
		log.Printf("go env %s failed:\n%s", key, err)
		log.Panicf("%s", err.(*exec.ExitError).Stderr)
	}
	return strings.TrimSpace(string(out))
}

func cmdToRun(name string) string {
	return "./" + name + exeSuffix
}

func adbCmd() []string {
	cmd := []string{"adb"}
	if flags := os.Getenv("GOANDROID_ADB_FLAGS"); flags != "" {
		cmd = append(cmd, strings.Split(flags, " ")...)
	}
	return cmd
}

func adbPush(t *testing.T, filename string) {
	if runtime.GOOS == GOOS || GOOS != "android" {
		return
	}
	args := append(adbCmd(), "push", filename, fmt.Sprintf("%s/%s", androiddir, filename))
	cmd := exec.Command(args[0], args[1:]...)
	if out, err := cmd.CombinedOutput(); err != nil {
		t.Fatalf("adb command failed: %v\n%s\n", err, out)
	}
}

func adbRun(t *testing.T, env []string, adbargs ...string) string {
	if GOOS != "android" {
		t.Fatalf("trying to run adb command when operating system is not android.")
	}
	args := append(adbCmd(), "exec-out")
	// Propagate LD_LIBRARY_PATH to the adb shell invocation.
	for _, e := range env {
		if strings.Index(e, "LD_LIBRARY_PATH=") != -1 {
			adbargs = append([]string{e}, adbargs...)
			break
		}
	}
	shellcmd := fmt.Sprintf("cd %s; %s", androiddir, strings.Join(adbargs, " "))
	args = append(args, shellcmd)
	cmd := exec.Command(args[0], args[1:]...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("adb command failed: %v\n%s\n", err, out)
	}
	return strings.Replace(string(out), "\r", "", -1)
}

func run(t *testing.T, extraEnv []string, args ...string) string {
	t.Helper()
	cmd := exec.Command(args[0], args[1:]...)
	if len(extraEnv) > 0 {
		cmd.Env = append(os.Environ(), extraEnv...)
	}

	if GOOS != "windows" {
		// TestUnexportedSymbols relies on file descriptor 30
		// being closed when the program starts, so enforce
		// that in all cases. (The first three descriptors are
		// stdin/stdout/stderr, so we just need to make sure
		// that cmd.ExtraFiles[27] exists and is nil.)
		cmd.ExtraFiles = make([]*os.File, 28)
	}

	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("command failed: %v\n%v\n%s\n", args, err, out)
	} else {
		t.Logf("run: %v", args)
	}
	return string(out)
}

func runExe(t *testing.T, extraEnv []string, args ...string) string {
	t.Helper()
	if runtime.GOOS != GOOS && GOOS == "android" {
		return adbRun(t, append(os.Environ(), extraEnv...), args...)
	}
	return run(t, extraEnv, args...)
}

func runCC(t *testing.T, args ...string) string {
	t.Helper()
	// This function is run in parallel, so append to a copy of cc
	// rather than cc itself.
	return run(t, nil, append(append([]string(nil), cc...), args...)...)
}

func createHeaders() error {
	// The 'cgo' command generates a number of additional artifacts,
	// but we're only interested in the header.
	// Shunt the rest of the outputs to a temporary directory.
	objDir, err := ioutil.TempDir("", "testcshared_obj")
	if err != nil {
		return err
	}
	defer os.RemoveAll(objDir)

	// Generate a C header file for p, which is a non-main dependency
	// of main package libgo.
	//
	// TODO(golang.org/issue/35715): This should be simpler.
	args := []string{"go", "tool", "cgo",
		"-objdir", objDir,
		"-exportheader", "p.h",
		filepath.Join(".", "p", "p.go")}
	cmd := exec.Command(args[0], args[1:]...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("command failed: %v\n%v\n%s\n", args, err, out)
	}

	// Generate a C header file for libgo itself.
	args = []string{"go", "install", "-buildmode=c-shared",
		"-installsuffix", "testcshared", "./libgo"}
	cmd = exec.Command(args[0], args[1:]...)
	out, err = cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("command failed: %v\n%v\n%s\n", args, err, out)
	}

	args = []string{"go", "build", "-buildmode=c-shared",
		"-installsuffix", "testcshared",
		"-o", libgoname,
		filepath.Join(".", "libgo", "libgo.go")}
	cmd = exec.Command(args[0], args[1:]...)
	out, err = cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("command failed: %v\n%v\n%s\n", args, err, out)
	}

	if runtime.GOOS != GOOS && GOOS == "android" {
		args = append(adbCmd(), "push", libgoname, fmt.Sprintf("%s/%s", androiddir, libgoname))
		cmd = exec.Command(args[0], args[1:]...)
		out, err = cmd.CombinedOutput()
		if err != nil {
			return fmt.Errorf("adb command failed: %v\n%s\n", err, out)
		}
	}

	return nil
}

var (
	headersOnce sync.Once
	headersErr  error
)

func createHeadersOnce(t *testing.T) {
	headersOnce.Do(func() {
		headersErr = createHeaders()
	})
	if headersErr != nil {
		t.Fatal(headersErr)
	}
}

func cleanupAndroid() {
	if GOOS != "android" {
		return
	}
	args := append(adbCmd(), "exec-out", "rm", "-rf", androiddir)
	cmd := exec.Command(args[0], args[1:]...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		log.Panicf("cleanupAndroid failed: %v\n%s\n", err, out)
	}
}

// test0: exported symbols in shared lib are accessible.
func TestExportedSymbols(t *testing.T) {
	t.Parallel()

	cmd := "testp0"
	bin := cmdToRun(cmd)

	createHeadersOnce(t)

	runCC(t, "-I", installdir, "-o", cmd, "main0.c", libgoname)
	adbPush(t, cmd)

	defer os.Remove(bin)

	out := runExe(t, []string{"LD_LIBRARY_PATH=."}, bin)
	if strings.TrimSpace(out) != "PASS" {
		t.Error(out)
	}
}

// test1: shared library can be dynamically loaded and exported symbols are accessible.
func TestExportedSymbolsWithDynamicLoad(t *testing.T) {
	t.Parallel()

	if GOOS == "windows" {
		t.Logf("Skipping on %s", GOOS)
		return
	}

	cmd := "testp1"
	bin := cmdToRun(cmd)

	createHeadersOnce(t)

	if GOOS != "freebsd" {
		runCC(t, "-o", cmd, "main1.c", "-ldl")
	} else {
		runCC(t, "-o", cmd, "main1.c")
	}
	adbPush(t, cmd)

	defer os.Remove(bin)

	out := runExe(t, nil, bin, "./"+libgoname)
	if strings.TrimSpace(out) != "PASS" {
		t.Error(out)
	}
}

// test2: tests libgo2 which does not export any functions.
func TestUnexportedSymbols(t *testing.T) {
	t.Parallel()

	if GOOS == "windows" {
		t.Logf("Skipping on %s", GOOS)
		return
	}

	cmd := "testp2"
	bin := cmdToRun(cmd)
	libname := "libgo2." + libSuffix

	run(t,
		nil,
		"go", "build",
		"-buildmode=c-shared",
		"-installsuffix", "testcshared",
		"-o", libname, "./libgo2",
	)
	adbPush(t, libname)

	linkFlags := "-Wl,--no-as-needed"
	if GOOS == "darwin" {
		linkFlags = ""
	}

	runCC(t, "-o", cmd, "main2.c", linkFlags, libname)
	adbPush(t, cmd)

	defer os.Remove(libname)
	defer os.Remove(bin)

	out := runExe(t, []string{"LD_LIBRARY_PATH=."}, bin)

	if strings.TrimSpace(out) != "PASS" {
		t.Error(out)
	}
}

// test3: tests main.main is exported on android.
func TestMainExportedOnAndroid(t *testing.T) {
	t.Parallel()

	switch GOOS {
	case "android":
		break
	default:
		t.Logf("Skipping on %s", GOOS)
		return
	}

	cmd := "testp3"
	bin := cmdToRun(cmd)

	createHeadersOnce(t)

	runCC(t, "-o", cmd, "main3.c", "-ldl")
	adbPush(t, cmd)

	defer os.Remove(bin)

	out := runExe(t, nil, bin, "./"+libgoname)
	if strings.TrimSpace(out) != "PASS" {
		t.Error(out)
	}
}

func testSignalHandlers(t *testing.T, pkgname, cfile, cmd string) {
	libname := pkgname + "." + libSuffix
	run(t,
		nil,
		"go", "build",
		"-buildmode=c-shared",
		"-installsuffix", "testcshared",
		"-o", libname, pkgname,
	)
	adbPush(t, libname)
	if GOOS != "freebsd" {
		runCC(t, "-pthread", "-o", cmd, cfile, "-ldl")
	} else {
		runCC(t, "-pthread", "-o", cmd, cfile)
	}
	adbPush(t, cmd)

	bin := cmdToRun(cmd)

	defer os.Remove(libname)
	defer os.Remove(bin)
	defer os.Remove(pkgname + ".h")

	out := runExe(t, nil, bin, "./"+libname)
	if strings.TrimSpace(out) != "PASS" {
		t.Error(run(t, nil, bin, libname, "verbose"))
	}
}

// test4: test signal handlers
func TestSignalHandlers(t *testing.T) {
	t.Parallel()
	if GOOS == "windows" {
		t.Logf("Skipping on %s", GOOS)
		return
	}
	testSignalHandlers(t, "./libgo4", "main4.c", "testp4")
}

// test5: test signal handlers with os/signal.Notify
func TestSignalHandlersWithNotify(t *testing.T) {
	t.Parallel()
	if GOOS == "windows" {
		t.Logf("Skipping on %s", GOOS)
		return
	}
	testSignalHandlers(t, "./libgo5", "main5.c", "testp5")
}

func TestPIE(t *testing.T) {
	t.Parallel()

	switch GOOS {
	case "linux", "android":
		break
	default:
		t.Logf("Skipping on %s", GOOS)
		return
	}

	createHeadersOnce(t)

	f, err := elf.Open(libgoname)
	if err != nil {
		t.Fatalf("elf.Open failed: %v", err)
	}
	defer f.Close()

	ds := f.SectionByType(elf.SHT_DYNAMIC)
	if ds == nil {
		t.Fatalf("no SHT_DYNAMIC section")
	}
	d, err := ds.Data()
	if err != nil {
		t.Fatalf("can't read SHT_DYNAMIC contents: %v", err)
	}
	for len(d) > 0 {
		var tag elf.DynTag
		switch f.Class {
		case elf.ELFCLASS32:
			tag = elf.DynTag(f.ByteOrder.Uint32(d[:4]))
			d = d[8:]
		case elf.ELFCLASS64:
			tag = elf.DynTag(f.ByteOrder.Uint64(d[:8]))
			d = d[16:]
		}
		if tag == elf.DT_TEXTREL {
			t.Fatalf("%s has DT_TEXTREL flag", libgoname)
		}
	}
}

// Test that installing a second time recreates the header file.
func TestCachedInstall(t *testing.T) {
	tmpdir, err := ioutil.TempDir("", "cshared")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)

	copyFile(t, filepath.Join(tmpdir, "src", "testcshared", "go.mod"), "go.mod")
	copyFile(t, filepath.Join(tmpdir, "src", "testcshared", "libgo", "libgo.go"), filepath.Join("libgo", "libgo.go"))
	copyFile(t, filepath.Join(tmpdir, "src", "testcshared", "p", "p.go"), filepath.Join("p", "p.go"))

	env := append(os.Environ(), "GOPATH="+tmpdir, "GOBIN="+filepath.Join(tmpdir, "bin"))

	buildcmd := []string{"go", "install", "-x", "-buildmode=c-shared", "-installsuffix", "testcshared", "./libgo"}

	cmd := exec.Command(buildcmd[0], buildcmd[1:]...)
	cmd.Dir = filepath.Join(tmpdir, "src", "testcshared")
	cmd.Env = env
	t.Log(buildcmd)
	out, err := cmd.CombinedOutput()
	t.Logf("%s", out)
	if err != nil {
		t.Fatal(err)
	}

	var libgoh, ph string

	walker := func(path string, info os.FileInfo, err error) error {
		if err != nil {
			t.Fatal(err)
		}
		var ps *string
		switch filepath.Base(path) {
		case "libgo.h":
			ps = &libgoh
		case "p.h":
			ps = &ph
		}
		if ps != nil {
			if *ps != "" {
				t.Fatalf("%s found again", *ps)
			}
			*ps = path
		}
		return nil
	}

	if err := filepath.Walk(tmpdir, walker); err != nil {
		t.Fatal(err)
	}

	if libgoh == "" {
		t.Fatal("libgo.h not installed")
	}

	if err := os.Remove(libgoh); err != nil {
		t.Fatal(err)
	}

	cmd = exec.Command(buildcmd[0], buildcmd[1:]...)
	cmd.Dir = filepath.Join(tmpdir, "src", "testcshared")
	cmd.Env = env
	t.Log(buildcmd)
	out, err = cmd.CombinedOutput()
	t.Logf("%s", out)
	if err != nil {
		t.Fatal(err)
	}

	if _, err := os.Stat(libgoh); err != nil {
		t.Errorf("libgo.h not installed in second run: %v", err)
	}
}

// copyFile copies src to dst.
func copyFile(t *testing.T, dst, src string) {
	t.Helper()
	data, err := ioutil.ReadFile(src)
	if err != nil {
		t.Fatal(err)
	}
	if err := os.MkdirAll(filepath.Dir(dst), 0777); err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(dst, data, 0666); err != nil {
		t.Fatal(err)
	}
}

func TestGo2C2Go(t *testing.T) {
	switch GOOS {
	case "darwin":
		// Darwin shared libraries don't support the multiple
		// copies of the runtime package implied by this test.
		t.Skip("linking c-shared into Go programs not supported on Darwin; issue 29061")
	case "android":
		t.Skip("test fails on android; issue 29087")
	}

	t.Parallel()

	tmpdir, err := ioutil.TempDir("", "cshared-TestGo2C2Go")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)

	lib := filepath.Join(tmpdir, "libtestgo2c2go."+libSuffix)
	run(t, nil, "go", "build", "-buildmode=c-shared", "-o", lib, "./go2c2go/go")

	cgoCflags := os.Getenv("CGO_CFLAGS")
	if cgoCflags != "" {
		cgoCflags += " "
	}
	cgoCflags += "-I" + tmpdir

	cgoLdflags := os.Getenv("CGO_LDFLAGS")
	if cgoLdflags != "" {
		cgoLdflags += " "
	}
	cgoLdflags += "-L" + tmpdir + " -ltestgo2c2go"

	goenv := []string{"CGO_CFLAGS=" + cgoCflags, "CGO_LDFLAGS=" + cgoLdflags}

	ldLibPath := os.Getenv("LD_LIBRARY_PATH")
	if ldLibPath != "" {
		ldLibPath += ":"
	}
	ldLibPath += tmpdir

	runenv := []string{"LD_LIBRARY_PATH=" + ldLibPath}

	bin := filepath.Join(tmpdir, "m1") + exeSuffix
	run(t, goenv, "go", "build", "-o", bin, "./go2c2go/m1")
	runExe(t, runenv, bin)

	bin = filepath.Join(tmpdir, "m2") + exeSuffix
	run(t, goenv, "go", "build", "-o", bin, "./go2c2go/m2")
	runExe(t, runenv, bin)
}


text:
package org.web3j.abi.datatypes.generated;

import org.web3j.abi.datatypes.Bytes;

/**
 *
Auto generated code.

 * Do not modifiy!

 * Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.

 */
public class Bytes30 extends Bytes {
    public static final Bytes30 DEFAULT = new Bytes30(new byte[30]);

    public Bytes30(byte[] value) {
        super(30, value);
    }
}


text:
import pygame
import os
from pygame import *
import random

#PREPROCESSING
pygame.mixer.init()
clock = pygame.time.Clock()

#COLORS
RED = (255,0,0)
MAGENTA = (255, 56, 156)
ORANGE = (240, 240, 0)
GREEN = (0,255,0)
YELLOW = (255,255,0)
BLUE = (0,0,255)
BLU = (83,190,255)
WHITE = (255,255,255)
BLACK = (0,0,0)
GREY = (127, 127, 127)
LGRAY = (200, 200, 200)
DGRAY = (55, 55, 55)

#VARIOUS DEFAULT VALUES
WINSIZE = (640,480)
FPS = 60

#PLACEHOLDER DUMMY FUNCTION
def derp():
    counter = 0
    while counter <= 50:
        counter+=1
        clock.tick(FPS)
    counter = 0
    print 'nothing to see here'

#Takes the name of a text sheet and returns a text-object
def texty(name,size):
	name = os.path.join("data", name)
	Texty = pygame.font.Font(name, size)
	return Texty

#HELPER FUNCTIONS
def imglode(file,folder="data",alpha=True):
    img = pygame.image.load(os.path.join(folder, file))
    if alpha:
        colorkey = img.get_at((0,0))
        img.set_colorkey(colorkey, RLEACCEL)
    return img.convert()

#Takes the file name for a given "sound" file (.wav,
# .ogg, or .mp3), returns a "sound" object. Sound file
# must be located in "data" subfolder.
def FXLODE(file,volume=0.4,path="FX"):
    FX = pygame.mixer.Sound(os.path.join(path, file))
    print "Sound " + file + " successfully loaded"
    FX.set_volume(volume)
    return FX
def fxplay(thing,sure=True):
	if sure:
		thing.play()

#Takes the file name for a given "music" file (.mp3),
# and loads it for playback. Due to audio constraints,
# pygame restricts music playback to 1 stream, therefore
# musiclode() returns nothing. Music file imported must
# be in subfolder named "data"
def musiclode(file):
	if(checkfile(file)):
		pygame.mixer.music.load(os.path.join("data", file))
		print "music successfuly loaded: " + file
	else:
		print "Error, " + file + " does not exist."

# if sure is true, then music plays on infinite loop b/c amount = -1
def musicplay(sure=True,amount=-1):
    if sure: pygame.mixer.music.play((amount))
    print "playing.."

#Changes the name of the program on the toolbar
def caption(name):
    pygame.display.set_caption(name)

#To be used in conjunction with the imglode function, this
 #function takes a surface and increases the size by a
 #given amount, maintaining proportions
def imgscale(image, amount):
    newsize = image.get_size()
    newsize = (newsize[0]*amount, newsize[1]*amount)
    return pygame.transform.scale(image, newsize)

#This function takes an image and splits it into multiple
 #frames contained within the suface array that it returns.
 #The image is split up first by row, and then by column.
 #The coder must enter the name of the surface, as well as
 #the size of the length/width of the square
def getsub(image, size):
    sub = image.get_rect()
    subx = sub[2]/size
    suby = sub[3]/size
    dummy = (0,0)
    images = []
    while dummy[0] < suby:
        while dummy[1] < subx:
            newrect = (dummy[1]*size,
                       dummy[0]*size,
                       size, size)
            images.append(image.subsurface(newrect))
            dummy = (dummy[0], dummy[1]+1)
        dummy = (dummy[0]+1, 0)
    return images

#File handling function. All files read are assumed to be in
# text format, and are also assumed to be contained in a folder
# named "levels" which is in this directory. Second parameter
# determines the mode of opening the file. If left off, mode
# defaults to "read"
def FILE(name,code='r'):
    return open(os.path.join("levels", name+'.txt'),code)

#String->Int or String->Float converter. If an error occurs
# the string is simply returned
def convertStr(s):
    try:
        ret = int(s)
    except ValueError:
        try:
            ret = float(s)
        finally:
            print "ERROR, INPUT IS NOT A NUMBER"
            return "FAIL"
    return ret

#Text-handling function for the easy and rapid development of
# levels for linearly-designed games or otherwise-choreographed
# scripted events within the game. This function takes only one
# parameter, the name of the file where the text document is
# located (e.g. 'LEVELS'). If successful, function returns a
# list in the form:
# list(level title, list of integers, list of letters, end title)
def loadlevel(textname):
    f = FILE(textname)
    z = f.readlines()
    title = z[0][0:(len(z[0])-1)]
    alternator = 1
    lineno = 1
    numbers = []
    letters = []
    returner = []
    for i in z[1:(len(z)-1)]:
        lineno+=1
        if alternator:
            number = convertStr(i[0:len(i)-1])
            if(number != "FAIL"):
                numbers.append(number*30)
            else:
                print "ERROR ON LINE %d: " % lineno
                print " LINE IS NOT A NUMBER"
                return False
            alternator = 0
        else:
            letter = i[0:len(i)-1]
            if((letter == 'w') or
			(letter=='b') or (letter=='B') or
			(letter=='g') or (letter=='G') or
			(letter=='f') or (letter=='F') or
			(letter=='3w')or (letter=='3W') or
			(letter=='k') or (letter=='K') or
			(letter=='x') or (letter=='X') or
			(letter=='p') or (letter=='P') or
			(letter=='s') or (letter=='S')):
                letters.append(i[0:len(i)-1])
            else:
                print "ERROR ON LINE %d: " % lineno
                print " LINE IS NOT A VALID LETTER"
                print " MUST BE 'w', 'b', '3w', 'k', 'g', 'x', 'f'"
                print "		'p', or 's'"
                return False
            alternator = 1
    returner.append(title)
    returner.append(numbers)
    returner.append(letters)
    returner.append(z[(len(z))-1])
    print returner
    return returner

#checkfile() is a function that takes two inputs:
# *A filename (e.g. "levels.txt", "scores.txt", et al)
# *A folder (e.g. "data", "music", et al)
#Using these parameters, function will return true if the
# file exists and false if it does not. For the sake of
# streamlining, folder will default to "data"
def checkfile(file,folder="data"):
	if os.path.isfile(os.path.join(folder, file)):
		return True
	else: return False


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package guidemo.helpers;

import guidemo.models.ReticEntry;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import guidemo.models.WaterDetail;
import java.util.ArrayList;

/**
 *
 */
public class XlsReader {

    public static void readXlsFile(String fileName) {
        String excelFilePath = fileName;
        try {
            FileInputStream excelFile = new FileInputStream(new File(excelFilePath));
            XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
            XSSFSheet datatypeSheet = workbook.getSheetAt(1);
            Iterator<Row> iterator = datatypeSheet.iterator();

            while (iterator.hasNext()) {
                Row nextRow = iterator.next();
                Iterator<Cell> cellIterator = nextRow.cellIterator();

                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    CellType type = cell.getCellTypeEnum();

                    if (type == CellType.STRING) {
                        System.out.print(cell.getStringCellValue());
                    }

                    if (type == CellType.BOOLEAN) {
                        System.out.print(cell.getBooleanCellValue());
                    }

                    if (type == CellType.FORMULA) {
                        System.out.print(cell.getCellFormula());
                    }

                    if (type == CellType.NUMERIC) {
                        System.out.print(cell.getNumericCellValue());
                    }

                    System.out.print(" - ");
                }
                System.out.println();
            }

            workbook.close();
            excelFile.close();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(XlsReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XlsReader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static public WaterDetail[] readWaterInfo(String fileName, int beginRow, int sheetNumber) {

        ArrayList<WaterDetail> rs = new ArrayList<>();

        try {
            FileInputStream excelFile = new FileInputStream(new File(fileName));
            XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
            XSSFSheet datatypeSheet = workbook.getSheetAt(sheetNumber);
            Iterator<Row> iterator = datatypeSheet.iterator();
            int line = 0;

            while (iterator.hasNext()) {
                Row nextRow = iterator.next();

                if (line >= beginRow) {
                    Cell dateCell = nextRow.getCell(0);
                    Cell tciInCell = nextRow.getCell(1);
                    Cell tciOutCell = nextRow.getCell(2);
                    Cell tempCell = nextRow.getCell(3);
                    Cell nh3Cell = nextRow.getCell(4);
                    Cell no2Cell = nextRow.getCell(5);
                    Cell tabletCell = nextRow.getCell(6);

                    if (canParseDate(dateCell)) {
                        Date date = dateCell.getDateCellValue();
                        float tciIn = tryParseNumber(tciInCell);
                        float tciOut = tryParseNumber(tciOutCell);
                        float temp = tryParseNumber(tempCell);
                        float nh3 = tryParseNumber(nh3Cell);
                        float no2 = tryParseNumber(no2Cell);
                        String tablet = tryParseString(tabletCell);

                        WaterDetail dt;
                        dt = new WaterDetail(date, tciIn, tciOut, temp, nh3, no2, tablet);
                        dt.calculateValue();

                        rs.add(dt);
                    }
                }

                line++;
            }

            workbook.close();
            excelFile.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XlsReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XlsReader.class.getName()).log(Level.SEVERE, null, ex);
        }

        return rs.toArray(new WaterDetail[rs.size()]);
    }

    static public ReticEntry[] readReticInfo(String fileName, int beginRow, int sheetNumber) {

        ArrayList<ReticEntry> rs = new ArrayList<>();

        try {
            FileInputStream excelFile = new FileInputStream(new File(fileName));
            XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
            XSSFSheet datatypeSheet = workbook.getSheetAt(sheetNumber);
            Iterator<Row> iterator = datatypeSheet.iterator();
            int line = 0;

            while (iterator.hasNext()) {
                Row nextRow = iterator.next();

                if (line >= beginRow) {
                    Cell dateCell = nextRow.getCell(8);
                    Cell totalChlorineCell = nextRow.getCell(9);
                    Cell temperatureCell = nextRow.getCell(10);
                    Cell nh3Cell = nextRow.getCell(11);
                    Cell no2Cell = nextRow.getCell(12);

                    if (canParseDate(dateCell)) {
                        Date date = dateCell.getDateCellValue();
                        float totalChlorine = tryParseNumber(totalChlorineCell);
                        float temperature = tryParseNumber(temperatureCell);
                        float nh3 = tryParseNumber(nh3Cell);
                        float no2 = tryParseNumber(no2Cell);

                        ReticEntry dt;
                        dt = new ReticEntry(date, totalChlorine, temperature, nh3, no2);
                        dt.calculateValue();

                        rs.add(dt);
                    }
                }

                line++;
            }

            workbook.close();
            excelFile.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XlsReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XlsReader.class.getName()).log(Level.SEVERE, null, ex);
        }

        return rs.toArray(new ReticEntry[rs.size()]);
    }

    public static float tryParseNumber(Cell cell) {
        float val = 0;

        if (cell != null) {
            CellType type = cell.getCellTypeEnum();

            if (type == CellType.NUMERIC) {
                val = (float) cell.getNumericCellValue();
            }

            if (type == CellType.FORMULA) {

                CellType cachedType = cell.getCachedFormulaResultTypeEnum();
                if ( cachedType == CellType.NUMERIC) {
                    val = (float) cell.getNumericCellValue();
                }

            }
        }

        return val;
    }

    public static String tryParseString(Cell cell) {
        String val = "";

        if (cell != null) {
            CellType type = cell.getCellTypeEnum();

            if (type == CellType.STRING) {
                val = cell.getStringCellValue();
            }
        }

        return val;
    }

    private static Boolean canParseDate(Cell cell) {
        if (cell == null) {
            return false;
        }

        return cell.getCellTypeEnum() == CellType.NUMERIC;
    }
}


text:
//  Copyright (c) 2013 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using DNA.Patterns.Commands;
using System;

namespace DNA.Patterns.Tasks
{
    /// <summary>
    /// The Task pattern combine with Command pattern
    /// </summary>
    public interface ICommandTask : ITask
    {
        /// <summary>
        /// Gets the command that execute on task successful run.
        /// </summary>
        ICommand SuccessCommand { get; }

        /// <summary>
        /// Gets the command that execute on fail.
        /// </summary>
        ICommand FailCommand { get; }

        /// <summary>
        /// Gets the process command
        /// </summary>
        ICommand Command { get; }

        /// <summary>
        /// Execute the fail command.
        /// </summary>
        /// <param name="e"></param>
        void Fail(Exception e);

        /// <summary>
        /// Execute the success command.
        /// </summary>
        void Succeed();

    }

}


text:
CREATE OR REPLACE FUNCTION live.inventory_get (p_account_id live.inventory.account_id%type)
returns
	TABLE(
		bag_type_id live.inventory_bags.bag_type_id%TYPE
	  , internal_name static.item.internal_name%TYPE
	  , name static.localized_text_detail.value%TYPE
	  , description static.localized_text_detail.value%TYPE
	  , flags static.item.flag%TYPE
	  , count live.inventory_details.count%TYPE
	  , max_count static.item.max_count%TYPE
	  , metadata live.inventory_details.metadata%TYPE)

AS $$
declare
	v_lang live.account.language_id%TYPE;
	v_cur_event static.event.event_id%TYPE = live.get_current_event(p_account_id);
BEGIN
	select language_id into v_lang
	from live.account
	where account_id = p_account_id;

	return query (
		select
			b.bag_type_id
		  , si.internal_name
		  , static.get_localized_text(si.name_id, v_lang)
		  , static.get_localized_text(si.description_id, v_lang)
		  , flag
		  , id.count
		  , si.max_count
		  , id.metadata
		from live.inventory_details id
		inner join static.item si
			on si.item_id = id.item_id
		inner join live.inventory_bags b
			on id.bag_instance_id = b.bag_instance_id
		inner join live.inventory i
			on i.inventory_id = b.inventory_id
		where i.account_id = p_account_id
			and id.count > 0
			and (b.event_id is null or b.event_id = v_cur_event));
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;


text:
          <m-img encode="true" src="item.image"></m-img>

					<m-img encode="true" src="item.image"></m-img>

      <m-img class="detail-img full-width-image-{{ itemStyle }}" url="{{detail.image}}"></m-img>


text:
<?php

namespace Totaltrash\LibraryBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;

class SongType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // UH OH - THIS FORM IS PARTIALLY DUPLICATED IN SongAdminController->editAction
        $builder
            ->add('name')
            ->add('description')
            ->add('files', 'collection', array('type' => new SongFileType()))
            ->add('genre', 'entity', array(
                    'class'=>'TotaltrashLibraryBundle:Genre',
                    'query_builder' => function(EntityRepository $er) {
                        return $er->createQueryBuilder('t')
                            ->where('t.enabled = true')
                            ->orderBy('t.name', 'ASC');
                    },
                    'property'=>'name'))
            ->add('instruments', 'entity', array(
                    'class'=>'TotaltrashLibraryBundle:Instrument',
                    'query_builder' => function(EntityRepository $er) {
                        return $er->createQueryBuilder('t')
                            ->where('t.enabled = true')
                            ->orderBy('t.name', 'ASC');
                    },
                    'property'=>'name',
                    'expanded'=>TRUE,
                    'multiple'=>TRUE))
            ->add('soundTags', 'entity', array(
                    'class'=>'TotaltrashLibraryBundle:SoundTag',
                    'query_builder' => function(EntityRepository $er) {
                        return $er->createQueryBuilder('t')
                            ->where('t.enabled = true')
                            ->orderBy('t.name', 'ASC');
                    },
                    'property'=>'name',
                    'expanded'=>TRUE,
                    'multiple'=>TRUE))
            ->add('production_types', 'entity', array(
                    'class'=>'TotaltrashLibraryBundle:ProductionType',
                    'query_builder' => function(EntityRepository $er) {
                        return $er->createQueryBuilder('t')
                            ->where('t.enabled = true')
                            ->orderBy('t.name', 'ASC');
                    },
                    'property'=>'name',
                    'expanded'=>TRUE,
                    'multiple'=>TRUE));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Totaltrash\LibraryBundle\Entity\Song',
        ));
    }

    public function getName()
    {
        return 'song';
    }
}