text:
/*global angular*/
/*global _*/
/*global moment*/
/*global $U*/
angular.module('service-app-api', ['service-app-utils']).service('appApi', ['$rootScope', '$log', 'appUtils', 'appSettings', 'fileUpload', 'i18n', function($rootScope, $log, appUtils, appSettings, fileUpload, i18n) {

    const CONSTANT = {
        COMMON_DATABASE_ACTIONS: ['get', 'getAll', 'save', 'update', 'getById', 'exists', 'removeWhen', 'updateOrPushArrayElement', 'modelCustom', 'aggregate'],
        COMMON_DATABASE_CONTROLLERS: ['categories', 'texts']
    };

    function getLemonwayMessage(res) {
        return res.err.Msg + '  (LEMONWAY CODE ' + res.err.Code + ')';
    }

    function getGenericMessage(res) {
        if (res.err && res.err.code) {
            if (i18n && i18n[res.err.code]) {
                return i18n[res.err.code];
            }
        }
        var str = (res.err && (res.err.message || res.err.msg) || JSON.stringify(res));
        str = str.replace("'", "");
        return str + '  (BACKEND)';
    }

    function json(ctrl, action, data) {
        return appUtils.Promise(function(resolve, error) {
            appUtils.httpPost(appSettings.URL + 'api/' + ctrl + '/' + action, data, function(res) {
                //console.info('CTRL: ',res.data);
                return resolve(res.data);
            }, error);
        });
    }

    function fetch(url) {
        return appUtils.Promise(function(resolve, error) {
            appUtils.httpGet(url, function(res) {
                return resolve(res.data);
            }, error);
        });
    }

    function form(ctrl, action, payload) {
        var multerType = payload.__form;
        delete payload.__form;
        return appUtils.Promise(function(resolve, error) {
            var file = payload.file;
            delete payload.file;
            payload = JSON.stringify(payload);
            return fileUpload.single({
                url: appSettings.URL + 'api/' + ctrl + '/' + action + '/' + multerType,
                file: file,
                data: payload
            }, (res) => {
                resolve(res);
            }, (res) => {
                error(res);
            });
        });
    }

    function handle(controller, action, payload) {
        return appUtils.Promise(function(resolve, err, emit) {
            if (payload.__form) {
                form(controller, action, payload).then(onSuccess).error(onError);
            }
            else {
                json(controller, action, payload).then(onSuccess).error(onError);
            }

            function onSuccess(res) {
                if (res.ok != undefined && res.ok == false) {
                    if (res.err && res.err.Code) {
                        return emit('validate', getLemonwayMessage(res));
                    }
                    if (res.err) {
                        return emit('validate', getGenericMessage(res));
                    }
                    err(res);
                }
                else {
                    resolve(res.result);
                }
            }

            function onError(res) {
                if (res.err && res.err.Code) {
                    return emit('validate', getLemonwayMessage(res));
                }
                if (res.err) {
                    emit('validate', getGenericMessage(res));
                }
                err(res);
            }
        });
    }

    function createActions(collectionName, includeClientSideCustomApiActions) {
        includeClientSideCustomApiActions = includeClientSideCustomApiActions == undefined ? true : includeClientSideCustomApiActions;
        var self = {};
        var actions = CONSTANT.COMMON_DATABASE_ACTIONS;

        for (var x in actions) {
            (function(collectionName, actionName) {
                self[actionName] = (data) => {
                    return handle(collectionName, actionName, data);
                };
            })(collectionName, actions[x]);
        }

        if (includeClientSideCustomApiActions && customApiActions[collectionName] !== undefined) {
            Object.keys(customApiActions[collectionName]).forEach(actionName => {
                self[actionName] = (data) => {
                    return appUtils.Promise(function(resolve, reject, emit) {
                        return customApiActions[collectionName][actionName](data, resolve, reject, emit);
                    });
                };
            });
        }

        self.custom = (actionName, data) => {
            return handle(collectionName, actionName, data);
        };

        return self;
    }

    var customApiActions = {};

    var self = {
        addCustomAction: (collectionName, actionName, handler) => {
            customApiActions[collectionName] = customApiActions[collectionName] || {};
            customApiActions[collectionName][actionName] = handler;
        },
        addController: (controllerName, collectionName, customActions) => {
            if (customActions) {
                Object.keys(customActions).forEach(actionName => {
                    self.addCustomAction(collectionName, actionName, customActions[actionName])
                });
            }
            self[controllerName] = createActions(collectionName);
        },
        ctrl: handle,
        updateAttribute: function(table, _id, attrName, attrValue) {
            var payload = {
                _id: _id
            };
            payload[attrName] = attrValue;
            return handle(table, 'update', payload);
        },
        savePrerender: function() {
            var partialRoute = window.location.href.substring(window.location.origin.length + 1);
            partialRoute = appUtils.replaceAll(partialRoute, "/", "--");

            return appUtils.Promise(function(resolve, error) {
                fetch('/app/index.html').then(raw => {
                    if (raw) {
                        var staticContent = window.$('#main-view').html()
                        raw = raw.replaceAll('

', '
' + staticContent + '
');
                        var encoded = window.encodeURIComponent(raw);
                        return handle('prerender', 'savePrerender', {
                            path: partialRoute,
                            content: encoded
                        });
                    }
                });
            });
        },
        saveImageCloudinary: function(public_id, file) {
            return handle('image', 'saveCloudinary', {
                file: file,
                __cloudinary: {
                    public_id: public_id
                },
                __form: "multer_single"
            });
        },
        subscribe: function(email) {
            return handle('Notification', 'M_SUBSCRIBE', {
                email: email
            });
        },
        delete: function(table, id) {
            return handle(table, 'removeWhen', {
                _id: id
            });
        },
        getById: function(table, id, extraPayload) {
            return handle(table, 'get', Object.assign({
                _id: id
            }, extraPayload || {}));
        },
        getEvent: function(id, extraPayload) {
            return handle('mevent', 'get', Object.assign({
                _id: id
            }, extraPayload || {}));
        },
        saveCollection: function(collectionName, data) {
            return handle(collectionName, 'save', data);
        },
        saveProject: function(data) {
            return handle('project', 'saveProject', data);
        },
        saveTask: function(data) {
            return handle('task', 'saveTask', data);
        },
        saveEvent: function(data) {
            if (!data._id) {
                data.status = 'open';
            }
            return handle('mevent', 'save', data);
        },
        closeEvent: function(data) {
            data = {
                _id: data._id,
                status: 'closed'
            };
            return handle('mevent', 'update', data);
        },
        openEvent: function(data) {
            data = {
                _id: data._id,
                status: 'open'
            };
            return handle('mevent', 'update', data);
        },
        saveProfile: function(data) {
            return handle('muser', 'saveProfile', data);
        },
        signUp: function(data) {
            return handle('muser', 'signUp', data);
        },
        signIn: function(data) {
            return handle('muser', 'signIn', data);
        }
    };

    CONSTANT.COMMON_DATABASE_CONTROLLERS.forEach((controllerName) => {
        self.addController(controllerName, controllerName);
    });

    $rootScope._appApi = self;
    return self;

}]);


text:
using System;
using System.Linq;
using System.Reflection;

using JetBrains.Annotations;

// ReSharper disable CheckNamespace

namespace AntData.ORM
{
	using Extensions;
	using SqlQuery;

	partial class Sql
	{
		[PublicAPI]
		[Serializable]
		[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
		public class ExpressionAttribute : Attribute
		{
			public ExpressionAttribute(string expression)
			{
				Expression = expression;
				Precedence = SqlQuery.Precedence.Primary;
			}

			public ExpressionAttribute(string expression, params int[] argIndices)
			{
				Expression = expression;
				ArgIndices = argIndices;
				Precedence = SqlQuery.Precedence.Primary;
			}

			public ExpressionAttribute(string configuration, string expression)
			{
				Configuration = configuration;
				Expression    = expression;
				Precedence    = SqlQuery.Precedence.Primary;
			}

			public ExpressionAttribute(string configuration, string expression, params int[] argIndices)
			{
				Configuration = configuration;
				Expression    = expression;
				ArgIndices    = argIndices;
				Precedence    = SqlQuery.Precedence.Primary;
			}

			public string Expression       { get; set; }
			public int[]  ArgIndices       { get; set; }
			public int    Precedence       { get; set; }
			public string Configuration    { get; set; }
			public bool   ServerSideOnly   { get; set; }
			public bool   PreferServerSide { get; set; }
			public bool   InlineParameters { get; set; }
			public bool   ExpectExpression { get; set; }
			public bool   IsPredicate      { get; set; }

			private bool? _canBeNull;
			public  bool   CanBeNull
			{
				get { return _canBeNull ?? true;  }
				set { _canBeNull = value;         }
			}

			protected ISqlExpression[] ConvertArgs(MemberInfo member, ISqlExpression[] args)
			{
				if (member is MethodInfo)
				{
					var method = (MethodInfo)member;

					if (method.DeclaringType.IsGenericTypeEx())
						args = args.Concat(method.DeclaringType.GetGenericArgumentsEx().Select(t => (ISqlExpression)SqlDataType.GetDataType(t))).ToArray();

					if (method.IsGenericMethod)
						args = args.Concat(method.GetGenericArguments().Select(t => (ISqlExpression)SqlDataType.GetDataType(t))).ToArray();
				}

				if (ArgIndices != null)
				{
					var idxs = new ISqlExpression[ArgIndices.Length];

					for (var i = 0; i < ArgIndices.Length; i++)
						idxs[i] = args[ArgIndices[i]];

					return idxs;
				}

				return args;
			}

			public virtual ISqlExpression GetExpression(MemberInfo member, params ISqlExpression[] args)
			{
				return new SqlExpression(member.GetMemberType(), Expression ?? member.Name, Precedence, ConvertArgs(member, args)) { CanBeNull = CanBeNull };
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.cognitoidp.model.transform;

import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.cognitoidp.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * CodeDeliveryDetailsTypeMarshaller
 */
public class CodeDeliveryDetailsTypeJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a SdkJsonGenerator
     */
    public void marshall(CodeDeliveryDetailsType codeDeliveryDetailsType,
            StructuredJsonGenerator jsonGenerator) {

        if (codeDeliveryDetailsType == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonGenerator.writeStartObject();

            if (codeDeliveryDetailsType.getDestination() != null) {
                jsonGenerator.writeFieldName("Destination").writeValue(
                        codeDeliveryDetailsType.getDestination());
            }
            if (codeDeliveryDetailsType.getDeliveryMedium() != null) {
                jsonGenerator.writeFieldName("DeliveryMedium").writeValue(
                        codeDeliveryDetailsType.getDeliveryMedium());
            }
            if (codeDeliveryDetailsType.getAttributeName() != null) {
                jsonGenerator.writeFieldName("AttributeName").writeValue(
                        codeDeliveryDetailsType.getAttributeName());
            }

            jsonGenerator.writeEndObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static CodeDeliveryDetailsTypeJsonMarshaller instance;

    public static CodeDeliveryDetailsTypeJsonMarshaller getInstance() {
        if (instance == null)
            instance = new CodeDeliveryDetailsTypeJsonMarshaller();
        return instance;
    }

}


text:
This gem was made to connect to the Computrabajo api: https://iapi.computrabajo.com

## Getting started

Computrabajo works with Rails 3.2 onwards. You can add it to your Gemfile with:

```ruby
gem 'computrabajo', :git => 'git@github.com:rcereceda/computrabajo.git'
```

...or can fetch the latest developer version with:

```ruby
gem 'computrabajo', :git => 'git@github.com:rcereceda/computrabajo.git', :branch => 'develop'
```

### Configuration

After you finished the gem installation, you need to configure it with your Computrabajo user information. You can do it filling a file like config/initializers/computrabajo.rb with:

```ruby
Computrabajo.setup do |config|
  config.username          = ""   # username provided by Computrabajo
  config.password          = ""   # password provided by Computrabajo
  config.contact_name      = ""   # your contact name
  config.contact_email     = ""   # your contact email (if not empty, will be shown on the offer detail for registered candidates)
  config.contact_telephone = ""   # your phone number
  config.contact_url       = ""   # your company URL
  config.job_reference     = ""   # your internal offer reference
  config.environment "production" # You can choose between production or development
end
```

## How to use

All return a json object, and raise an error (401, 403, 500) if there was one.

On success there is a "status" field on response with the following values:

- Pendiente = 1
- Activa = 2
- Caducada = 3
- Eliminada = 4
- Rechazada = 5
- Archivada = 6

### Create (publish) a new publication

```ruby
publication = Computrabajo::Publication.new
Computrabajo.create_aviso(publication.body)
```

### Get a publication data

```ruby
Computrabajo.get_aviso(publication_id)
```

### Destroy a publication

```ruby
publication = { offerId: publication_id }
Computrabajo.destroy_aviso(publication)
```

## TODO

- Add the missing methods to obtain the list of postulants


text:
require "helpers/spec_helper"

describe Videojuicer::Resource::Collection do

  before(:all) do
    @objects = [:foo]*100
    @collection = Videojuicer::Resource::Collection.new(@objects[0..9], 155, 10, 10)
  end

  it "is instantiated correctly" do
    @collection.should be_kind_of(Videojuicer::Resource::Collection)
    @collection.total.should == 155
    @collection.offset.should == 10
    @collection.limit.should == 10
  end

  it "can count the number of pages" do
    @collection.page_count.should == 16
  end

  it "can tell the current page" do
    @collection.page_number.should == 2
  end

  it "reports page 1 when tested with a zero offset" do
    c = Videojuicer::Resource::Collection.new(@objects[0..9], 155, 0, 10)
    c.page_number.should == 1
  end

  it "reports page 1 when there are zero items" do
    c = Videojuicer::Resource::Collection.new(@objects[0..9], 0, 0, 10)
    c.page_number.should == 1
  end

  it "pagination copes with a nil limit" do
    collection = Videojuicer::Resource::Collection.new(@objects[0..9], 155, 17, nil)
    collection.page_count.should == 1
    collection.page_number.should == 1
  end

  it "provides a correct offset for a page number and limit when the page is 1" do
    offset = Videojuicer::Resource::Collection.offset_from_page_number 1, 20
    offset.should == 0
  end

  it "should provide a correct offset" do
    offset = Videojuicer::Resource::Collection.offset_from_page_number 2, 20
    offset.should == 20
  end

  it "should be able to take a string as a page and limit argument" do
    offset = Videojuicer::Resource::Collection.offset_from_page_number "2", "20"
    offset.should == 20
  end

end


text:
<?php

namespace Admin\Repository;

class AbstractRepository {
}


text:
FactoryBot.define do
  factory :classification_type do |f|
    f.sequence(:name){|n| "classification_type_#{n}"}
  end
end

# == Schema Information
#
# Table name: classification_types
#
#  id           :bigint           not null, primary key
#  name         :string           not null
#  display_name :text
#  note         :text
#  position     :integer
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#


text:
            This site is not yet live.  Our official site is
            sensiblewashington.org.
            There you can join the cause, catch up on the latest news, make a
            donation, and more.

            Volunteers working on web content:  Please join the
            Web Content team for more
            information.


text:
cask 'font-unna' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/raw/master/ofl/unna/Unna-Regular.ttf'
  name 'Unna'
  homepage 'http://www.google.com/fonts/specimen/Unna'

  font 'Unna-Regular.ttf'
end


text:
#ifndef PSQLSCANSLASH_H
#define PSQLSCANSLASH_H

#include "fe_utils/psqlscan.h"

/* Different ways for scan_slash_option to handle parameter words */
enum slash_option_type
{
	OT_NORMAL,					/* normal case */
	OT_SQLID,					/* treat as SQL identifier */
	OT_SQLIDHACK,				/* SQL identifier, but don't downcase */
	OT_FILEPIPE,				/* it's a filename or pipe */
	OT_WHOLE_LINE				/* just snarf the rest of the line */
};

extern char *psql_scan_slash_command(PsqlScanState state);

extern char *psql_scan_slash_option(PsqlScanState state,
					   enum slash_option_type type,
					   char *quote,
					   bool semicolon);

extern void psql_scan_slash_command_end(PsqlScanState state);

extern int	psql_scan_get_paren_depth(PsqlScanState state);

extern void psql_scan_set_paren_depth(PsqlScanState state, int depth);

extern void dequote_downcase_identifier(char *str, bool downcase, int encoding);

#endif   /* PSQLSCANSLASH_H */


text:
using System.Collections.Generic;
using FluentAssertions;
using Xunit;

namespace Okanshi.Test
{
    public class OkanshiMonitorRegistryTest
    {
        private readonly OkanshiMonitorRegistry _okanshiMonitorRegistry;

        public OkanshiMonitorRegistryTest()
        {
            _okanshiMonitorRegistry = new OkanshiMonitorRegistry();
        }

        [Fact]
        public void No_monitors_are_registered_by_default()
        {
            var monitors = _okanshiMonitorRegistry.GetRegisteredMonitors();

            monitors.Should().BeEmpty();
        }

        [Fact]
        public void Monitor_is_not_registered_when_not_added_to_the_list_of_registered_monitors()
        {
            var monitor = new FakeMonitor();

            var isRegistered = _okanshiMonitorRegistry.IsRegistered(monitor);

            isRegistered.Should().BeFalse();
        }

        [Fact]
        public void Get_or_add_two_monitors_of_same_type_with_same_tags_result_in_one_registration()
        {
            var monitor = new FakeMonitor();
            var anotherMonitor = new FakeMonitor();
            _okanshiMonitorRegistry.GetOrAdd(monitor.Config, _ => monitor);

            _okanshiMonitorRegistry.GetOrAdd(anotherMonitor.Config, _ => anotherMonitor);

            _okanshiMonitorRegistry.GetRegisteredMonitors().Should().HaveCount(1);
        }

        [Fact]
        public void Get_or_add_two_monitors_of_same_type_with_same_tags_returns_the_first_registrated_instance()
        {
            var monitor = new FakeMonitor();
            var anotherMonitor = new FakeMonitor();
            _okanshiMonitorRegistry.GetOrAdd(monitor.Config, _ => monitor);

            var result = _okanshiMonitorRegistry.GetOrAdd(anotherMonitor.Config, _ => anotherMonitor);

            result.Should().BeSameAs(monitor);
        }

        [Fact]
        public void Get_or_add_two_monitors_of_same_type_with_different_tags_result_in_two_registrations()
        {
            var monitor = new FakeMonitor();
            var anotherMonitor = new FakeMonitor(new[] { new Tag("Test", "Test"), });
            _okanshiMonitorRegistry.GetOrAdd(monitor.Config, _ => monitor);

            _okanshiMonitorRegistry.GetOrAdd(anotherMonitor.Config, _ => anotherMonitor);

            _okanshiMonitorRegistry.GetRegisteredMonitors().Should().HaveCount(2);
        }

        [Fact]
        public void Get_or_add_two_monitors_of_same_type_with_differrent_tags_returns_the_newly_registrated_instance()
        {
            var monitor = new FakeMonitor();
            var anotherMonitor = new FakeMonitor(new[] { new Tag("Test", "Test"), });
            _okanshiMonitorRegistry.GetOrAdd(monitor.Config, _ => monitor);

            var result = _okanshiMonitorRegistry.GetOrAdd(anotherMonitor.Config, _ => anotherMonitor);

            result.Should().BeSameAs(anotherMonitor);
        }

        [Fact]
        public void Get_or_add_two_monitors_of_different_types_result_in_two_registrations()
        {
            var monitor = new FakeMonitor();
            var anotherMonitor = new FakeMonitor2();

            _okanshiMonitorRegistry.GetOrAdd(monitor.Config, _ => monitor);
            _okanshiMonitorRegistry.GetOrAdd(anotherMonitor.Config, _ => anotherMonitor);

            _okanshiMonitorRegistry.GetRegisteredMonitors().Should().HaveCount(2);
        }

        [Fact]
        public void Monitor_can_be_unregistered()
        {
            var monitor = new FakeMonitor();
            _okanshiMonitorRegistry.GetOrAdd(monitor.Config, _ => monitor);

            _okanshiMonitorRegistry.Unregister(monitor);

            _okanshiMonitorRegistry.GetRegisteredMonitors().Should().BeEmpty();
        }

        [Fact]
        public void Monitor_can_be_unregistered_when_recreated()
        {
            var monitor = new FakeMonitor();
            _okanshiMonitorRegistry.GetOrAdd(monitor.Config, _ => monitor);

            _okanshiMonitorRegistry.Unregister(new FakeMonitor());

            _okanshiMonitorRegistry.GetRegisteredMonitors().Should().BeEmpty();
        }

        [Fact]
        public void Monitor_can_be_unrgistered_when_registry_is_used_as_interface()
        {
            IMonitorRegistry registry = new OkanshiMonitorRegistry();
            var monitor = new FakeMonitor();
            registry.GetOrAdd(monitor.Config, _ => monitor);

            registry.Unregister(monitor);

            registry.GetRegisteredMonitors().Should().BeEmpty();
        }

        private class FakeMonitor : IMonitor
        {
            public FakeMonitor(IEnumerable<Tag> tags = null)
            {
                Config = MonitorConfig.Build("test");
                if (tags != null)
                {
                    Config = Config.WithTags(tags);
                }
            }

            public IEnumerable<IMeasurement> GetValues()
            {
                throw new System.NotImplementedException();
            }

            public IEnumerable<IMeasurement> GetValuesAndReset()
            {
                throw new System.NotImplementedException();
            }

            public MonitorConfig Config { get; private set; }
        }

        private class FakeMonitor2 : IMonitor
        {
            public FakeMonitor2(IEnumerable<Tag> tags = null)
            {
                Config = MonitorConfig.Build("test");
                if (tags != null)
                {
                    Config = Config.WithTags(tags);
                }
            }

            public IEnumerable<IMeasurement> GetValues()
            {
                throw new System.NotImplementedException();
            }

            public IEnumerable<IMeasurement> GetValuesAndReset()
            {
                throw new System.NotImplementedException();
            }

            public MonitorConfig Config { get; private set; }
        }
    }
}


text:
package org.oep.processmgt.model;

import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.model.BaseModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import com.liferay.portal.util.PortalUtil;

import org.oep.processmgt.service.ClpSerializer;
import org.oep.processmgt.service.UserAssignmentLocalServiceUtil;

import java.io.Serializable;

import java.lang.reflect.Method;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author trungdk
 */
public class UserAssignmentClp extends BaseModelImpl<UserAssignment>
	implements UserAssignment {
	public UserAssignmentClp() {
	}

	@Override
	public Class<?> getModelClass() {
		return UserAssignment.class;
	}

	@Override
	public String getModelClassName() {
		return UserAssignment.class.getName();
	}

	@Override
	public long getPrimaryKey() {
		return _userAssignmentId;
	}

	@Override
	public void setPrimaryKey(long primaryKey) {
		setUserAssignmentId(primaryKey);
	}

	@Override
	public Serializable getPrimaryKeyObj() {
		return _userAssignmentId;
	}

	@Override
	public void setPrimaryKeyObj(Serializable primaryKeyObj) {
		setPrimaryKey(((Long)primaryKeyObj).longValue());
	}

	@Override
	public Map<String, Object> getModelAttributes() {
		Map<String, Object> attributes = new HashMap<String, Object>();

		attributes.put("userAssignmentId", getUserAssignmentId());
		attributes.put("userId", getUserId());
		attributes.put("groupId", getGroupId());
		attributes.put("companyId", getCompanyId());
		attributes.put("createDate", getCreateDate());
		attributes.put("processOrderId", getProcessOrderId());
		attributes.put("dossierStepId", getDossierStepId());
		attributes.put("assignToUserId", getAssignToUserId());

		return attributes;
	}

	@Override
	public void setModelAttributes(Map<String, Object> attributes) {
		Long userAssignmentId = (Long)attributes.get("userAssignmentId");

		if (userAssignmentId != null) {
			setUserAssignmentId(userAssignmentId);
		}

		Long userId = (Long)attributes.get("userId");

		if (userId != null) {
			setUserId(userId);
		}

		Long groupId = (Long)attributes.get("groupId");

		if (groupId != null) {
			setGroupId(groupId);
		}

		Long companyId = (Long)attributes.get("companyId");

		if (companyId != null) {
			setCompanyId(companyId);
		}

		Date createDate = (Date)attributes.get("createDate");

		if (createDate != null) {
			setCreateDate(createDate);
		}

		Long processOrderId = (Long)attributes.get("processOrderId");

		if (processOrderId != null) {
			setProcessOrderId(processOrderId);
		}

		Long dossierStepId = (Long)attributes.get("dossierStepId");

		if (dossierStepId != null) {
			setDossierStepId(dossierStepId);
		}

		Long assignToUserId = (Long)attributes.get("assignToUserId");

		if (assignToUserId != null) {
			setAssignToUserId(assignToUserId);
		}
	}

	@Override
	public long getUserAssignmentId() {
		return _userAssignmentId;
	}

	@Override
	public void setUserAssignmentId(long userAssignmentId) {
		_userAssignmentId = userAssignmentId;

		if (_userAssignmentRemoteModel != null) {
			try {
				Class<?> clazz = _userAssignmentRemoteModel.getClass();

				Method method = clazz.getMethod("setUserAssignmentId",
						long.class);

				method.invoke(_userAssignmentRemoteModel, userAssignmentId);
			}
			catch (Exception e) {
				throw new UnsupportedOperationException(e);
			}
		}
	}

	@Override
	public long getUserId() {
		return _userId;
	}

	@Override
	public void setUserId(long userId) {
		_userId = userId;

		if (_userAssignmentRemoteModel != null) {
			try {
				Class<?> clazz = _userAssignmentRemoteModel.getClass();

				Method method = clazz.getMethod("setUserId", long.class);

				method.invoke(_userAssignmentRemoteModel, userId);
			}
			catch (Exception e) {
				throw new UnsupportedOperationException(e);
			}
		}
	}

	@Override
	public String getUserUuid() throws SystemException {
		return PortalUtil.getUserValue(getUserId(), "uuid", _userUuid);
	}

	@Override
	public void setUserUuid(String userUuid) {
		_userUuid = userUuid;
	}

	@Override
	public long getGroupId() {
		return _groupId;
	}

	@Override
	public void setGroupId(long groupId) {
		_groupId = groupId;

		if (_userAssignmentRemoteModel != null) {
			try {
				Class<?> clazz = _userAssignmentRemoteModel.getClass();

				Method method = clazz.getMethod("setGroupId", long.class);

				method.invoke(_userAssignmentRemoteModel, groupId);
			}
			catch (Exception e) {
				throw new UnsupportedOperationException(e);
			}
		}
	}

	@Override
	public long getCompanyId() {
		return _companyId;
	}

	@Override
	public void setCompanyId(long companyId) {
		_companyId = companyId;

		if (_userAssignmentRemoteModel != null) {
			try {
				Class<?> clazz = _userAssignmentRemoteModel.getClass();

				Method method = clazz.getMethod("setCompanyId", long.class);

				method.invoke(_userAssignmentRemoteModel, companyId);
			}
			catch (Exception e) {
				throw new UnsupportedOperationException(e);
			}
		}
	}

	@Override
	public Date getCreateDate() {
		return _createDate;
	}

	@Override
	public void setCreateDate(Date createDate) {
		_createDate = createDate;

		if (_userAssignmentRemoteModel != null) {
			try {
				Class<?> clazz = _userAssignmentRemoteModel.getClass();

				Method method = clazz.getMethod("setCreateDate", Date.class);

				method.invoke(_userAssignmentRemoteModel, createDate);
			}
			catch (Exception e) {
				throw new UnsupportedOperationException(e);
			}
		}
	}

	@Override
	public long getProcessOrderId() {
		return _processOrderId;
	}

	@Override
	public void setProcessOrderId(long processOrderId) {
		_processOrderId = processOrderId;

		if (_userAssignmentRemoteModel != null) {
			try {
				Class<?> clazz = _userAssignmentRemoteModel.getClass();

				Method method = clazz.getMethod("setProcessOrderId", long.class);

				method.invoke(_userAssignmentRemoteModel, processOrderId);
			}
			catch (Exception e) {
				throw new UnsupportedOperationException(e);
			}
		}
	}

	@Override
	public long getDossierStepId() {
		return _dossierStepId;
	}

	@Override
	public void setDossierStepId(long dossierStepId) {
		_dossierStepId = dossierStepId;

		if (_userAssignmentRemoteModel != null) {
			try {
				Class<?> clazz = _userAssignmentRemoteModel.getClass();

				Method method = clazz.getMethod("setDossierStepId", long.class);

				method.invoke(_userAssignmentRemoteModel, dossierStepId);
			}
			catch (Exception e) {
				throw new UnsupportedOperationException(e);
			}
		}
	}

	@Override
	public long getAssignToUserId() {
		return _assignToUserId;
	}

	@Override
	public void setAssignToUserId(long assignToUserId) {
		_assignToUserId = assignToUserId;

		if (_userAssignmentRemoteModel != null) {
			try {
				Class<?> clazz = _userAssignmentRemoteModel.getClass();

				Method method = clazz.getMethod("setAssignToUserId", long.class);

				method.invoke(_userAssignmentRemoteModel, assignToUserId);
			}
			catch (Exception e) {
				throw new UnsupportedOperationException(e);
			}
		}
	}

	@Override
	public String getAssignToUserUuid() throws SystemException {
		return PortalUtil.getUserValue(getAssignToUserId(), "uuid",
			_assignToUserUuid);
	}

	@Override
	public void setAssignToUserUuid(String assignToUserUuid) {
		_assignToUserUuid = assignToUserUuid;
	}

	public BaseModel<?> getUserAssignmentRemoteModel() {
		return _userAssignmentRemoteModel;
	}

	public void setUserAssignmentRemoteModel(
		BaseModel<?> userAssignmentRemoteModel) {
		_userAssignmentRemoteModel = userAssignmentRemoteModel;
	}

	public Object invokeOnRemoteModel(String methodName,
		Class<?>[] parameterTypes, Object[] parameterValues)
		throws Exception {
		Object[] remoteParameterValues = new Object[parameterValues.length];

		for (int i = 0; i < parameterValues.length; i++) {
			if (parameterValues[i] != null) {
				remoteParameterValues[i] = ClpSerializer.translateInput(parameterValues[i]);
			}
		}

		Class<?> remoteModelClass = _userAssignmentRemoteModel.getClass();

		ClassLoader remoteModelClassLoader = remoteModelClass.getClassLoader();

		Class<?>[] remoteParameterTypes = new Class[parameterTypes.length];

		for (int i = 0; i < parameterTypes.length; i++) {
			if (parameterTypes[i].isPrimitive()) {
				remoteParameterTypes[i] = parameterTypes[i];
			}
			else {
				String parameterTypeName = parameterTypes[i].getName();

				remoteParameterTypes[i] = remoteModelClassLoader.loadClass(parameterTypeName);
			}
		}

		Method method = remoteModelClass.getMethod(methodName,
				remoteParameterTypes);

		Object returnValue = method.invoke(_userAssignmentRemoteModel,
				remoteParameterValues);

		if (returnValue != null) {
			returnValue = ClpSerializer.translateOutput(returnValue);
		}

		return returnValue;
	}

	@Override
	public void persist() throws SystemException {
		if (this.isNew()) {
			UserAssignmentLocalServiceUtil.addUserAssignment(this);
		}
		else {
			UserAssignmentLocalServiceUtil.updateUserAssignment(this);
		}
	}

	@Override
	public UserAssignment toEscapedModel() {
		return (UserAssignment)ProxyUtil.newProxyInstance(UserAssignment.class.getClassLoader(),
			new Class[] { UserAssignment.class },
			new AutoEscapeBeanHandler(this));
	}

	@Override
	public Object clone() {
		UserAssignmentClp clone = new UserAssignmentClp();

		clone.setUserAssignmentId(getUserAssignmentId());
		clone.setUserId(getUserId());
		clone.setGroupId(getGroupId());
		clone.setCompanyId(getCompanyId());
		clone.setCreateDate(getCreateDate());
		clone.setProcessOrderId(getProcessOrderId());
		clone.setDossierStepId(getDossierStepId());
		clone.setAssignToUserId(getAssignToUserId());

		return clone;
	}

	@Override
	public int compareTo(UserAssignment userAssignment) {
		long primaryKey = userAssignment.getPrimaryKey();

		if (getPrimaryKey() < primaryKey) {
			return -1;
		}
		else if (getPrimaryKey() > primaryKey) {
			return 1;
		}
		else {
			return 0;
		}
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}

		if (!(obj instanceof UserAssignmentClp)) {
			return false;
		}

		UserAssignmentClp userAssignment = (UserAssignmentClp)obj;

		long primaryKey = userAssignment.getPrimaryKey();

		if (getPrimaryKey() == primaryKey) {
			return true;
		}
		else {
			return false;
		}
	}

	public Class<?> getClpSerializerClass() {
		return _clpSerializerClass;
	}

	@Override
	public int hashCode() {
		return (int)getPrimaryKey();
	}

	@Override
	public String toString() {
		StringBundler sb = new StringBundler(17);

		sb.append("{userAssignmentId=");
		sb.append(getUserAssignmentId());
		sb.append(", userId=");
		sb.append(getUserId());
		sb.append(", groupId=");
		sb.append(getGroupId());
		sb.append(", companyId=");
		sb.append(getCompanyId());
		sb.append(", createDate=");
		sb.append(getCreateDate());
		sb.append(", processOrderId=");
		sb.append(getProcessOrderId());
		sb.append(", dossierStepId=");
		sb.append(getDossierStepId());
		sb.append(", assignToUserId=");
		sb.append(getAssignToUserId());
		sb.append("}");

		return sb.toString();
	}

	@Override
	public String toXmlString() {
		StringBundler sb = new StringBundler(28);

		sb.append("<model><model-name>");
		sb.append("org.oep.processmgt.model.UserAssignment");
		sb.append("</model-name>");

		sb.append(
			"<column><column-name>userAssignmentId</column-name><column-value><![CDATA[");
		sb.append(getUserAssignmentId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>userId</column-name><column-value><![CDATA[");
		sb.append(getUserId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>groupId</column-name><column-value><![CDATA[");
		sb.append(getGroupId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>companyId</column-name><column-value><![CDATA[");
		sb.append(getCompanyId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>createDate</column-name><column-value><![CDATA[");
		sb.append(getCreateDate());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>processOrderId</column-name><column-value><![CDATA[");
		sb.append(getProcessOrderId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>dossierStepId</column-name><column-value><![CDATA[");
		sb.append(getDossierStepId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>assignToUserId</column-name><column-value><![CDATA[");
		sb.append(getAssignToUserId());
		sb.append("]]></column-value></column>");

		sb.append("</model>");

		return sb.toString();
	}

	private long _userAssignmentId;
	private long _userId;
	private String _userUuid;
	private long _groupId;
	private long _companyId;
	private Date _createDate;
	private long _processOrderId;
	private long _dossierStepId;
	private long _assignToUserId;
	private String _assignToUserUuid;
	private BaseModel<?> _userAssignmentRemoteModel;
	private Class<?> _clpSerializerClass = org.oep.processmgt.service.ClpSerializer.class;
}


text:
import logging

from rest_framework.decorators import api_view
from rest_framework.decorators import permission_classes
from rest_framework.decorators import renderer_classes
from rest_framework import permissions
from rest_framework import renderers as rf_renderers
from rest_framework import status
from rest_framework.response import Response
from rest_framework import viewsets

import ozpcenter.model_access as model_access
import ozpcenter.api.listing.model_access as listing_model_access
import ozpcenter.api.listing.serializers as listing_serializers
import ozpiwc.hal as hal
import ozpiwc.renderers as renderers

logger = logging.getLogger('ozp-iwc.' + str(__name__))

class ApplicationViewSet(viewsets.ViewSet):
    """
    List of applications
    """
    permission_classes = (permissions.IsAuthenticated,)
    renderer_classes = (renderers.RootResourceRenderer, rf_renderers.JSONRenderer)

    def list(self, request):
        if not hal.validate_version(request.META.get('HTTP_ACCEPT')):
            return Response('Invalid version requested',
                status=status.HTTP_406_NOT_ACCEPTABLE)

        listing_root_url = hal.get_abs_url_for_iwc(request)
        profile = model_access.get_profile(request.user.username)
        data = hal.create_base_structure(request, hal.generate_content_type(
            request.accepted_media_type))
        applications = listing_model_access.get_listings(profile.user.username)
        items = []
        embedded_items = []
        for i in applications:
            item = {"href": '{0!s}listing/{1!s}/'.format(listing_root_url, i.id),
                "type": hal.generate_content_type(renderers.ApplicationResourceRenderer.media_type)}
            items.append(item)

            embedded = {'_links': {'self': item}}
            embedded['id'] = i.id
            embedded['title'] = i.title
            embedded['unique_name'] = i.unique_name

            intents = []
            for j in i.intents.all():
                intent = {'action': j.action, 'media_type': j.media_type,
                'label': j.label, 'icon_id': j.icon.id}
                intents.append(intent)

            embedded['intents'] = intents
            embedded_items.append(embedded)

        data['_links']['item'] = items
        data['_embedded']['item'] = embedded_items

        return Response(data)

class ApplicationListingViewSet(viewsets.ViewSet):
    """
    Single application
    """
    permission_classes = (permissions.IsAuthenticated,)
    renderer_classes = (renderers.RootResourceRenderer, rf_renderers.JSONRenderer)

    def retrieve(self, request, pk):
        if not hal.validate_version(request.META.get('HTTP_ACCEPT')):
            return Response('Invalid version requested',
                status=status.HTTP_406_NOT_ACCEPTABLE)

        listing_root_url = hal.get_abs_url_for_iwc(request)  # flake8: noqa TODO: Is Necessary? - Variable not being used in method
        profile = model_access.get_profile(request.user.username)

        # TODO: only include the fields that are necessary for IWC. This will also
        # allow us to sever ties with ozpcenter.api.listing.serializers

        # This minimal definition of what a Listing object must have should be
        # advertised so that others can use IWC with their own systems
        queryset = listing_model_access.get_listing_by_id(profile.user.username, pk)
        if not queryset:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = listing_serializers.ListingSerializer(queryset,
                context={'request': request})
        data = serializer.data
        data = hal.add_hal_structure(data, request, hal.generate_content_type(
            request.accepted_media_type))

        return Response(data)

class SystemViewSet(viewsets.ViewSet):
    """
    System view - TODO
    """
    permission_classes = (permissions.IsAuthenticated,)
    renderer_classes = (renderers.RootResourceRenderer, rf_renderers.JSONRenderer)

    def list(self, request):
        if not hal.validate_version(request.META.get('HTTP_ACCEPT')):
            return Response('Invalid version requested',
                status=status.HTTP_406_NOT_ACCEPTABLE)

        listing_root_url = hal.get_abs_url_for_iwc(request)  # flake8: noqa TODO: Is Necessary? - Variable not being used in method
        profile = model_access.get_profile(request.user.username)  # flake8: noqa TODO: Is Necessary? - Variable not being used in method

        data = hal.create_base_structure(request, hal.generate_content_type(
            request.accepted_media_type))
        data["version"] = "1.0"
        data["name"] = "TBD"
        return Response(data)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/accountActivity_linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".AccountActivity" >

    <TableLayout
        android:id="@+id/accountActivity_tableInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TableRow
            android:id="@+id/addBank_tableRowNameHeader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/accountActivity_textViewNameTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/account_name" />

            <TextView
                android:id="@+id/accountActivity_textViewName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/textViewDefaultText" />
        </TableRow>

        <TableRow
            android:id="@+id/addBank_tableRowName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/accountActivity_textViewNicknameTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/account_nickname" />

            <TextView
                android:id="@+id/accountActivity_textViewNickname"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/textViewDefaultText" />
        </TableRow>

        <TableRow
            android:id="@+id/addBank_tableRowPhoneHeader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/accountActivity_textViewCurrentBalTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/account_current_bal" />

            <TextView
                android:id="@+id/accountActivity_textViewCurrentBal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/textViewDefaultText" />
        </TableRow>

        <TableRow
            android:id="@+id/addBank_tableRowPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/accountActivity_textViewAvailableBalTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/account_available_bal" />

            <TextView
                android:id="@+id/accountActivity_textViewAvailableBal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/textViewDefaultText" />
        </TableRow>

        <TableRow
            android:id="@+id/accountActivity_tableRowTransactionsFrom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/accountActivity_textViewTransactionsFrom"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/account_transactions_from" />

            <Spinner
                android:id="@+id/accountActivity_spinnerFrom"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </TableRow>

        <TableRow
            android:id="@+id/accountActivity_tableRowSortBy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/accountActivity_textViewSortBy"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/account_sort_by" />

            <Spinner
                android:id="@+id/accountActivity_spinnerSortBy"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </TableRow>

        <TableRow
            android:id="@+id/accountActivity_tableRowNoTransactions"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/accountActivity_textViewNoTransactions"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/account_no_transactions" />
        </TableRow>
    </TableLayout>

    <ExpandableListView
        android:id="@+id/accountActivity_expandableListView"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >
    </ExpandableListView>

</LinearLayout>


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('article', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='article',
            name='leedindex',
            field=models.IntegerField(null=True),
        ),
    ]


text:
package com.ardic.android.iot.hwnodeapptemplate.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.ardic.android.iot.hwnodeapptemplate.service.WifiNodeService;

/**
 * Created by yavuz.erzurumlu on 04.11.2016.
 */

public class StartReceiver extends BroadcastReceiver {
    private static final String TAG = StartReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Boot completed.Starting service...");
        context.startService(new Intent(context, WifiNodeService.class));
    }
}


text:
'''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class TraderateAddRequest(RestApi):
	def __init__(self,domain='gw.api.taobao.com',port=80):
		RestApi.__init__(self,domain, port)
		self.anony = None
		self.content = None
		self.oid = None
		self.result = None
		self.role = None
		self.tid = None

	def getapiname(self):
		return 'taobao.traderate.add'


text:
<?php

// /srv/www/zestfule/vendor/bundles/Symfony/Bundle/WebConfiguratorBundle/Resources/views/steps.html.twig
return array (
);


text:
#include <string.h>
#include "stm320Fxx_ksk.h"

static uint32_t CP_CalCntr = 0;
static uint32_t CP_Index = 0;
static uint32_t CB_Cal_Count[6];
static volatile uint32_t CB_Res = 0;
static volatile uint32_t CP_Error = 0;

#define CP_THRESHOLD_LEVEL  3000

GPIO_TypeDef* GPIO_PORT[LEDn] = {LED1_GPIO_PORT, LED2_GPIO_PORT, LED3_GPIO_PORT,
                                 LED4_GPIO_PORT};
const uint16_t GPIO_PIN[LEDn] = {LED1_PIN, LED2_PIN, LED3_PIN,
                                 LED4_PIN};
const uint32_t GPIO_CLK[LEDn] = {LED1_GPIO_CLK, LED2_GPIO_CLK, LED3_GPIO_CLK,
                                 LED4_GPIO_CLK};

GPIO_TypeDef* BUTTON_PORT[BUTTONn] = {USR1_BUTTON_GPIO_PORT, USR2_BUTTON_GPIO_PORT};

const uint16_t BUTTON_PIN[BUTTONn] = {USR1_BUTTON_PIN, USR2_BUTTON_PIN};

const uint32_t BUTTON_CLK[BUTTONn] = {USR1_BUTTON_GPIO_CLK, USR2_BUTTON_GPIO_CLK};

const uint16_t BUTTON_EXTI_LINE[BUTTONn] = {USR1_BUTTON_EXTI_LINE,
                                            USR2_BUTTON_EXTI_LINE
																						};

const uint16_t BUTTON_PORT_SOURCE[BUTTONn] = {USR1_BUTTON_EXTI_PORT_SOURCE,
                                              USR2_BUTTON_EXTI_PORT_SOURCE
                                             };

const uint16_t BUTTON_PIN_SOURCE[BUTTONn] = {USR1_BUTTON_EXTI_PIN_SOURCE,
                                             USR2_BUTTON_EXTI_PIN_SOURCE
                                            };

const uint16_t BUTTON_IRQn[BUTTONn] = {USR1_BUTTON_EXTI_IRQn, USR2_BUTTON_EXTI_IRQn};

USART_TypeDef* COM_USART[COMn] = {RS232_COM1, UXT_COM2};

const uint32_t COM_USART_CLK[COMn] = {RS232_COM1_CLK, UXT_COM2_CLK};

GPIO_TypeDef* COM_TX_PORT[COMn] = {RS232_COM1_TX_GPIO_PORT, UXT_COM2_TX_GPIO_PORT};

GPIO_TypeDef* COM_RX_PORT[COMn] = {RS232_COM1_RX_GPIO_PORT, UXT_COM2_RX_GPIO_PORT};

const uint32_t COM_TX_PORT_CLK[COMn] = {RS232_COM1_TX_GPIO_CLK, UXT_COM2_TX_GPIO_CLK};

const uint32_t COM_RX_PORT_CLK[COMn] = {RS232_COM1_RX_GPIO_CLK, UXT_COM2_RX_GPIO_CLK};

const uint16_t COM_TX_PIN[COMn] = {RS232_COM1_TX_PIN, UXT_COM2_TX_PIN};

const uint16_t COM_RX_PIN[COMn] = {RS232_COM1_RX_PIN, UXT_COM2_RX_PIN};

const uint16_t COM_TX_PIN_SOURCE[COMn] = {RS232_COM1_TX_SOURCE, UXT_COM2_TX_SOURCE};

const uint16_t COM_RX_PIN_SOURCE[COMn] = {RS232_COM1_RX_SOURCE, UXT_COM2_RX_SOURCE};

const uint16_t COM_TX_AF[COMn] = {RS232_COM1_TX_AF, UXT_COM2_TX_AF};

const uint16_t COM_RX_AF[COMn] = {RS232_COM1_RX_AF, UXT_COM2_RX_AF};

const uint8_t COM_FLOW_CTRL[COMn] = {1, 0};

GPIO_TypeDef* COM_CTS_PORT[COMn] = {RS232_COM1_CTS_GPIO_PORT};

const uint32_t COM_CTS_PORT_CLK[COMn] = {RS232_COM1_CTS_GPIO_CLK};

const uint16_t COM_CTS_PIN[COMn] = {RS232_COM1_CTS_PIN};

const uint16_t COM_CTS_PIN_SOURCE[COMn] = {RS232_COM1_CTS_SOURCE};

const uint16_t COM_CTS_AF[COMn] = {RS232_COM1_CTS_AF};

GPIO_TypeDef* COM_RTS_PORT[COMn] = {RS232_COM1_RTS_GPIO_PORT};

const uint32_t COM_RTS_PORT_CLK[COMn] = {RS232_COM1_RTS_GPIO_CLK};

const uint16_t COM_RTS_PIN[COMn] = {RS232_COM1_RTS_PIN};

const uint16_t COM_RTS_PIN_SOURCE[COMn] = {RS232_COM1_RTS_SOURCE};

const uint16_t COM_RTS_AF[COMn] = {RS232_COM1_RTS_AF};

/**
  * @brief  Configures LED GPIO.
  * @param  Led: Specifies the Led to be configured.
  *   This parameter can be one of following parameters:
  *     @arg LED1
  *     @arg LED2
  *     @arg LED3
  *     @arg LED4
  * @retval None
  */
void LEDInit(Led_TypeDef Led)
{
  GPIO_InitTypeDef  GPIO_InitStructure;

  /* Enable the GPIO_LED Clock */
  RCC_AHBPeriphClockCmd(GPIO_CLK[Led], ENABLE);

  /* Configure the GPIO_LED pin */
  GPIO_InitStructure.GPIO_Pin = GPIO_PIN[Led];
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIO_PORT[Led], &GPIO_InitStructure);
  GPIO_PORT[Led]->BSRR = GPIO_PIN[Led];
}

/**
  * @brief  Turns selected LED On.
  * @param  Led: Specifies the Led to be set on.
  *   This parameter can be one of following parameters:
  *     @arg LED1
  *     @arg LED2
  *     @arg LED3
  *     @arg LED4
  * @retval None
  */
void LEDOn(Led_TypeDef Led)
{
  GPIO_PORT[Led]->BRR = GPIO_PIN[Led];
}

/**
  * @brief  Turns selected LED Off.
  * @param  Led: Specifies the Led to be set off.
  *   This parameter can be one of following parameters:
  *     @arg LED1
  *     @arg LED2
  *     @arg LED3
  *     @arg LED4
  * @retval None
  */
void LEDOff(Led_TypeDef Led)
{
  GPIO_PORT[Led]->BSRR = GPIO_PIN[Led];
}

/**
  * @brief  Toggles the selected LED.
  * @param  Led: Specifies the Led to be toggled.
  *   This parameter can be one of following parameters:
  *     @arg LED1
  *     @arg LED2
  *     @arg LED3
  *     @arg LED4
  * @retval None
  */
void LEDToggle(Led_TypeDef Led)
{
  GPIO_PORT[Led]->ODR ^= GPIO_PIN[Led];
}

/**
  * @brief  Configures Button GPIO and EXTI Line.
  * @param  Button: Specifies the Button to be configured.
  *   This parameter can be one of following parameters:
  *     @arg USR1_BUTTON: User Push Button 1
  *     @arg USR2_BUTTON: User Push Button 2
  * @param  Button_Mode: Specifies Button mode.
  *   This parameter can be one of following parameters:
  *     @arg BUTTON_MODE_GPIO: Button will be used as simple IO
  *     @arg BUTTON_MODE_EXTI: Button will be connected to EXTI line with interrupt
  *                     generation capability
  * @retval None
  */
void PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  EXTI_InitTypeDef EXTI_InitStructure;
  NVIC_InitTypeDef NVIC_InitStructure;

  /* Enable the BUTTON Clock */
  RCC_AHBPeriphClockCmd(BUTTON_CLK[Button], ENABLE);
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

  /* Configure Button pin as input */
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Pin = BUTTON_PIN[Button];
  GPIO_Init(BUTTON_PORT[Button], &GPIO_InitStructure);

  if (Button_Mode == BUTTON_MODE_EXTI)
  {
    /* Connect Button EXTI Line to Button GPIO Pin */
    SYSCFG_EXTILineConfig(BUTTON_PORT_SOURCE[Button], BUTTON_PIN_SOURCE[Button]);

    /* Configure Button EXTI line */
    EXTI_InitStructure.EXTI_Line = BUTTON_EXTI_LINE[Button];
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStructure);

    /* Enable and set Button EXTI Interrupt to the lowest priority */
    NVIC_InitStructure.NVIC_IRQChannel = BUTTON_IRQn[Button];
    NVIC_InitStructure.NVIC_IRQChannelPriority = 0x03;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

    NVIC_Init(&NVIC_InitStructure);
  }
}

/**
  * @brief  Returns the selected Button state.
  * @param  Button: Specifies the Button to be checked.
  *   This parameter can be one of following parameters:
  *     @arg USR1_BUTTON: User Push Button 1
  *     @arg USR2_BUTTON: User Push Button 2
  * @retval The Button GPIO pin value.
  */
uint32_t PBGetState(Button_TypeDef Button)
{
  /* There is no Wakeup button on STM320518-EVAL. */
  return GPIO_ReadInputDataBit(BUTTON_PORT[Button], BUTTON_PIN[Button]);
}

/**
  * @brief  Configures COM port.
  * @param  COM: Specifies the COM port to be configured.
  *   This parameter can be one of following parameters:
  *     @arg COM1
  *     @arg COM2
  * @param  USART_InitStruct: pointer to a USART_InitTypeDef structure that
  *   contains the configuration information for the specified USART peripheral.
  * @retval None
  */
void COMInit(COM_TypeDef COM, USART_InitTypeDef* USART_InitStruct)
{
  GPIO_InitTypeDef GPIO_InitStructure;

  /* Enable GPIO clock */
  RCC_AHBPeriphClockCmd(COM_TX_PORT_CLK[COM] | COM_RX_PORT_CLK[COM], ENABLE);

  if(COM1 == COM)
  {
    /* Enable USART clock */
    RCC_APB2PeriphClockCmd(COM_USART_CLK[COM], ENABLE);
  }
  else
  {
    /* Enable USART clock */
    RCC_APB1PeriphClockCmd(COM_USART_CLK[COM], ENABLE);
  }

	if(COM_FLOW_CTRL[COM])
	{
	  RCC_AHBPeriphClockCmd(COM_CTS_PORT_CLK[COM] | COM_RTS_PORT_CLK[COM], ENABLE);
	  /* Connect PXx to USARTx_CTS */
	  GPIO_PinAFConfig(COM_CTS_PORT[COM], COM_CTS_PIN_SOURCE[COM], COM_CTS_AF[COM]);
	  /* Connect PXx to USARTx_RTS */
	  GPIO_PinAFConfig(COM_RTS_PORT[COM], COM_RTS_PIN_SOURCE[COM], COM_RTS_AF[COM]);

	  /* Configure USART CTS as alternate function push-pull */
	  GPIO_InitStructure.GPIO_Pin = COM_CTS_PIN[COM];
	  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	  GPIO_Init(COM_TX_PORT[COM], &GPIO_InitStructure);

	  /* Configure USART RTS as alternate function push-pull */
	  GPIO_InitStructure.GPIO_Pin = COM_RTS_PIN[COM];
	  GPIO_Init(COM_RX_PORT[COM], &GPIO_InitStructure);

	}

  /* Connect PXx to USARTx_Tx */
  GPIO_PinAFConfig(COM_TX_PORT[COM], COM_TX_PIN_SOURCE[COM], COM_TX_AF[COM]);

  /* Connect PXx to USARTx_Rx */
  GPIO_PinAFConfig(COM_RX_PORT[COM], COM_RX_PIN_SOURCE[COM], COM_RX_AF[COM]);

  /* Configure USART Tx as alternate function push-pull */
  GPIO_InitStructure.GPIO_Pin = COM_TX_PIN[COM];
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_Init(COM_TX_PORT[COM], &GPIO_InitStructure);

  /* Configure USART Rx as alternate function push-pull */
  GPIO_InitStructure.GPIO_Pin = COM_RX_PIN[COM];
  GPIO_Init(COM_RX_PORT[COM], &GPIO_InitStructure);

  /* USART configuration */
  USART_Init(COM_USART[COM], USART_InitStruct);

  /* Enable USART */
  USART_Cmd(COM_USART[COM], ENABLE);
}

/**
  * @brief  Initializes the ACC_I2C..
  * @param  None
  * @retval None
  */
void Acc_LowLevel_Init(void)
{
  GPIO_InitTypeDef  GPIO_InitStructure;
  EXTI_InitTypeDef  EXTI_InitStructure;
  NVIC_InitTypeDef  NVIC_InitStructure;

  RCC_AHBPeriphClockCmd(ACC_INT_GPIO_CLK, ENABLE);
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

  /*!< Configure ACC_INT pins: input */
  GPIO_InitStructure.GPIO_Pin = ACC_INT_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(ACC_INT_GPIO_PORT, &GPIO_InitStructure);

  SYSCFG_EXTILineConfig(ACC_INT_EXTI_PORT_SOURCE, ACC_INT_EXTI_PIN_SOURCE);

  /* Configure ACC INT line */
  EXTI_InitStructure.EXTI_Line = ACC_INT_EXTI_LINE;
  EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
  EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
  EXTI_InitStructure.EXTI_LineCmd = ENABLE;
  EXTI_Init(&EXTI_InitStructure);

  /* Enable and set Button EXTI Interrupt to the lowest priority */
  NVIC_InitStructure.NVIC_IRQChannel = ACC_INT_EXTI_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 0x03;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

  NVIC_Init(&NVIC_InitStructure);
}

/**
  * @brief  Initializes the UXT_I2C..
  * @param  None
  * @retval None
  */
void UXT_I2C_LowLevel_Init(void)
{
  GPIO_InitTypeDef  GPIO_InitStructure;

  /*!< UXT_I2C Periph clock enable */
  RCC_APB1PeriphClockCmd(UXT_I2C_CLK, ENABLE);

  /*!< UXT_I2C_SCL_GPIO_CLK, UXT_I2C_SDA_GPIO_CLK Periph clock enable */
  RCC_AHBPeriphClockCmd(UXT_I2C_SCL_GPIO_CLK | UXT_I2C_SDA_GPIO_CLK, ENABLE);

  /* Connect PXx to I2C_SCL */
  GPIO_PinAFConfig(UXT_I2C_SCL_GPIO_PORT, UXT_I2C_SCL_SOURCE, UXT_I2C_SCL_AF);

  /* Connect PXx to I2C_SDA */
  GPIO_PinAFConfig(UXT_I2C_SDA_GPIO_PORT, UXT_I2C_SDA_SOURCE, UXT_I2C_SDA_AF);

  /*!< Configure UXT_I2C pins: SCL */
  GPIO_InitStructure.GPIO_Pin = UXT_I2C_SCL_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_NOPULL;
  GPIO_Init(UXT_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);

  /*!< Configure UXT_I2C pins: SDA */
  GPIO_InitStructure.GPIO_Pin = UXT_I2C_SDA_PIN;
  GPIO_Init(UXT_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
}

/**
  * @brief  Initializes the UXT SPI and put it into
  * @param  None
  * @retval None
  */
void UXT_SPI_LowLevel_Init(void)
{
  GPIO_InitTypeDef  GPIO_InitStructure;
  SPI_InitTypeDef   SPI_InitStructure;

  /*!< UXT_SPI_CS_GPIO, UXT_SPI_MOSI_GPIO, UXT_SPI_MISO_GPIO,
       and UXT_SPI_SCK_GPIO Periph clock enable */
  RCC_AHBPeriphClockCmd(UXT_SPI_SCK_GPIO_CLK | UXT_SPI_MISO_GPIO_CLK | UXT_SPI_MOSI_GPIO_CLK |
                        UXT_CS_GPIO_CLK , ENABLE);

  /*!< UXT_SPI Periph clock enable */
  RCC_APB2PeriphClockCmd(UXT_SPI_CLK, ENABLE);

  /*!< Configure UXT_SPI pins: SCK */
  GPIO_InitStructure.GPIO_Pin = UXT_SPI_SCK_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
  GPIO_Init(UXT_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);

  /*!< Configure UXT_SPI pins: MISO */
  GPIO_InitStructure.GPIO_Pin = UXT_SPI_MISO_PIN;
  GPIO_Init(UXT_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);

  /*!< Configure UXT_SPI pins: MOSI */
  GPIO_InitStructure.GPIO_Pin = UXT_SPI_MOSI_PIN;
  GPIO_Init(UXT_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);

  /*!< Configure UXT_SPI_CS_PIN pin: UXT Card CS pin */
  GPIO_InitStructure.GPIO_Pin = UXT_CS_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(UXT_CS_GPIO_PORT, &GPIO_InitStructure);

  /* Connect PXx to UXT_SPI_SCK */
  GPIO_PinAFConfig(UXT_SPI_SCK_GPIO_PORT, UXT_SPI_SCK_SOURCE, UXT_SPI_SCK_AF);

  /* Connect PXx to UXT_SPI_MISO */
  GPIO_PinAFConfig(UXT_SPI_MISO_GPIO_PORT, UXT_SPI_MISO_SOURCE, UXT_SPI_MISO_AF);

  /* Connect PXx to UXT_SPI_MOSI */
  GPIO_PinAFConfig(UXT_SPI_MOSI_GPIO_PORT, UXT_SPI_MOSI_SOURCE, UXT_SPI_MOSI_AF);

  /*!< UXT_SPI Config */
  SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
  SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
  SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
  SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
  SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;

  SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
  SPI_InitStructure.SPI_CRCPolynomial = 7;
  SPI_Init(UXT_SPI, &SPI_InitStructure);

  SPI_RxFIFOThresholdConfig(UXT_SPI, SPI_RxFIFOThreshold_QF);

  SPI_Cmd(UXT_SPI, ENABLE); /*!< UXT_SPI enable */
}

/**
  * @brief  Initializes the UXT PWR control
  * @param  None
  * @retval None
  */
void UXT_PWR_Init(void)
{
  GPIO_InitTypeDef  GPIO_InitStructure;

  /* Enable the PWR Port Clock */
  RCC_AHBPeriphClockCmd(UXT_PWR_GPIO_CLK, ENABLE);

  /* Configure the PWR pin */
  GPIO_InitStructure.GPIO_Pin = UXT_PWR_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(UXT_PWR_GPIO_PORT, &GPIO_InitStructure);
  UXT_PWR_GPIO_PORT->BSRR = UXT_PWR_PIN;
}

/**
  * @brief  Enable/disable the UXT PWR
  * @param  Pwr
  * @retval None
  */
void UXT_PWR_Ctrl(PWR_CtrlDef Pwr)
{
	if(PWR_OFF == Pwr)
	{
  	UXT_PWR_GPIO_PORT->BSRR = UXT_PWR_PIN;
	}
	else
	{
  	UXT_PWR_GPIO_PORT->BRR = UXT_PWR_PIN;
	}
}

/**
  * @brief  Initializes the CEC_I2C..
  * @param  None
  * @retval None
  */
void CEC_I2C_LowLevel_Init(void)
{
  GPIO_InitTypeDef  GPIO_InitStructure;

  /*!< CEC_I2C Periph clock enable */
  RCC_APB1PeriphClockCmd(CEC_I2C_CLK, ENABLE);

  /* Configure the I2C clock source. The clock is derived from the HSI */
  RCC_I2CCLKConfig(RCC_I2C1CLK_HSI);

  /*!< CEC_I2C_SCL_GPIO_CLK, CEC_I2C_SDA_GPIO_CLK Periph clock enable */
  RCC_AHBPeriphClockCmd(CEC_I2C_SCL_GPIO_CLK | CEC_I2C_SDA_GPIO_CLK, ENABLE);

  /* Connect PXx to I2C_SCL */
  GPIO_PinAFConfig(CEC_I2C_SCL_GPIO_PORT, CEC_I2C_SCL_SOURCE, CEC_I2C_SCL_AF);

  /* Connect PXx to I2C_SDA */
  GPIO_PinAFConfig(CEC_I2C_SDA_GPIO_PORT, CEC_I2C_SDA_SOURCE, CEC_I2C_SDA_AF);

  /*!< Configure CEC_I2C pins: SCL */
  GPIO_InitStructure.GPIO_Pin = CEC_I2C_SCL_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_NOPULL;
  GPIO_Init(CEC_I2C_SCL_GPIO_PORT, &GPIO_InitStructure);

  /*!< Configure CEC_I2C pins: SDA */
  GPIO_InitStructure.GPIO_Pin = CEC_I2C_SDA_PIN;
  GPIO_Init(CEC_I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
}

/**
  * @brief  Initializes the DAT ...
  * @param  None
  * @retval None
  */
void AudioOut_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;

  /* DAC Periph clock enable */
  RCC_APB1PeriphClockCmd(DAC_CLK, ENABLE);

  /* GPIOA clock enable */
  RCC_AHBPeriphClockCmd(AUDIO_OUT_GPIO_CLK, ENABLE);

  /* Configure PA.04 (DAC_OUT1) as analog */
  GPIO_InitStructure.GPIO_Pin =  AUDIO_OUT_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(AUDIO_OUT_GPIO_PORT, &GPIO_InitStructure);

  DAC_DeInit();
}

/**
  * @brief  Initializes the ADC TRIM ...
  * @param  None
  * @retval None
  */
void Trim_Init(void)
{
ADC_InitTypeDef          ADC_InitStructure;
GPIO_InitTypeDef         GPIO_InitStructure;

  /* TRIM GPIO Periph clock enable */
  RCC_AHBPeriphClockCmd(TRIM_GPIO_CLK, ENABLE);

  /* TRIM ADC Periph clock enable */
  RCC_APB2PeriphClockCmd(TRIM_ADC_CLK, ENABLE);

  /* Configure TRIM as analog input */
  GPIO_InitStructure.GPIO_Pin = TRIM_PIN ;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
  GPIO_Init(TRIM_GPIO_PORT, &GPIO_InitStructure);

 	/* ADC DeInit */
  ADC_DeInit(TRIM_ADC);

  /* Initialize ADC structure */
  ADC_StructInit(&ADC_InitStructure);

  /* Configure the TRIM ADC in a 12 bits resolutuion */
  ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
  ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
  ADC_InitStructure.ADC_ExternalTrigConv =  ADC_ExternalTrigConv_T1_TRGO;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
  ADC_Init(TRIM_ADC, &ADC_InitStructure);

  /* Convert the TRIM Channel with 239.5 Cycles as sampling time */
  ADC_ChannelConfig(TRIM_ADC, TRIM_ADC_CHANNEL, ADC_SampleTime_239_5Cycles);

  /* ADC Calibration */
  ADC_GetCalibrationFactor(TRIM_ADC);

  /* Enable ADCperipheral[PerIdx] */
  ADC_Cmd(TRIM_ADC, ENABLE);

  /* Wait the ADCEN falg */
  while(!ADC_GetFlagStatus(TRIM_ADC, ADC_FLAG_ADEN));
}

/**
  * @brief  Initializes the ADC Distance sensor ...
  * @param  None
  * @retval None
  */
void Dist_Init(void)
{
ADC_InitTypeDef          ADC_InitStructure;
GPIO_InitTypeDef         GPIO_InitStructure;

  /* DIST GPIO Periph clock enable */
  RCC_AHBPeriphClockCmd(DIST_GPIO_CLK, ENABLE);

  /* DIST ADC Periph clock enable */
  RCC_APB2PeriphClockCmd(DIST_ADC_CLK, ENABLE);

  /* Configure DIST as analog input */
  GPIO_InitStructure.GPIO_Pin = DIST_PIN ;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
  GPIO_Init(DIST_GPIO_PORT, &GPIO_InitStructure);

 	/* ADC DeInit */
  ADC_DeInit(DIST_ADC);

  /* Initialize ADC structure */
  ADC_StructInit(&ADC_InitStructure);

  /* Configure the TRIM ADC in a 12 bits resolutuion */
  ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
  ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
  ADC_InitStructure.ADC_ExternalTrigConv =  ADC_ExternalTrigConv_T1_TRGO;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
  ADC_Init(DIST_ADC, &ADC_InitStructure);

  /* Convert the DIST Channel with 239.5 Cycles as sampling time */
  ADC_ChannelConfig(DIST_ADC, DIST_ADC_CHANNEL, ADC_SampleTime_239_5Cycles);

  /* ADC Calibration */
  ADC_GetCalibrationFactor(DIST_ADC);

  /* Enable ADCperipheral[PerIdx] */
  ADC_Cmd(DIST_ADC, ENABLE);

  /* Wait the ADCEN falg */
  while(!ADC_GetFlagStatus(DIST_ADC, ADC_FLAG_ADEN));
}

/**
  * @brief  Initializes the ADC Light sensor ...
  * @param  None
  * @retval None
  */
void Light_Init(void)
{
ADC_InitTypeDef          ADC_InitStructure;
GPIO_InitTypeDef         GPIO_InitStructure;

  /* LIGHT GPIO Periph clock enable */
  RCC_AHBPeriphClockCmd(LIGHT_GPIO_CLK | LIGHT_PWR_GPIO_CLK, ENABLE);

  /* LIGHT ADC Periph clock enable */
  RCC_APB2PeriphClockCmd(LIGHT_ADC_CLK, ENABLE);

  /* Configure LIGHT as analog input */
  GPIO_InitStructure.GPIO_Pin = LIGHT_PIN ;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
  GPIO_Init(LIGHT_GPIO_PORT, &GPIO_InitStructure);

  /* Configure LIGHT_PWR_PIN pin: Light sensor shutdown pin */
  GPIO_InitStructure.GPIO_Pin = LIGHT_PWR_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(LIGHT_PWR_GPIO_PORT, &GPIO_InitStructure);
  LIGHT_PWR_GPIO_PORT->BSRR = LIGHT_PWR_PIN;

	/* ADC DeInit */
  ADC_DeInit(LIGHT_ADC);

  /* Initialize ADC structure */
  ADC_StructInit(&ADC_InitStructure);

  /* Configure the LIGHT ADC in a 12 bits resolutuion */
  ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
  ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
  ADC_InitStructure.ADC_ExternalTrigConv =  ADC_ExternalTrigConv_T1_TRGO;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
  ADC_Init(LIGHT_ADC, &ADC_InitStructure);

  /* Convert the LIGHT Channel with 239.5 Cycles as sampling time */
  ADC_ChannelConfig(LIGHT_ADC, LIGHT_ADC_CHANNEL, ADC_SampleTime_239_5Cycles);

  /* ADC Calibration */
  ADC_GetCalibrationFactor(LIGHT_ADC);

  /* Enable ADCperipheral[PerIdx] */
  ADC_Cmd(LIGHT_ADC, ENABLE);

  /* Wait the ADCEN falg */
  while(!ADC_GetFlagStatus(LIGHT_ADC, ADC_FLAG_ADEN));
}

/**
  * @brief  Light sensor power control ...
  * @param  Pwr
  * @retval None
  */
void Light_Ctrl(PWR_CtrlDef Pwr)
{
	if(PWR_OFF == Pwr)
	{
  	LIGHT_PWR_GPIO_PORT->BSRR = LIGHT_PWR_PIN;
	}
	else
	{
  	LIGHT_PWR_GPIO_PORT->BRR = LIGHT_PWR_PIN;
	}
}

/**
  * @brief  Touch sensing buttons calibration ...
  * @param  None
  * @retval uint32_t 0 - pass 1 - fault
  */
uint32_t CP_Calibrate(void)
{
  uint32_t status;
  CP_CalCntr = 0;
  memset(CB_Cal_Count,0,sizeof(CB_Cal_Count));
  CP_CalCntr = 8;
  while(CP_CalCntr);
  status = CB_GetStatus();
  if(!status)
  {
    // calibration pass
    for(int i = 0; i < sizeof(CB_Cal_Count)/sizeof(CB_Cal_Count[0]); i++)
    {
      CB_Cal_Count[i] /= 8+3;
    }
  }
  return status;
}

/**
  * @brief  Touch sensing buttons initialization ...
  * @param  None
  * @retval uint32_t 0 - pass 1 - fault
  */
uint32_t CB_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  NVIC_InitTypeDef NVIC_InitStructure;
  CP_Index = 0;
  CB_Res = 0;
  CP_CalCntr = 0;
  memset(CB_Cal_Count,0,sizeof(CB_Cal_Count));

  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_TS | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC, ENABLE);

  GPIO_PinAFConfig(GPIOB, GPIO_PinSource0, GPIO_AF_3);
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource1, GPIO_AF_3);
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource2, GPIO_AF_3);
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource3, GPIO_AF_3);
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_3);
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_3);
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_3);
  GPIO_PinAFConfig(GPIOC, GPIO_PinSource5, GPIO_AF_0);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2
                              | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_6
                              | GPIO_Pin_7;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOC, &GPIO_InitStructure);

  TSC->CR  = (0xFUL << 28)  /* Charge transfer pulse high */
           | (0xFUL << 24)  /* Charge transfer pulse low */
           | (6UL   <<  5)  /* Max count value */
           ;
  /* Disable I/O hysteresis */
  TSC->IOHCR &= ~(  (0xFul << 8)  /* Group 3 */
                  | (0xFul <<16)  /* Group 5 */
                  );
  /* Enable analog switches */
  TSC->IOASCR = 0;
  TSC->IOSCR = (1UL << 8)      /* PC5 */
             | (1UL << 16)      /* PB3 */
             ;

  TSC->IOCCR = (  (1UL << (CP_Index+9))
                | (1UL << (CP_Index+17))
               );
  TSC->IOGCSR = (1UL << 2)      /* Group 3 */
              | (1UL << 4)      /* Group 5 */
              ;

  TSC->ICR = 3; /* clear EOAIE and MCEIE  */
  TSC->IER = 3; /* enable EOAIE and MCEIE  */

  /* Enable and set Button EXTI Interrupt to the lowest priority */
  NVIC_InitStructure.NVIC_IRQChannel = TS_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 0x03;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

  NVIC_Init(&NVIC_InitStructure);
  TSC->CR |= 3;

  return CP_Calibrate();
}

/**
  * @brief  Touch sensing buttons interrupt handler ...
  * @param  None
  * @retval None
  */
void CB_Handler(void)
{
  static uint32_t sycn = 0;
  if((1UL << 1) & TSC->ISR)
  {
    /* Max count error */
    TSC->ICR = 2;
    sycn = CP_CalCntr = 0;
    CP_Error = 1;
  }
  else if((1UL << 0) & TSC->ISR)
  {
    /* End of acquisition */
    TSC->ICR = 1;

    if(sycn && CP_CalCntr)
    {
      /* Calibration data collection */
      CB_Cal_Count[CP_Index]   += TSC->IOGXCR[3-1];
      CB_Cal_Count[CP_Index+3] += TSC->IOGXCR[5-1];
    }
    else
    {
      /* Buttons' state data collection */
      if( CB_Cal_Count[CP_Index] > TSC->IOGXCR[3-1])
      {
        CB_Res |= 1UL << CP_Index;
      }
      else
      {
        CB_Res &=~(1UL << CP_Index);
      }

      if(CB_Cal_Count[CP_Index+3] > TSC->IOGXCR[5-1])
      {
        CB_Res |= (1UL << (CP_Index+3));
      }
      else
      {
        CB_Res &=~(1UL << (CP_Index+3));
      }
    }
    /*  Next channel */
    if(++CP_Index >= 3)
    {
      CP_Index = 0;
      if(!sycn)
      {
        sycn = !!CP_CalCntr;
      }
      else if(CP_CalCntr)
      {
        --CP_CalCntr;
      }
      else
      {
        sycn = 0;
      }
    }
    TSC->IOCCR = ((1UL << (CP_Index+9)) | (1UL << (CP_Index+17)));
    /*  Start new acquisition*/
    TSC->CR |= 2;
  }
}

/**
  * @brief  Return state of touch buttons ...
  * @param  None
  * @retval uint32_t 0 - no touched 1- touched
  */
uint32_t CB_GetState(void)
{
	return CB_Res;
}

/**
  * @brief  Return status of touch buttons ...
  * @param  None
  * @retval uint32_t 1 - Max count error
  */
uint32_t CB_GetStatus(void)
{
  uint32_t ret = CP_Error;
	return ret;
}


text:
module PGCrypto
  class KeyManager < Hash
    def []=(key, value)
      unless value.is_a?(Key)
        value = Key.new(value)
      end
      value.name = key
      super key, value
    end
  end
end


text:
/**
 * @fileoverview Angle input field.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.FieldAngle');

goog.require('Blockly.FieldTextInput');
goog.require('goog.math');
goog.require('goog.userAgent');

/**
 * Class for an editable angle field.
 * @param {string} text The initial content of the field.
 * @param {Function=} opt_validator An optional function that is called
 *     to validate any constraints on what the user entered.  Takes the new
 *     text as an argument and returns the accepted text or null to abort
 *     the change.
 * @extends {Blockly.FieldTextInput}
 * @constructor
 */
Blockly.FieldAngle = function(text, opt_validator) {
  // Add degree symbol: "360°" (LTR) or "°360" (RTL)
  this.symbol_ = Blockly.createSvgElement('tspan', {}, null);
  this.symbol_.appendChild(document.createTextNode('\u00B0'));

  Blockly.FieldAngle.superClass_.constructor.call(this, text, opt_validator);
};
goog.inherits(Blockly.FieldAngle, Blockly.FieldTextInput);

/**
 * Round angles to the nearest 15 degrees when using mouse.
 * Set to 0 to disable rounding.
 */
Blockly.FieldAngle.ROUND = 15;

/**
 * Half the width of protractor image.
 */
Blockly.FieldAngle.HALF = 100 / 2;

/* The following two settings work together to set the behaviour of the angle
 * picker.  While many combinations are possible, two modes are typical:
 * Math mode.
 *   0 deg is right, 90 is up.  This is the style used by protractors.
 *   Blockly.FieldAngle.CLOCKWISE = false;
 *   Blockly.FieldAngle.OFFSET = 0;
 * Compass mode.
 *   0 deg is up, 90 is right.  This is the style used by maps.
 *   Blockly.FieldAngle.CLOCKWISE = true;
 *   Blockly.FieldAngle.OFFSET = 90;
 */

/**
 * Angle increases clockwise (true) or counterclockwise (false).
 */
Blockly.FieldAngle.CLOCKWISE = false;

/**
 * Offset the location of 0 degrees (and all angles) by a constant.
 * Usually either 0 (0 = right) or 90 (0 = up).
 */
Blockly.FieldAngle.OFFSET = 0;

/**
 * Maximum allowed angle before wrapping.
 * Usually either 360 (for 0 to 359.9) or 180 (for -179.9 to 180).
 */
Blockly.FieldAngle.WRAP = 360;

/**
 * Radius of protractor circle.  Slightly smaller than protractor size since
 * otherwise SVG crops off half the border at the edges.
 */
Blockly.FieldAngle.RADIUS = Blockly.FieldAngle.HALF - 1;

/**
 * Clean up this FieldAngle, as well as the inherited FieldTextInput.
 * @return {!Function} Closure to call on destruction of the WidgetDiv.
 * @private
 */
Blockly.FieldAngle.prototype.dispose_ = function() {
  var thisField = this;
  return function() {
    Blockly.FieldAngle.superClass_.dispose_.call(thisField)();
    thisField.gauge_ = null;
    if (thisField.clickWrapper_) {
      Blockly.unbindEvent_(thisField.clickWrapper_);
    }
    if (thisField.moveWrapper1_) {
      Blockly.unbindEvent_(thisField.moveWrapper1_);
    }
    if (thisField.moveWrapper2_) {
      Blockly.unbindEvent_(thisField.moveWrapper2_);
    }
  };
};

/**
 * Show the inline free-text editor on top of the text.
 * @private
 */
Blockly.FieldAngle.prototype.showEditor_ = function() {
  var noFocus =
      goog.userAgent.MOBILE || goog.userAgent.ANDROID || goog.userAgent.IPAD;
  // Mobile browsers have issues with in-line textareas (focus & keyboards).
  Blockly.FieldAngle.superClass_.showEditor_.call(this, noFocus);
  var div = Blockly.WidgetDiv.DIV;
  if (!div.firstChild) {
    // Mobile interface uses Blockly.prompt.
    return;
  }
  // Build the SVG DOM.
  var svg = Blockly.createSvgElement('svg', {
    'xmlns': 'http://www.w3.org/2000/svg',
    'xmlns:html': 'http://www.w3.org/1999/xhtml',
    'xmlns:xlink': 'http://www.w3.org/1999/xlink',
    'version': '1.1',
    'height': (Blockly.FieldAngle.HALF * 2) + 'px',
    'width': (Blockly.FieldAngle.HALF * 2) + 'px'
  }, div);
  var circle = Blockly.createSvgElement('circle', {
    'cx': Blockly.FieldAngle.HALF, 'cy': Blockly.FieldAngle.HALF,
    'r': Blockly.FieldAngle.RADIUS,
    'class': 'blocklyAngleCircle'
  }, svg);
  this.gauge_ = Blockly.createSvgElement('path',
      {'class': 'blocklyAngleGauge'}, svg);
  this.line_ = Blockly.createSvgElement('line',
      {'x1': Blockly.FieldAngle.HALF,
      'y1': Blockly.FieldAngle.HALF,
      'class': 'blocklyAngleLine'}, svg);
  // Draw markers around the edge.
  for (var angle = 0; angle < 360; angle += 15) {
    Blockly.createSvgElement('line', {
      'x1': Blockly.FieldAngle.HALF + Blockly.FieldAngle.RADIUS,
      'y1': Blockly.FieldAngle.HALF,
      'x2': Blockly.FieldAngle.HALF + Blockly.FieldAngle.RADIUS -
          (angle % 45 == 0 ? 10 : 5),
      'y2': Blockly.FieldAngle.HALF,
      'class': 'blocklyAngleMarks',
      'transform': 'rotate(' + angle + ',' +
          Blockly.FieldAngle.HALF + ',' + Blockly.FieldAngle.HALF + ')'
    }, svg);
  }
  svg.style.marginLeft = (15 - Blockly.FieldAngle.RADIUS) + 'px';

  // The angle picker is different from other fields in that it updates on
  // mousemove even if it's not in the middle of a drag.  In future we may
  // change this behavior.  For now, using bindEvent_ instead of
  // bindEventWithChecks_ allows it to work without a mousedown/touchstart.
  this.clickWrapper_ =
      Blockly.bindEvent_(svg, 'click', this, Blockly.WidgetDiv.hide);
  this.moveWrapper1_ =
      Blockly.bindEvent_(circle, 'mousemove', this, this.onMouseMove);
  this.moveWrapper2_ =
      Blockly.bindEvent_(this.gauge_, 'mousemove', this,
      this.onMouseMove);
  this.updateGraph_();
};

/**
 * Set the angle to match the mouse's position.
 * @param {!Event} e Mouse move event.
 */
Blockly.FieldAngle.prototype.onMouseMove = function(e) {
  var bBox = this.gauge_.ownerSVGElement.getBoundingClientRect();
  var dx = e.clientX - bBox.left - Blockly.FieldAngle.HALF;
  var dy = e.clientY - bBox.top - Blockly.FieldAngle.HALF;
  var angle = Math.atan(-dy / dx);
  if (isNaN(angle)) {
    // This shouldn't happen, but let's not let this error propogate further.
    return;
  }
  angle = goog.math.toDegrees(angle);
  // 0: East, 90: North, 180: West, 270: South.
  if (dx < 0) {
    angle += 180;
  } else if (dy > 0) {
    angle += 360;
  }
  if (Blockly.FieldAngle.CLOCKWISE) {
    angle = Blockly.FieldAngle.OFFSET + 360 - angle;
  } else {
    angle -= Blockly.FieldAngle.OFFSET;
  }
  if (Blockly.FieldAngle.ROUND) {
    angle = Math.round(angle / Blockly.FieldAngle.ROUND) *
        Blockly.FieldAngle.ROUND;
  }
  angle = this.callValidator(angle);
  Blockly.FieldTextInput.htmlInput_.value = angle;
  this.setValue(angle);
  this.validate_();
  this.resizeEditor_();
};

/**
 * Insert a degree symbol.
 * @param {?string} text New text.
 */
Blockly.FieldAngle.prototype.setText = function(text) {
  Blockly.FieldAngle.superClass_.setText.call(this, text);
  if (!this.textElement_) {
    // Not rendered yet.
    return;
  }
  this.updateGraph_();
  // Insert degree symbol.
  if (this.sourceBlock_.RTL) {
    this.textElement_.insertBefore(this.symbol_, this.textElement_.firstChild);
  } else {
    this.textElement_.appendChild(this.symbol_);
  }
  // Cached width is obsolete.  Clear it.
  this.size_.width = 0;
};

/**
 * Redraw the graph with the current angle.
 * @private
 */
Blockly.FieldAngle.prototype.updateGraph_ = function() {
  if (!this.gauge_) {
    return;
  }
  var angleDegrees = Number(this.getText()) + Blockly.FieldAngle.OFFSET;
  var angleRadians = goog.math.toRadians(angleDegrees);
  var path = ['M ', Blockly.FieldAngle.HALF, ',', Blockly.FieldAngle.HALF];
  var x2 = Blockly.FieldAngle.HALF;
  var y2 = Blockly.FieldAngle.HALF;
  if (!isNaN(angleRadians)) {
    var angle1 = goog.math.toRadians(Blockly.FieldAngle.OFFSET);
    var x1 = Math.cos(angle1) * Blockly.FieldAngle.RADIUS;
    var y1 = Math.sin(angle1) * -Blockly.FieldAngle.RADIUS;
    if (Blockly.FieldAngle.CLOCKWISE) {
      angleRadians = 2 * angle1 - angleRadians;
    }
    x2 += Math.cos(angleRadians) * Blockly.FieldAngle.RADIUS;
    y2 -= Math.sin(angleRadians) * Blockly.FieldAngle.RADIUS;
    // Don't ask how the flag calculations work.  They just do.
    var largeFlag = Math.abs(Math.floor((angleRadians - angle1) / Math.PI) % 2);
    if (Blockly.FieldAngle.CLOCKWISE) {
      largeFlag = 1 - largeFlag;
    }
    var sweepFlag = Number(Blockly.FieldAngle.CLOCKWISE);
    path.push(' l ', x1, ',', y1,
        ' A ', Blockly.FieldAngle.RADIUS, ',', Blockly.FieldAngle.RADIUS,
        ' 0 ', largeFlag, ' ', sweepFlag, ' ', x2, ',', y2, ' z');
  }
  this.gauge_.setAttribute('d', path.join(''));
  this.line_.setAttribute('x2', x2);
  this.line_.setAttribute('y2', y2);
};

/**
 * Ensure that only an angle may be entered.
 * @param {string} text The user's text.
 * @return {?string} A string representing a valid angle, or null if invalid.
 */
Blockly.FieldAngle.prototype.classValidator = function(text) {
  if (text === null) {
    return null;
  }
  var n = parseFloat(text || 0);
  if (isNaN(n)) {
    return null;
  }
  n = n % 360;
  if (n < 0) {
    n += 360;
  }
  if (n > Blockly.FieldAngle.WRAP) {
    n -= 360;
  }
  return String(n);
};


text:
package loop.confidence.interop;

import loop.Loop;
import loop.LoopTest;
import org.junit.Test;

import java.util.Arrays;
import java.util.Date;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Confidence tests run a bunch of semi-realistic programs and assert that their results are
 * as expected. This is meant to be our functional regression test suite.
 *
 * @author dhanji@gmail.com (Dhanji R. Prasanna)
 */
public class JavaInteropConfidenceTest extends LoopTest {
  public static final Integer CONSTANT = Long.valueOf(new Date().getTime()).intValue();

  @Test
  public final void newInstanceByReflection() {
    assertEquals("",
        Loop.run("test/loop/confidence/interop/new_instance.loop"));
  }

  @Test
  public final void newInstanceByReflectionWithForName() {
    assertEquals("",
        Loop.run("test/loop/confidence/interop/new_instance_2.loop"));
  }

  @Test
  public final void newInstanceByReflectionWithForNameCalendar() {
    Date now = new Date();
    Object result = Loop.run("test/loop/confidence/interop/new_instance_3.loop");
    assertTrue(result instanceof Date);
    assertTrue(now.before((Date) result) || now.equals(result));
  }

  @Test
  public final void newInstanceByReflectionCalendar() {
    Date now = new Date();
    Object result = Loop.run("test/loop/confidence/interop/new_instance_4.loop");
    assertTrue(result instanceof Date);
    assertTrue(now.before((Date) result) || now.equals(result));
  }

  @Test
  public final void mainMethodArgs() {
    assertEquals(Arrays.asList("ARG1", "ARG2"),
        Loop.run("test/loop/confidence/interop/main_args.loop", new String[] { "arg1", "arg2" }));
  }

  @Test
  public final void normalFunctionCall() {
    assertEquals("hello", Loop.run("test/loop/confidence/interop/postfix_call_1.loop"));
  }

  @Test
  public final void forceCallAsJava() {
    assertEquals("hello", Loop.run("test/loop/confidence/interop/postfix_call_2.loop"));
  }

  @Test
  public final void callOverloadedJavaMethod() {
    assertEquals("hello", Loop.run("test/loop/confidence/interop/overloaded_call_1.loop"));
  }

  @Test
  public final void callAsLoopOverridingJava() {
    assertEquals("HELLO", Loop.run("test/loop/confidence/interop/postfix_call_3.loop"));
  }

  @Test
  public final void callJavaStaticFunction() {
    assertTrue(1327205727145L /* epoch time when this test was written */ < Long.parseLong(
        Loop.run("test/loop/confidence/interop/call_java_static.loop").toString()));
  }

  @Test
  public final void callJavaStaticConstant() {
    assertEquals(CONSTANT + 1, Loop.run("test/loop/confidence/interop/call_java_static_2.loop"));
  }

  @Test
  public final void callJavaStaticConstantWithoutBackticks() {
    assertEquals(CONSTANT + 1, Loop.run("test/loop/confidence/interop/call_java_static_3.loop"));
  }
}