text:
package javafx.scene.layout;

import javafx.scene.control.TitledPane;
import javafx.EasyInitialization;

/**
 * @author Nandem on 2017/3/13.
 */
public abstract class EasyTitledPane extends TitledPane implements EasyInitialization
{
    protected EasyTitledPane()
    {
        beforeInitialize();
    }
}


text:
ES5Harness.registerTest( {
id: "11.13.1-4-10-s",

path: "TestCases/chapter11/11.13/11.13.1/11.13.1-4-10-s.js",

description: "simple assignment throws TypeError if LeftHandSide is a readonly property in strict mode (Number.length)",

test: function testcase() {
  'use strict';

  try {
    Number.length = 42;
  }
  catch (e) {
    if (e instanceof TypeError) {
      return true;
    }
  }
 },

precondition: function prereq() {
  return fnSupportsStrict();
 }

});

redpajama_set_name: RedPajamaGithub


text:
<resources>
    <!-- common -->
    <string name="ncutils_yes">是</string>
    <string name="ncutils_no">否</string>
    <string name="ncutils_confirm">确定</string>
    <string name="ncutils_cancel">取消</string>
    <string name="ncutils_ok">OK</string>
    <string name="ncutils_loading">加载中</string>
    <string name="ncutils_please_wait">请稍等...</string>
    <string name="ncutils_button_allow">允许</string>
    <string name="ncutils_button_deny">拒绝</string>
    <string name="ncutils_done">完成</string>
    <string name="ncutils_error">发生错误!</string>
    <string name="ncutils_network_error">网络问题</string>

    <!-- permission -->
    <string name="ncutils_permission_settings">设置</string>
    <string name="ncutils_permission_group_calendar">日历</string>
    <string name="ncutils_permission_group_camera">相机</string>
    <string name="ncutils_permission_group_contacts">通讯录</string>
    <string name="ncutils_permission_group_location">位置</string>
    <string name="ncutils_permission_group_microphone">麦克风</string>
    <string name="ncutils_permission_group_phone">电话</string>
    <string name="ncutils_permission_group_sensors">传感器</string>
    <string name="ncutils_permission_group_sms">短信</string>
    <string name="ncutils_permission_group_storage">存储</string>
    <string name="ncutils_permission_rationale_general">以下电话功能要求允许:\n</string>
    <string name="ncutils_permission_rationale_general_part2">以便可以享用以下功能:\n</string>
    <string name="ncutils_permission_denied_general">程序无权使用以下电话功能:\n</string>
    <string name="ncutils_permission_denied_general_part2">\n受影响的功能:\n</string>
    <string name="ncutils_permission_denied_general_instructions">\n程序的权限可在手机设置中进行配置。</string>

    <!-- Calendar -->
    <string name="ncutils_permission_rationale_feature_access_calendar">访问日历</string>

    <!-- Camera -->
    <string name="ncutils_permission_rationale_feature_scan_qr_code">扫描二维码</string>
    <string name="ncutils_permission_rationale_feature_take_picture">拍照</string>

    <!-- Microphone -->
    <string name="ncutils_permission_rationale_feature_voice_call">语音通话</string>
    <string name="ncutils_permission_rationale_feature_voice_messaging">发送语音邮件</string>
    <string name="ncutils_permission_rationale_feature_record_voice">录制语音</string>

    <!-- Camera and Microphone -->
    <string name="ncutils_permission_rationale_feature_take_video">录制视频</string>
    <string name="ncutils_permission_rationale_feature_video_call">视频通话</string>

    <!-- Contacts -->
    <string name="ncutils_permission_rationale_feature_access_contacts">访问通讯录</string>
    <string name="ncutils_permission_rationale_feature_recommend_new_friends">从通讯录推荐好友</string>

    <!-- Location -->
    <string name="ncutils_permission_rationale_feature_auto_fill_area_code">自动填充区号</string>
    <string name="ncutils_permission_rationale_feature_share_location">分享位置</string>
    <string name="ncutils_permission_rationale_feature_locate_user">定位</string>

    <!-- Storage -->
    <string name="ncutils_permission_rationale_feature_pick_picture">从存储设备选择图片</string>
    <string name="ncutils_permission_rationale_feature_pick_video">从存储设备选择视频</string>
    <string name="ncutils_permission_rationale_feature_pick_audio">从存储设备选择音频</string>
    <string name="ncutils_permission_rationale_feature_pick_folder">从存储设备选择文件夹</string>
    <string name="ncutils_permission_rationale_feature_pick_file">从存储设备选择文件</string>
    <string name="ncutils_permission_rationale_feature_save_media_to_storage">用电话存储保存媒体</string>
    <string name="ncutils_permission_rationale_feature_save_content_to_storage">用电话存储保存内容</string>

    <!-- Telephone -->
    <string name="ncutils_permission_rationale_feature_access_phone_features">访问电话功能</string>
    <string name="ncutils_permission_rationale_feature_get_phone_number">获取电话号码</string>
    <string name="ncutils_permission_rationale_feature_make_phone_call">手机通话</string>
    <string name="ncutils_permission_rationale_feature_answer_phone_call">接听电话</string>

    <!-- SMS -->
    <string name="ncutils_permission_rationale_feature_access_sms">访问短信和彩信功能</string>
    <string name="ncutils_permission_rationale_send_sms">发送短信</string>
    <string name="ncutils_permission_rationale_read_sms">读短信</string>

    <!-- Sensors -->
    <string name="ncutils_permission_rationale_feature_access_sensors">访问手机传感器</string>

    <!-- BLE -->
    <string name="ncutils_permission_rationale_feature_scan_surrounding_ble">扫描周边蓝牙设备</string>
    <string name="ncutils_permission_rationale_feature_connect_ble">连接蓝牙设备</string>

</resources>


text:
package bnfc.abs.Absyn; // Java Package generated by the BNF Converter.

public abstract class AnyIdent implements java.io.Serializable {
  public abstract <R,A> R accept(AnyIdent.Visitor<R,A> v, A arg);
  public interface Visitor <R,A> {
    public R visit(bnfc.abs.Absyn.AnyIden p, A arg);
    public R visit(bnfc.abs.Absyn.AnyTyIden p, A arg);

  }

}


text:
Node JS client module to send SMS messages using SMS Alert Gateway.

To use this library, you must have a valid account on https://www.smsalert.co.in.

For any questions, please contact us at support@cozyvision.com

# Installation

```bash
$ npm install smsalert
```

# Send a message

```js
    const SMS = require('smsalert');
    const sms = new SMS(username, password);
	const resultMessage = sms.send(to, message,senderid).then((responseMessage) => {
    console.log(responseMessage);
    });
```

# More info

You can check out our website https://www.smsalert.co.in


text:
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

namespace JiiLib.Constraints.Analyzers
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    internal sealed class InterfaceUsageAnalyzer : BaseUsageAnalyzer<InterfacesOnlyAttribute, InterfaceConstraintDiagnosticChoice>
    {
        private const string DiagnosticId = "JLC0001U";
        private const string Title = "The InterfacesOnly attribute cannot be combined with an incompatible constraint";
        private const string MessageFormatVT = "The InterfacesOnly attribute on '{0}' in '{1}' cannot be combined with the ValueType constraint";
        private const string MessageFormatBC = "The InterfacesOnly attribute on '{0}' in '{1}' cannot be combined with a Base Class constraint";
        private const string MessageFormatCtor = "The InterfacesOnly attribute on '{0}' in '{1}' cannot be combined with the new() constraint";
        private const string MessageFormatTParam = "Type Parameter '{0}' in '{1}' is constrained to another type parameter with an incompatible constraint";
        private const string Description = "Invalid use of constraint attribute.";
        private const string Category = "API Usage";

        private static readonly DiagnosticDescriptor _ruleVT = new(
            DiagnosticId, Title, MessageFormatVT, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description);
        private static readonly DiagnosticDescriptor _ruleCtor = new(
            DiagnosticId, Title, MessageFormatCtor, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description);
        private static readonly DiagnosticDescriptor _ruleBC = new(
            DiagnosticId, Title, MessageFormatBC, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description);
        private static readonly DiagnosticDescriptor _ruleTParam = new(
            DiagnosticId, Title, MessageFormatTParam, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_ruleVT, _ruleCtor, _ruleBC, _ruleTParam);

        private protected override InterfaceConstraintDiagnosticChoice GetDiagnosticChoice(ITypeParameterSymbol typeParameterSymbol)
        {
            return typeParameterSymbol switch
            {
                { HasValueTypeConstraint: true } => InterfaceConstraintDiagnosticChoice.Struct,
                { HasConstructorConstraint: true } => InterfaceConstraintDiagnosticChoice.New,
                { ConstraintTypes: { IsEmpty: false } types } => GetChoiceFromConstraints(types, this),
                _ => InterfaceConstraintDiagnosticChoice.Valid
            };

            static InterfaceConstraintDiagnosticChoice GetChoiceFromConstraints(
                ImmutableArray<ITypeSymbol> types,
                InterfaceUsageAnalyzer @this)
            {
                foreach (var t in types)
                {
                    if (t.TypeKind == TypeKind.Class)
                        return InterfaceConstraintDiagnosticChoice.BaseClass;

                    if (t is ITypeParameterSymbol typeParam
                        && @this.GetDiagnosticChoice(typeParam) != InterfaceConstraintDiagnosticChoice.Valid)
                    {
                        return InterfaceConstraintDiagnosticChoice.TypeParam;
                    }
                }

                return InterfaceConstraintDiagnosticChoice.Valid;
            }
        }

        private protected override DiagnosticDescriptor GetDiagnosticDescriptor(InterfaceConstraintDiagnosticChoice choice)
        {
            return choice switch
            {
                InterfaceConstraintDiagnosticChoice.Struct => _ruleVT,
                InterfaceConstraintDiagnosticChoice.New => _ruleCtor,
                InterfaceConstraintDiagnosticChoice.BaseClass => _ruleBC,
                InterfaceConstraintDiagnosticChoice.TypeParam => _ruleTParam,
                _ => throw new InvalidOperationException()
            };
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="-1" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />

    <meta name="description" content=" ***  Your description goes `here ***">
    <meta name="author" content="SimonComputing, Inc.">

Hello World!


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Categories on Ibrahim Jarif</title>
    <link>https://jarifibrahim.github.io/categories/</link>
    <description>Recent content in Categories on Ibrahim Jarif</description>
    <generator>Hugo -- gohugo.io</generator>

	<atom:link href="https://jarifibrahim.github.io/categories/index.xml" rel="self" type="application/rss+xml" />

  </channel>
</rss>


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace Amazon.S3.Model
{
    /// <summary>
    /// This class contains the configuration Amazon S3 uses to figure out what events you want to listen
    /// and send the event to an Amazon SQS queue.
    /// <para>
    /// The queue's policy must allow S3 to send messages to it. The utility method
    /// <see cref="Amazon.SQS.AmazonSQSClient.AuthorizeS3ToSendMessage(string,string)"/>
    /// can be used to help setup the queue policy.
    /// </para>
    /// </summary>
    public class QueueConfiguration
    {
        /// <summary>
        /// Gets and set the Id property. The Id will be provided in the event content and can be used
        /// to identify which configuration caused an event to fire. If the Id is not provided for the configuration, one will be generated.
        /// </summary>
        public string Id { get; set; }

        internal bool IsSetId()
        {
            return this.Id != null;
        }

        List<EventType> _events;
        /// <summary>
        /// Gets and sets the Events property. These are the events the configuration will listen to and send to the Amazon SQS queue.
        /// </summary>
        public List<EventType> Events
        {
            get
            {
                if (this._events == null)
                    this._events = new List<EventType>();

                return this._events;
            }
            set { this._events = value; }
        }

        // Check to see if Event property is set
        internal bool IsSetEvents()
        {
            return this._events != null && this._events.Count > 0;
        }

        /// <summary>
        /// Gets and sets the Queue property. Amazon SQS queue to which Amazon S3 will publish a message
        /// to report the specified events for the bucket.
        /// <para>
        /// The queue's policy must allow S3 to send messages to it. The utility method
        /// <see cref="Amazon.SQS.AmazonSQSClient.AuthorizeS3ToSendMessage(string,string)"/>
        /// can be used to help setup the queue policy.
        /// </para>
        /// </summary>
        public string Queue { get; set; }

        // Check to see if Queue property is set
        internal bool IsSetQueue()
        {
            return this.Queue != null;
        }
    }
}


text:
"use strict";
/* -------------------------------------------------------------------
 * Require Statements << Keep in alphabetical order >>
 * ---------------------------------------------------------------- */

var Helpers = require('./Helpers');
var ScheduledTask = require('./ScheduledTask');
var Uuid = require('node-uuid');

/* =============================================================================
 *
 * Schtick
 *
 * ========================================================================== */

module.exports = Schtick;

function Schtick ()
{
	/** @private */
	this._tasks = {};
	/** @private */
	this._isShuttingDown = false;
	/** @private */
	this._errorHandlers = [];
	/** @private */
	this._onTaskError = onTaskError.bind(this);
}

/* -------------------------------------------------------------------
 * Public Methods
 * ---------------------------------------------------------------- */

Object.defineProperty(Schtick.prototype, 'isShuttingDown', {
	get: function () { return this._isShuttingDown; }
});

/**
 *
 * @param name {string}
 * @param schedule {string|Schedule}
 * @param [options] {{autoRun: boolean, lastKnownEvent: Date, window: number}}
 * @param callback {function(ScheduledTask, Date)}
 * @return {ScheduledTask}
 */
Schtick.prototype.addTask = function (name, schedule, options, callback)
{
	if (arguments.length < 4)
	{
		callback = options;
		options = {};
	}

	return this._addTaskImpl(name, schedule, options, callback, false);
};

/**
 *
 * @param name {string}
 * @param schedule {string|Schedule}
 * @param [options] {{autoRun: boolean, lastKnownEvent: Date, window: number}}
 * @param callback {function(ScheduledTask, Date, function(Error))}
 * @return {ScheduledTask}
 */
Schtick.prototype.addAsyncTask = function (name, schedule, options, callback)
{
	if (arguments.length < 4)
	{
		callback = options;
		options = {};
	}

	return this._addTaskImpl(name, schedule, options, callback, true);
};

/**
 * @param name {string}
 * @return {?ScheduledTask}
 */
Schtick.prototype.getTask = function (name)
{
	if (!this._tasks.hasOwnProperty(name))
		return null;

	return this._tasks[name];
};

/**
 * @return {ScheduledTask[]}
 */
Schtick.prototype.getAllTasks = function ()
{
	var tasks = [];
	for (var i in this._tasks)
	{
		if (this._tasks.hasOwnProperty(i))
			tasks.push(this._tasks[i]);
	}

	return tasks;
};

/**
 * Throws an exception if the task is still running.
 * @param name {string}
 * @return {boolean} True if the task was removed. False if it did not exist.
 */
Schtick.prototype.removeTask = function (name)
{
	if (this.isShuttingDown)
		throw new Error("Cannot remove a task from Schtick after shutdown() has been called.");

	var task = this.getTask(name);
	if (!task)
		return false;

	if (task.isScheduleRunning)
		throw new Error('Cannot remove task "' + name + '". It is still running.');

	task._isAttached = false;
	delete this._tasks[name];
	return true;
};

Schtick.prototype.shutdown = function ()
{
	this._isShuttingDown = true;
	var tasks = this.getAllTasks();

	for (var i = 0; i < tasks.length; i++)
	{
		tasks[i]._isAttached = false;
		tasks[i].stopSchedule();
	}
};

Schtick.prototype.addErrorHandler = function (callback)
{
	this._errorHandlers.push(callback);
};

Schtick.prototype.removeErrorHandler = function (callback)
{
	for (var i = 0; i < this._errorHandlers.length; i++)
	{
		if (this._errorHandlers[i] === callback)
		{
			this._errorHandlers.splice(i, 1);
			return;
		}
	}
};

/* -------------------------------------------------------------------
 * Private Methods
 * ---------------------------------------------------------------- */

/**
 * @param name {string}
 * @param schedule {string|Schedule}
 * @param options {{autoRun: boolean, lastKnownEvent: Date, window: number}}
 * @param callback
 * @param isAsync {boolean}
 * @return {ScheduledTask}
 * @private
 */
Schtick.prototype._addTaskImpl = function (name, schedule, options, callback, isAsync)
{
	if (!name)
		name = Uuid.v4();

	if (this.isShuttingDown)
		throw new Error('Cannot add a task to Schtick after shutdown() has been called.');

	if (this._tasks.hasOwnProperty(name))
		throw new Error('A scheduled task named "' + name + '" already exists.');

	schedule = Helpers.toSchedule(schedule);

	var task = new ScheduledTask(name, schedule, callback, isAsync);
	task._isAttached = true;
	task.addErrorHandler(this._onTaskError);
	if (typeof options.window === 'number')
		task.window = options.window;

	this._tasks[name] = task;

	if (options.autoRun !== false)
	{
		task.startSchedule(options.lastKnownEvent);
	}

	return task;
};

/**
 * @this {Schtick}
 */
function onTaskError (task, error)
{
	for (var i = 0; i < this._errorHandlers.length; i++)
	{
		this._errorHandlers[i](task, error);
	}
}


text:
@interface HHTestTableViewCell : HHSwipeTableViewCell
@property (nonatomic, strong) UILabel *label;
@end


text:
class GfxUi : public wxApp {
public:
	virtual bool OnInit();
	//virtual int OnExit();
	App app;
};

#endif


text:
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"

/*-----------------------------------------------------------
 * Implementation of functions defined in portable.h for the MSP430X port.
 *----------------------------------------------------------*/

/* Constants required for hardware setup.  The tick ISR runs off the ACLK,
not the MCLK. */
#define portACLK_FREQUENCY_HZ			( ( TickType_t ) 32768 )
#define portINITIAL_CRITICAL_NESTING	( ( uint16_t ) 10 )
#define portFLAGS_INT_ENABLED			( ( StackType_t ) 0x08 )

/* We require the address of the pxCurrentTCB variable, but don't want to know
any details of its type. */
typedef void TCB_t;
extern volatile TCB_t * volatile pxCurrentTCB;

/* Each task maintains a count of the critical section nesting depth.  Each
time a critical section is entered the count is incremented.  Each time a
critical section is exited the count is decremented - with interrupts only
being re-enabled if the count is zero.

usCriticalNesting will get set to zero when the scheduler starts, but must
not be initialised to zero as this will cause problems during the startup
sequence. */
volatile uint16_t usCriticalNesting = portINITIAL_CRITICAL_NESTING;
/*-----------------------------------------------------------*/

/*
 * Sets up the periodic ISR used for the RTOS tick.  This uses timer 0, but
 * could have alternatively used the watchdog timer or timer 1.
 */
void vPortSetupTimerInterrupt( void );
/*-----------------------------------------------------------*/

/*
 * Initialise the stack of a task to look exactly as if a call to
 * portSAVE_CONTEXT had been called.
 *
 * See the header file portable.h.
 */
StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
{
uint16_t *pusTopOfStack;
uint32_t *pulTopOfStack, ulTemp;

	/*
		Place a few bytes of known values on the bottom of the stack.
		This is just useful for debugging and can be included if required.

		*pxTopOfStack = ( StackType_t ) 0x1111;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0x2222;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0x3333;
		pxTopOfStack--;
	*/

	/* Data types are need either 16 bits or 32 bits depending on the data
	and code model used. */
	if( sizeof( pxCode ) == sizeof( uint16_t ) )
	{
		pusTopOfStack = ( uint16_t * ) pxTopOfStack;
		ulTemp = ( uint32_t ) pxCode;
		*pusTopOfStack = ( uint16_t ) ulTemp;
	}
	else
	{
		/* Make room for a 20 bit value stored as a 32 bit value. */
		pusTopOfStack = ( uint16_t * ) pxTopOfStack;
		pusTopOfStack--;
		pulTopOfStack = ( uint32_t * ) pusTopOfStack;
		*pulTopOfStack = ( uint32_t ) pxCode;
	}

	pusTopOfStack--;
	*pusTopOfStack = portFLAGS_INT_ENABLED;
	pusTopOfStack -= ( sizeof( StackType_t ) / 2 );

	/* From here on the size of stacked items depends on the memory model. */
	pxTopOfStack = ( StackType_t * ) pusTopOfStack;

	/* Next the general purpose registers. */
	#ifdef PRELOAD_REGISTER_VALUES
		*pxTopOfStack = ( StackType_t ) 0xffff;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0xeeee;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0xdddd;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) pvParameters;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0xbbbb;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0xaaaa;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0x9999;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0x8888;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0x5555;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0x6666;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0x5555;
		pxTopOfStack--;
		*pxTopOfStack = ( StackType_t ) 0x4444;
		pxTopOfStack--;
	#else
		pxTopOfStack -= 3;
		*pxTopOfStack = ( StackType_t ) pvParameters;
		pxTopOfStack -= 9;
	#endif

	/* A variable is used to keep track of the critical section nesting.
	This variable has to be stored as part of the task context and is
	initially set to zero. */
	*pxTopOfStack = ( StackType_t ) portNO_CRITICAL_SECTION_NESTING;

	/* Return a pointer to the top of the stack we have generated so this can
	be stored in the task control block for the task. */
	return pxTopOfStack;
}
/*-----------------------------------------------------------*/

void vPortEndScheduler( void )
{
	/* It is unlikely that the MSP430 port will get stopped.  If required simply
	disable the tick interrupt here. */
}
/*-----------------------------------------------------------*/

/*
 * Hardware initialisation to generate the RTOS tick.
 */
void vPortSetupTimerInterrupt( void )
{
	vApplicationSetupTimerInterrupt();
}
/*-----------------------------------------------------------*/

#pragma vector=configTICK_VECTOR
interrupt void vTickISREntry( void )
{
extern void vPortTickISR( void );

	__bic_SR_register_on_exit( SCG1 + SCG0 + OSCOFF + CPUOFF );
	#if configUSE_PREEMPTION == 1
		extern void vPortPreemptiveTickISR( void );
		vPortPreemptiveTickISR();
	#else
		extern void vPortCooperativeTickISR( void );
		vPortCooperativeTickISR();
	#endif
}


text:
import collections
from optparse import OptionParser
import os
import pickle
import re
import sys
import logging

from xml.etree import ElementTree

# Make sure we're using Babel source, and not some previously installed version
CHECKOUT_ROOT = os.path.abspath(os.path.join(
    os.path.dirname(__file__),
    '..'
))
BABEL_PACKAGE_ROOT = os.path.join(CHECKOUT_ROOT, "babel")
sys.path.insert(0, CHECKOUT_ROOT)

from babel import dates, numbers
from babel.dates import split_interval_pattern
from babel.localedata import Alias
from babel.plural import PluralRule

parse = ElementTree.parse
weekdays = {'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5,
            'sun': 6}

def _text(elem):
    buf = [elem.text or '']
    for child in elem:
        buf.append(_text(child))
    buf.append(elem.tail or '')
    return u''.join(filter(None, buf)).strip()

NAME_RE = re.compile(r"^\w+$")
TYPE_ATTR_RE = re.compile(r"^\w+\[@type='(.*?)'\]$")

NAME_MAP = {
    'dateFormats': 'date_formats',
    'dateTimeFormats': 'datetime_formats',
    'eraAbbr': 'abbreviated',
    'eraNames': 'wide',
    'eraNarrow': 'narrow',
    'timeFormats': 'time_formats'
}

log = logging.getLogger("import_cldr")

def need_conversion(dst_filename, data_dict, source_filename):
    with open(source_filename, 'rb') as f:
        blob = f.read(4096)
        version_match = re.search(b'version number="\\$Revision: (\\d+)', blob)
        if not version_match:  # CLDR 36.0 was shipped without proper revision numbers
            return True
        version = int(version_match.group(1))

    data_dict['_version'] = version
    if not os.path.isfile(dst_filename):
        return True

    with open(dst_filename, 'rb') as f:
        data = pickle.load(f)
        return data.get('_version') != version

def _translate_alias(ctxt, path):
    parts = path.split('/')
    keys = ctxt[:]
    for part in parts:
        if part == '..':
            keys.pop()
        else:
            match = TYPE_ATTR_RE.match(part)
            if match:
                keys.append(match.group(1))
            else:
                assert NAME_RE.match(part)
                keys.append(NAME_MAP.get(part, part))
    return keys

def _parse_currency_date(s):
    if not s:
        return None
    parts = s.split('-', 2)
    return tuple(map(int, parts + [1] * (3 - len(parts))))

def _currency_sort_key(tup):
    code, start, end, tender = tup
    return int(not tender), start or (1, 1, 1)

def _extract_plural_rules(file_path):
    rule_dict = {}
    prsup = parse(file_path)
    for elem in prsup.findall('.//plurals/pluralRules'):
        rules = []
        for rule in elem.findall('pluralRule'):
            rules.append((rule.attrib['count'], str(rule.text)))
        pr = PluralRule(rules)
        for locale in elem.attrib['locales'].split():
            rule_dict[locale] = pr
    return rule_dict

def _time_to_seconds_past_midnight(time_expr):
    """
    Parse a time expression to seconds after midnight.
    :param time_expr: Time expression string (H:M or H:M:S)
    :rtype: int
    """
    if time_expr is None:
        return None
    if time_expr.count(":") == 1:
        time_expr += ":00"
    hour, minute, second = [int(p, 10) for p in time_expr.split(":")]
    return hour * 60 * 60 + minute * 60 + second

def _compact_dict(dict):
    """
    "Compact" the given dict by removing items whose value is None or False.
    """
    out_dict = {}
    for key, value in dict.items():
        if value is not None and value is not False:
            out_dict[key] = value
    return out_dict

def debug_repr(obj):
    if isinstance(obj, PluralRule):
        return obj.abstract
    return repr(obj)

def write_datafile(path, data, dump_json=False):
    with open(path, 'wb') as outfile:
        pickle.dump(data, outfile, 2)
    if dump_json:
        import json

        with open(f"{path}.json", "w") as outfile:
            json.dump(data, outfile, indent=4, default=debug_repr)

def main():
    parser = OptionParser(usage='%prog path/to/cldr')
    parser.add_option(
        '-f', '--force', dest='force', action='store_true', default=False,
        help='force import even if destination file seems up to date'
    )
    parser.add_option(
        '-j', '--json', dest='dump_json', action='store_true', default=False,
        help='also export debugging JSON dumps of locale data'
    )
    parser.add_option(
        '-q', '--quiet', dest='quiet', action='store_true', default=bool(os.environ.get('BABEL_CLDR_QUIET')),
        help='quiesce info/warning messages',
    )

    options, args = parser.parse_args()
    if len(args) != 1:
        parser.error('incorrect number of arguments')

    logging.basicConfig(
        level=(logging.ERROR if options.quiet else logging.INFO),
    )

    return process_data(
        srcdir=args[0],
        destdir=BABEL_PACKAGE_ROOT,
        force=bool(options.force),
        dump_json=bool(options.dump_json)
    )

def process_data(srcdir, destdir, force=False, dump_json=False):
    sup_filename = os.path.join(srcdir, 'supplemental', 'supplementalData.xml')
    sup = parse(sup_filename)

    # Import global data from the supplemental files
    global_path = os.path.join(destdir, 'global.dat')
    global_data = {}
    if force or need_conversion(global_path, global_data, sup_filename):
        global_data.update(parse_global(srcdir, sup))
        write_datafile(global_path, global_data, dump_json=dump_json)
    _process_local_datas(sup, srcdir, destdir, force=force, dump_json=dump_json)

def parse_global(srcdir, sup):
    global_data = {}
    sup_dir = os.path.join(srcdir, 'supplemental')
    territory_zones = global_data.setdefault('territory_zones', {})
    zone_aliases = global_data.setdefault('zone_aliases', {})
    zone_territories = global_data.setdefault('zone_territories', {})
    win_mapping = global_data.setdefault('windows_zone_mapping', {})
    language_aliases = global_data.setdefault('language_aliases', {})
    territory_aliases = global_data.setdefault('territory_aliases', {})
    script_aliases = global_data.setdefault('script_aliases', {})
    variant_aliases = global_data.setdefault('variant_aliases', {})
    likely_subtags = global_data.setdefault('likely_subtags', {})
    territory_currencies = global_data.setdefault('territory_currencies', {})
    parent_exceptions = global_data.setdefault('parent_exceptions', {})
    all_currencies = collections.defaultdict(set)
    currency_fractions = global_data.setdefault('currency_fractions', {})
    territory_languages = global_data.setdefault('territory_languages', {})
    bcp47_timezone = parse(os.path.join(srcdir, 'bcp47', 'timezone.xml'))
    sup_windows_zones = parse(os.path.join(sup_dir, 'windowsZones.xml'))
    sup_metadata = parse(os.path.join(sup_dir, 'supplementalMetadata.xml'))
    sup_likely = parse(os.path.join(sup_dir, 'likelySubtags.xml'))
    # create auxiliary zone->territory map from the windows zones (we don't set
    # the 'zones_territories' map directly here, because there are some zones
    # aliases listed and we defer the decision of which ones to choose to the
    # 'bcp47' data
    _zone_territory_map = {}
    for map_zone in sup_windows_zones.findall('.//windowsZones/mapTimezones/mapZone'):
        if map_zone.attrib.get('territory') == '001':
            win_mapping[map_zone.attrib['other']] = map_zone.attrib['type'].split()[0]
        for tzid in str(map_zone.attrib['type']).split():
            _zone_territory_map[tzid] = str(map_zone.attrib['territory'])
    for key_elem in bcp47_timezone.findall('.//keyword/key'):
        if key_elem.attrib['name'] == 'tz':
            for elem in key_elem.findall('type'):
                if 'deprecated' not in elem.attrib:
                    aliases = str(elem.attrib['alias']).split()
                    tzid = aliases.pop(0)
                    territory = _zone_territory_map.get(tzid, '001')
                    territory_zones.setdefault(territory, []).append(tzid)
                    zone_territories[tzid] = territory
                    for alias in aliases:
                        zone_aliases[alias] = tzid
            break

    # Import Metazone mapping
    meta_zones = global_data.setdefault('meta_zones', {})
    tzsup = parse(os.path.join(srcdir, 'supplemental', 'metaZones.xml'))
    for elem in tzsup.findall('.//timezone'):
        for child in elem.findall('usesMetazone'):
            if 'to' not in child.attrib:  # FIXME: support old mappings
                meta_zones[elem.attrib['type']] = child.attrib['mzone']

    # Language aliases
    for alias in sup_metadata.findall('.//alias/languageAlias'):
        # We don't have a use for those at the moment.  They don't
        # pass our parser anyways.
        if '_' in alias.attrib['type']:
            continue
        language_aliases[alias.attrib['type']] = alias.attrib['replacement']

    # Territory aliases
    for alias in sup_metadata.findall('.//alias/territoryAlias'):
        territory_aliases[alias.attrib['type']] = alias.attrib['replacement'].split()

    # Script aliases
    for alias in sup_metadata.findall('.//alias/scriptAlias'):
        script_aliases[alias.attrib['type']] = alias.attrib['replacement']

    # Variant aliases
    for alias in sup_metadata.findall('.//alias/variantAlias'):
        repl = alias.attrib.get('replacement')
        if repl:
            variant_aliases[alias.attrib['type']] = repl

    # Likely subtags
    for likely_subtag in sup_likely.findall('.//likelySubtags/likelySubtag'):
        likely_subtags[likely_subtag.attrib['from']] = likely_subtag.attrib['to']

    # Currencies in territories
    for region in sup.findall('.//currencyData/region'):
        region_code = region.attrib['iso3166']
        region_currencies = []
        for currency in region.findall('./currency'):
            cur_code = currency.attrib['iso4217']
            cur_start = _parse_currency_date(currency.attrib.get('from'))
            cur_end = _parse_currency_date(currency.attrib.get('to'))
            cur_tender = currency.attrib.get('tender', 'true') == 'true'
            # Tie region to currency.
            region_currencies.append((cur_code, cur_start, cur_end, cur_tender))
            # Keep a reverse index of currencies to territorie.
            all_currencies[cur_code].add(region_code)
        region_currencies.sort(key=_currency_sort_key)
        territory_currencies[region_code] = region_currencies
    global_data['all_currencies'] = {
        currency: tuple(sorted(regions)) for currency, regions in all_currencies.items()}

    # Explicit parent locales
    for paternity in sup.findall('.//parentLocales/parentLocale'):
        parent = paternity.attrib['parent']
        for child in paternity.attrib['locales'].split():
            parent_exceptions[child] = parent

    # Currency decimal and rounding digits
    for fraction in sup.findall('.//currencyData/fractions/info'):
        cur_code = fraction.attrib['iso4217']
        cur_digits = int(fraction.attrib['digits'])
        cur_rounding = int(fraction.attrib['rounding'])
        cur_cdigits = int(fraction.attrib.get('cashDigits', cur_digits))
        cur_crounding = int(fraction.attrib.get('cashRounding', cur_rounding))
        currency_fractions[cur_code] = (cur_digits, cur_rounding, cur_cdigits, cur_crounding)

    # Languages in territories
    for territory in sup.findall('.//territoryInfo/territory'):
        languages = {}
        for language in territory.findall('./languagePopulation'):
            languages[language.attrib['type']] = {
                'population_percent': float(language.attrib['populationPercent']),
                'official_status': language.attrib.get('officialStatus'),
            }
        territory_languages[territory.attrib['type']] = languages
    return global_data

def _process_local_datas(sup, srcdir, destdir, force=False, dump_json=False):
    day_period_rules = parse_day_period_rules(parse(os.path.join(srcdir, 'supplemental', 'dayPeriods.xml')))
    # build a territory containment mapping for inheritance
    regions = {}
    for elem in sup.findall('.//territoryContainment/group'):
        regions[elem.attrib['type']] = elem.attrib['contains'].split()

    # Resolve territory containment
    territory_containment = {}
    region_items = sorted(regions.items())
    for group, territory_list in region_items:
        for territory in territory_list:
            containers = territory_containment.setdefault(territory, set())
            if group in territory_containment:
                containers |= territory_containment[group]
            containers.add(group)

    # prepare the per-locale plural rules definitions
    plural_rules = _extract_plural_rules(os.path.join(srcdir, 'supplemental', 'plurals.xml'))
    ordinal_rules = _extract_plural_rules(os.path.join(srcdir, 'supplemental', 'ordinals.xml'))

    filenames = os.listdir(os.path.join(srcdir, 'main'))
    filenames.remove('root.xml')
    filenames.sort(key=len)
    filenames.insert(0, 'root.xml')

    for filename in filenames:
        stem, ext = os.path.splitext(filename)
        if ext != '.xml':
            continue

        full_filename = os.path.join(srcdir, "main", filename)
        data_filename = os.path.join(destdir, "locale-data", f"{stem}.dat")

        data = {}
        if not (force or need_conversion(data_filename, data, full_filename)):
            continue

        tree = parse(full_filename)

        language = None
        elem = tree.find('.//identity/language')
        if elem is not None:
            language = elem.attrib['type']

        territory = None
        elem = tree.find('.//identity/territory')
        if elem is not None:
            territory = elem.attrib['type']
        else:
            territory = '001'  # world
        regions = territory_containment.get(territory, [])

        log.info(
            'Processing %s (Language = %s; Territory = %s)',
            filename, language, territory,
        )

        locale_id = '_'.join(filter(None, [
            language,
            territory != '001' and territory or None
        ]))

        data['locale_id'] = locale_id
        data['unsupported_number_systems'] = set()

        if locale_id in plural_rules:
            data['plural_form'] = plural_rules[locale_id]
        if locale_id in ordinal_rules:
            data['ordinal_form'] = ordinal_rules[locale_id]
        if locale_id in day_period_rules:
            data["day_period_rules"] = day_period_rules[locale_id]

        parse_locale_display_names(data, tree)
        parse_list_patterns(data, tree)
        parse_dates(data, tree, sup, regions, territory)

        for calendar in tree.findall('.//calendars/calendar'):
            if calendar.attrib['type'] != 'gregorian':
                # TODO: support other calendar types
                continue

            parse_calendar_months(data, calendar)
            parse_calendar_days(data, calendar)
            parse_calendar_quarters(data, calendar)
            parse_calendar_eras(data, calendar)
            parse_calendar_periods(data, calendar)
            parse_calendar_date_formats(data, calendar)
            parse_calendar_time_formats(data, calendar)
            parse_calendar_datetime_skeletons(data, calendar)
            parse_interval_formats(data, calendar)

        parse_number_symbols(data, tree)
        parse_decimal_formats(data, tree)
        parse_scientific_formats(data, tree)
        parse_percent_formats(data, tree)

        parse_currency_formats(data, tree)
        parse_currency_unit_patterns(data, tree)
        parse_currency_names(data, tree)
        parse_unit_patterns(data, tree)
        parse_date_fields(data, tree)
        parse_character_order(data, tree)
        parse_measurement_systems(data, tree)

        unsupported_number_systems_string = ', '.join(sorted(data.pop('unsupported_number_systems')))
        if unsupported_number_systems_string:
            log.warning(
                f"{locale_id}: unsupported number systems were ignored: "
                f"{unsupported_number_systems_string}"
            )

        write_datafile(data_filename, data, dump_json=dump_json)

def _should_skip_number_elem(data, elem):
    """
    Figure out whether the numbering-containing element `elem` is in a currently
    non-supported (i.e. currently non-Latin) numbering system.

    :param data: The root data element, for stashing the warning.
    :param elem: Element with `numberSystem` key
    :return: Boolean
    """
    number_system = elem.get('numberSystem', 'latn')

    if number_system != 'latn':
        data['unsupported_number_systems'].add(number_system)
        return True

    return False

def _should_skip_elem(elem, type=None, dest=None):
    """
    Check whether the given element should be skipped.

    Elements are skipped if they are drafts or alternates of data that already exists in `dest`.

    :param elem: XML element
    :param type: Type string. May be elided if the dest dict is elided.
    :param dest: Destination dict. May be elided to skip the dict check.
    :return: skip boolean
    """
    if 'draft' in elem.attrib or 'alt' in elem.attrib:
        if dest is None or type in dest:
            return True

def _import_type_text(dest, elem, type=None):
    """
    Conditionally import the element's inner text(s) into the `dest` dict.

    The condition being, namely, that the element isn't a draft/alternate version
    of a pre-existing element.

    :param dest: Destination dict
    :param elem: XML element.
    :param type: Override type. (By default, the `type` attr of the element.)
    :return:
    """
    if type is None:
        type = elem.attrib['type']
    if _should_skip_elem(elem, type, dest):
        return
    dest[type] = _text(elem)

def parse_locale_display_names(data, tree):
    territories = data.setdefault('territories', {})
    for elem in tree.findall('.//territories/territory'):
        _import_type_text(territories, elem)
    languages = data.setdefault('languages', {})
    for elem in tree.findall('.//languages/language'):
        _import_type_text(languages, elem)
    variants = data.setdefault('variants', {})
    for elem in tree.findall('.//variants/variant'):
        _import_type_text(variants, elem)
    scripts = data.setdefault('scripts', {})
    for elem in tree.findall('.//scripts/script'):
        _import_type_text(scripts, elem)

def parse_list_patterns(data, tree):
    list_patterns = data.setdefault('list_patterns', {})
    for listType in tree.findall('.//listPatterns/listPattern'):
        by_type = list_patterns.setdefault(listType.attrib.get('type', 'standard'), {})
        for listPattern in listType.findall('listPatternPart'):
            by_type[listPattern.attrib['type']] = _text(listPattern)

def parse_dates(data, tree, sup, regions, territory):
    week_data = data.setdefault('week_data', {})
    supelem = sup.find('.//weekData')
    for elem in supelem.findall('minDays'):
        if _should_skip_elem(elem):
            continue
        territories = elem.attrib['territories'].split()
        if territory in territories or any([r in territories for r in regions]):
            week_data['min_days'] = int(elem.attrib['count'])
    for elem in supelem.findall('firstDay'):
        if _should_skip_elem(elem):
            continue
        territories = elem.attrib['territories'].split()
        if territory in territories or any([r in territories for r in regions]):
            week_data['first_day'] = weekdays[elem.attrib['day']]
    for elem in supelem.findall('weekendStart'):
        if _should_skip_elem(elem):
            continue
        territories = elem.attrib['territories'].split()
        if territory in territories or any([r in territories for r in regions]):
            week_data['weekend_start'] = weekdays[elem.attrib['day']]
    for elem in supelem.findall('weekendEnd'):
        if _should_skip_elem(elem):
            continue
        territories = elem.attrib['territories'].split()
        if territory in territories or any([r in territories for r in regions]):
            week_data['weekend_end'] = weekdays[elem.attrib['day']]
    zone_formats = data.setdefault('zone_formats', {})
    for elem in tree.findall('.//timeZoneNames/gmtFormat'):
        if not _should_skip_elem(elem):
            zone_formats['gmt'] = str(elem.text).replace('{0}', '%s')
            break
    for elem in tree.findall('.//timeZoneNames/regionFormat'):
        if not _should_skip_elem(elem):
            zone_formats['region'] = str(elem.text).replace('{0}', '%s')
            break
    for elem in tree.findall('.//timeZoneNames/fallbackFormat'):
        if not _should_skip_elem(elem):
            zone_formats['fallback'] = (
                str(elem.text).replace('{0}', '%(0)s').replace('{1}', '%(1)s')
            )
            break
    for elem in tree.findall('.//timeZoneNames/fallbackRegionFormat'):
        if not _should_skip_elem(elem):
            zone_formats['fallback_region'] = (
                str(elem.text).replace('{0}', '%(0)s').replace('{1}', '%(1)s')
            )
            break
    time_zones = data.setdefault('time_zones', {})
    for elem in tree.findall('.//timeZoneNames/zone'):
        info = {}
        city = elem.findtext('exemplarCity')
        if city:
            info['city'] = str(city)
        for child in elem.findall('long/*'):
            info.setdefault('long', {})[child.tag] = str(child.text)
        for child in elem.findall('short/*'):
            info.setdefault('short', {})[child.tag] = str(child.text)
        time_zones[elem.attrib['type']] = info
    meta_zones = data.setdefault('meta_zones', {})
    for elem in tree.findall('.//timeZoneNames/metazone'):
        info = {}
        city = elem.findtext('exemplarCity')
        if city:
            info['city'] = str(city)
        for child in elem.findall('long/*'):
            info.setdefault('long', {})[child.tag] = str(child.text)
        for child in elem.findall('short/*'):
            info.setdefault('short', {})[child.tag] = str(child.text)
        meta_zones[elem.attrib['type']] = info

def parse_calendar_months(data, calendar):
    months = data.setdefault('months', {})
    for ctxt in calendar.findall('months/monthContext'):
        ctxt_type = ctxt.attrib['type']
        ctxts = months.setdefault(ctxt_type, {})
        for width in ctxt.findall('monthWidth'):
            width_type = width.attrib['type']
            widths = ctxts.setdefault(width_type, {})
            for elem in width:
                if elem.tag == 'month':
                    _import_type_text(widths, elem, int(elem.attrib['type']))
                elif elem.tag == 'alias':
                    ctxts[width_type] = Alias(
                        _translate_alias(['months', ctxt_type, width_type],
                                         elem.attrib['path'])
                    )

def parse_calendar_days(data, calendar):
    days = data.setdefault('days', {})
    for ctxt in calendar.findall('days/dayContext'):
        ctxt_type = ctxt.attrib['type']
        ctxts = days.setdefault(ctxt_type, {})
        for width in ctxt.findall('dayWidth'):
            width_type = width.attrib['type']
            widths = ctxts.setdefault(width_type, {})
            for elem in width:
                if elem.tag == 'day':
                    _import_type_text(widths, elem, weekdays[elem.attrib['type']])
                elif elem.tag == 'alias':
                    ctxts[width_type] = Alias(
                        _translate_alias(['days', ctxt_type, width_type],
                                         elem.attrib['path'])
                    )

def parse_calendar_quarters(data, calendar):
    quarters = data.setdefault('quarters', {})
    for ctxt in calendar.findall('quarters/quarterContext'):
        ctxt_type = ctxt.attrib['type']
        ctxts = quarters.setdefault(ctxt.attrib['type'], {})
        for width in ctxt.findall('quarterWidth'):
            width_type = width.attrib['type']
            widths = ctxts.setdefault(width_type, {})
            for elem in width:
                if elem.tag == 'quarter':
                    _import_type_text(widths, elem, int(elem.attrib['type']))
                elif elem.tag == 'alias':
                    ctxts[width_type] = Alias(
                        _translate_alias(['quarters', ctxt_type,
                                          width_type],
                                         elem.attrib['path']))

def parse_calendar_eras(data, calendar):
    eras = data.setdefault('eras', {})
    for width in calendar.findall('eras/*'):
        width_type = NAME_MAP[width.tag]
        widths = eras.setdefault(width_type, {})
        for elem in width:
            if elem.tag == 'era':
                _import_type_text(widths, elem, type=int(elem.attrib.get('type')))
            elif elem.tag == 'alias':
                eras[width_type] = Alias(
                    _translate_alias(['eras', width_type],
                                     elem.attrib['path'])
                )

def parse_calendar_periods(data, calendar):
    # Day periods (AM/PM/others)
    periods = data.setdefault('day_periods', {})
    for day_period_ctx in calendar.findall('dayPeriods/dayPeriodContext'):
        ctx_type = day_period_ctx.attrib["type"]
        for day_period_width in day_period_ctx.findall('dayPeriodWidth'):
            width_type = day_period_width.attrib["type"]
            dest_dict = periods.setdefault(ctx_type, {}).setdefault(width_type, {})
            for day_period in day_period_width.findall('dayPeriod'):
                period_type = day_period.attrib['type']
                if 'alt' not in day_period.attrib:
                    dest_dict[period_type] = str(day_period.text)

def parse_calendar_date_formats(data, calendar):
    date_formats = data.setdefault('date_formats', {})
    for format in calendar.findall('dateFormats'):
        for elem in format:
            if elem.tag == 'dateFormatLength':
                type = elem.attrib.get('type')
                if _should_skip_elem(elem, type, date_formats):
                    continue
                try:
                    date_formats[type] = dates.parse_pattern(
                        str(elem.findtext('dateFormat/pattern'))
                    )
                except ValueError as e:
                    log.error(e)
            elif elem.tag == 'alias':
                date_formats = Alias(_translate_alias(
                    ['date_formats'], elem.attrib['path'])
                )

def parse_calendar_time_formats(data, calendar):
    time_formats = data.setdefault('time_formats', {})
    for format in calendar.findall('timeFormats'):
        for elem in format:
            if elem.tag == 'timeFormatLength':
                type = elem.attrib.get('type')
                if _should_skip_elem(elem, type, time_formats):
                    continue
                try:
                    time_formats[type] = dates.parse_pattern(
                        str(elem.findtext('timeFormat/pattern'))
                    )
                except ValueError as e:
                    log.error(e)
            elif elem.tag == 'alias':
                time_formats = Alias(_translate_alias(
                    ['time_formats'], elem.attrib['path'])
                )

def parse_calendar_datetime_skeletons(data, calendar):
    datetime_formats = data.setdefault('datetime_formats', {})
    datetime_skeletons = data.setdefault('datetime_skeletons', {})
    for format in calendar.findall('dateTimeFormats'):
        for elem in format:
            if elem.tag == 'dateTimeFormatLength':
                type = elem.attrib.get('type')
                if _should_skip_elem(elem, type, datetime_formats):
                    continue
                try:
                    datetime_formats[type] = str(elem.findtext('dateTimeFormat/pattern'))
                except ValueError as e:
                    log.error(e)
            elif elem.tag == 'alias':
                datetime_formats = Alias(_translate_alias(
                    ['datetime_formats'], elem.attrib['path'])
                )
            elif elem.tag == 'availableFormats':
                for datetime_skeleton in elem.findall('dateFormatItem'):
                    datetime_skeletons[datetime_skeleton.attrib['id']] = (
                        dates.parse_pattern(str(datetime_skeleton.text))
                    )

def parse_number_symbols(data, tree):
    number_symbols = data.setdefault('number_symbols', {})
    for symbol_elem in tree.findall('.//numbers/symbols'):
        if _should_skip_number_elem(data, symbol_elem):  # TODO: Support other number systems
            continue

        for elem in symbol_elem.findall('./*'):
            if _should_skip_elem(elem):
                continue
            number_symbols[elem.tag] = str(elem.text)

def parse_decimal_formats(data, tree):
    decimal_formats = data.setdefault('decimal_formats', {})
    for df_elem in tree.findall('.//decimalFormats'):
        if _should_skip_number_elem(data, df_elem):  # TODO: Support other number systems
            continue
        for elem in df_elem.findall('./decimalFormatLength'):
            length_type = elem.attrib.get('type')
            if _should_skip_elem(elem, length_type, decimal_formats):
                continue
            if elem.findall('./alias'):
                # TODO map the alias to its target
                continue
            for pattern_el in elem.findall('./decimalFormat/pattern'):
                pattern_type = pattern_el.attrib.get('type')
                pattern = numbers.parse_pattern(str(pattern_el.text))
                if pattern_type:
                    # This is a compact decimal format, see:
                    # https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats

                    # These are mapped into a `compact_decimal_formats` dictionary
                    # with the format {length: {count: {multiplier: pattern}}}.
                    compact_decimal_formats = data.setdefault('compact_decimal_formats', {})
                    length_map = compact_decimal_formats.setdefault(length_type, {})
                    length_count_map = length_map.setdefault(pattern_el.attrib['count'], {})
                    length_count_map[pattern_type] = pattern
                else:
                    # Regular decimal format.
                    decimal_formats[length_type] = pattern

def parse_scientific_formats(data, tree):
    scientific_formats = data.setdefault('scientific_formats', {})
    for sf_elem in tree.findall('.//scientificFormats'):
        if _should_skip_number_elem(data, sf_elem):  # TODO: Support other number systems
            continue
        for elem in sf_elem.findall('./scientificFormatLength'):
            type = elem.attrib.get('type')
            if _should_skip_elem(elem, type, scientific_formats):
                continue
            pattern = str(elem.findtext('scientificFormat/pattern'))
            scientific_formats[type] = numbers.parse_pattern(pattern)

def parse_percent_formats(data, tree):
    percent_formats = data.setdefault('percent_formats', {})

    for pf_elem in tree.findall('.//percentFormats'):
        if _should_skip_number_elem(data, pf_elem):  # TODO: Support other number systems
            continue
        for elem in pf_elem.findall('.//percentFormatLength'):
            type = elem.attrib.get('type')
            if _should_skip_elem(elem, type, percent_formats):
                continue
            pattern = str(elem.findtext('percentFormat/pattern'))
            percent_formats[type] = numbers.parse_pattern(pattern)

def parse_currency_names(data, tree):
    currency_names = data.setdefault('currency_names', {})
    currency_names_plural = data.setdefault('currency_names_plural', {})
    currency_symbols = data.setdefault('currency_symbols', {})
    for elem in tree.findall('.//currencies/currency'):
        code = elem.attrib['type']
        for name in elem.findall('displayName'):
            if ('draft' in name.attrib) and code in currency_names:
                continue
            if 'count' in name.attrib:
                currency_names_plural.setdefault(code, {})[
                    name.attrib['count']] = str(name.text)
            else:
                currency_names[code] = str(name.text)
        for symbol in elem.findall('symbol'):
            if 'draft' in symbol.attrib or 'choice' in symbol.attrib:  # Skip drafts and choice-patterns
                continue
            if symbol.attrib.get('alt'):  # Skip alternate forms
                continue
            currency_symbols[code] = str(symbol.text)

def parse_unit_patterns(data, tree):
    unit_patterns = data.setdefault('unit_patterns', {})
    compound_patterns = data.setdefault('compound_unit_patterns', {})
    unit_display_names = data.setdefault('unit_display_names', {})

    for elem in tree.findall('.//units/unitLength'):
        unit_length_type = elem.attrib['type']
        for unit in elem.findall('unit'):
            unit_type = unit.attrib['type']
            unit_and_length_patterns = unit_patterns.setdefault(unit_type, {}).setdefault(unit_length_type, {})
            for pattern in unit.findall('unitPattern'):
                if pattern.attrib.get('case', 'nominative') != 'nominative':
                    # Skip non-nominative cases.
                    continue
                unit_and_length_patterns[pattern.attrib['count']] = _text(pattern)

            per_unit_pat = unit.find('perUnitPattern')
            if per_unit_pat is not None:
                unit_and_length_patterns['per'] = _text(per_unit_pat)

            display_name = unit.find('displayName')
            if display_name is not None:
                unit_display_names.setdefault(unit_type, {})[unit_length_type] = _text(display_name)

        for unit in elem.findall('compoundUnit'):
            unit_type = unit.attrib['type']
            compound_unit_info = {}
            compound_variations = {}
            for child in unit:
                if child.attrib.get('case', 'nominative') != 'nominative':
                    # Skip non-nominative cases.
                    continue
                if child.tag == "unitPrefixPattern":
                    compound_unit_info['prefix'] = _text(child)
                elif child.tag == "compoundUnitPattern":
                    compound_variations[None] = _text(child)
                elif child.tag == "compoundUnitPattern1":
                    compound_variations[child.attrib.get('count')] = _text(child)
            if compound_variations:
                compound_variation_values = set(compound_variations.values())
                if len(compound_variation_values) == 1:
                    # shortcut: if all compound variations are the same, only store one
                    compound_unit_info['compound'] = next(iter(compound_variation_values))
                else:
                    compound_unit_info['compound_variations'] = compound_variations
            compound_patterns.setdefault(unit_type, {})[unit_length_type] = compound_unit_info

def parse_date_fields(data, tree):
    date_fields = data.setdefault('date_fields', {})
    for elem in tree.findall('.//dates/fields/field'):
        field_type = elem.attrib['type']
        date_fields.setdefault(field_type, {})
        for rel_time in elem.findall('relativeTime'):
            rel_time_type = rel_time.attrib['type']
            for pattern in rel_time.findall('relativeTimePattern'):
                type_dict = date_fields[field_type].setdefault(rel_time_type, {})
                type_dict[pattern.attrib['count']] = str(pattern.text)

def parse_interval_formats(data, tree):
    # https://www.unicode.org/reports/tr35/tr35-dates.html#intervalFormats
    interval_formats = data.setdefault("interval_formats", {})
    for elem in tree.findall("dateTimeFormats/intervalFormats/*"):
        if 'draft' in elem.attrib:
            continue
        if elem.tag == "intervalFormatFallback":
            interval_formats[None] = elem.text
        elif elem.tag == "intervalFormatItem":
            skel_data = interval_formats.setdefault(elem.attrib["id"], {})
            for item_sub in elem:
                if item_sub.tag == "greatestDifference":
                    skel_data[item_sub.attrib["id"]] = split_interval_pattern(item_sub.text)
                else:
                    raise NotImplementedError(f"Not implemented: {item_sub.tag}({item_sub.attrib!r})")

def parse_currency_formats(data, tree):
    currency_formats = data.setdefault('currency_formats', {})
    for currency_format in tree.findall('.//currencyFormats'):
        if _should_skip_number_elem(data, currency_format):  # TODO: Support other number systems
            continue

        for length_elem in currency_format.findall('./currencyFormatLength'):
            curr_length_type = length_elem.attrib.get('type')
            for elem in length_elem.findall('currencyFormat'):
                type = elem.attrib.get('type')
                if _should_skip_elem(elem, type, currency_formats):
                    continue
                for child in elem.iter():
                    if child.tag == 'alias':
                        currency_formats[type] = Alias(
                            _translate_alias(['currency_formats', elem.attrib['type']],
                                             child.attrib['path'])
                        )
                    elif child.tag == 'pattern':
                        pattern_type = child.attrib.get('type')
                        pattern = numbers.parse_pattern(str(child.text))
                        if pattern_type:
                            # This is a compact currency format, see:
                            # https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats

                            # These are mapped into a `compact_currency_formats` dictionary
                            # with the format {length: {count: {multiplier: pattern}}}.
                            compact_currency_formats = data.setdefault('compact_currency_formats', {})
                            length_map = compact_currency_formats.setdefault(curr_length_type, {})
                            length_count_map = length_map.setdefault(child.attrib['count'], {})
                            length_count_map[pattern_type] = pattern
                        else:
                            # Regular currency format
                            currency_formats[type] = pattern

def parse_currency_unit_patterns(data, tree):
    currency_unit_patterns = data.setdefault('currency_unit_patterns', {})
    for currency_formats_elem in tree.findall('.//currencyFormats'):
        if _should_skip_number_elem(data, currency_formats_elem):  # TODO: Support other number systems
            continue
        for unit_pattern_elem in currency_formats_elem.findall('./unitPattern'):
            count = unit_pattern_elem.attrib['count']
            pattern = str(unit_pattern_elem.text)
            currency_unit_patterns[count] = pattern

def parse_day_period_rules(tree):
    """
    Parse dayPeriodRule data into a dict.

    :param tree: ElementTree
    """
    day_periods = {}
    for ruleset in tree.findall(".//dayPeriodRuleSet"):
        ruleset_type = ruleset.attrib.get("type")  # None|"selection"
        for rules in ruleset.findall("dayPeriodRules"):
            locales = rules.attrib["locales"].split()
            for rule in rules.findall("dayPeriodRule"):
                type = rule.attrib["type"]
                if type in ("am", "pm"):  # These fixed periods are handled separately by `get_period_id`
                    continue
                rule = _compact_dict({
                    key: _time_to_seconds_past_midnight(rule.attrib.get(key))
                    for key in ("after", "at", "before", "from", "to")
                })
                for locale in locales:
                    dest_list = day_periods.setdefault(locale, {}).setdefault(ruleset_type, {}).setdefault(type, [])
                    dest_list.append(rule)
    return day_periods

def parse_character_order(data, tree):
    for elem in tree.findall('.//layout/orientation/characterOrder'):
        data['character_order'] = elem.text

def parse_measurement_systems(data, tree):
    measurement_systems = data.setdefault('measurement_systems', {})
    for measurement_system in tree.findall('.//measurementSystemNames/measurementSystemName'):
        type = measurement_system.attrib['type']
        if not _should_skip_elem(measurement_system, type=type, dest=measurement_systems):
            _import_type_text(measurement_systems, measurement_system, type=type)

if __name__ == '__main__':
    main()


text:
<?php

interface IAction
{
    public function execute();
}

?>


text:
<?php
  if(!$_SESSION['validarTSM']){
      header("location:inicio");
      exit();
  } else {
      if($_SESSION['documentos']==1){
        include_once("vistas/modulos/inc/aside.php");
?>

          Control
          Vehiculo de chofer

               Inicio

Vehiculos

Vehiculos

                  <button class="pull-right btn btn-success" id="btnagregar" onclick="mostrarform(true)">
                     Agregar</button>

                      Opciones
                      Placa
                      Modelo
                      Año
                      Titulo
                      Estado

                      Opciones
                      Placa
                      Modelo
                      Año
                      Titulo
                      Estado

                  <form name="formulario" id="formulario" method="POST">

                      Placa *:
                      <input type="hidden" name="idvehiculo" id="idvehiculo">

                      <input type="text" class="form-control" name="placa" id="placa" placeholder="Placa" required>

                      Seguro *:

                      <select id="idseguro" class="form-control selectpicker" data-live-search="true" name="idseguro" required>
                      </select>

                      Titulo:

                      <input type="file" class="form-control" name="imagen" id="imagen">
                      <input type="hidden" class="form-control" name="imagenactual" id="imagenactual">

                      Color:

                      <select id="color" class="form-control selectpicker" data-live-search="true" name="color" required>
                        <option value="">--</option>
                        <option value="AMARILLO">AMARILLO</option>
                        <option value="AZUL">AZUL</option>
                        <option value="ROJO">ROJO</option>
                        <option value="VERDE">VERDE</option>
                        <option value="DORADO">DORADO</option>
                        <option value="BEIGE">BEIGE</option>
                        <option value="BLANCO">BLANCO</option>
                        <option value="GRIS">GRIS</option>
                        <option value="PLATEADO">PLATEADO</option>
                        <option value="VINOTINTO">VINOTINTO</option>
                        <option value="NEGRO">NEGRO</option>
                      </select>

                      Modelo *:

                      <input type="text" class="form-control" name="modelo" id="modelo" required>

                      Año *:

                      <input type="number" class="form-control" name="anovehiculo" id="anovehiculo" required>

                      <button class="btn btn-primary" type="submit" id="btnGuardar">
                         Guardar</button>
                      <button class="btn btn-danger" type="button" onclick="cancelarform()">
                         Cancelar</button>
                      <button type="button" class="btn btn-info" data-toggle="modal" data-target="#modal-primary">
                        Ayuda
                      </button>

                  </form>

                <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
                  ×
                </button>

Modulo Vehiculo

Placa

Ingrese el numero de placa del vehiculo respectivo.

Seguro

Ingrese el codigo de poliza, descrito en la planilla de seguro del vehiculo

Titulo

Suba el certificado de registro del vehiculo en formato PDF.

Modelo

Descripcion del modelo del vehiculo.

Año

Ingrese el año del vehiculo.

                <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cerrar</button>

<?php include_once("vistas/modulos/inc/footer.php"); ?>

<?php
    } else {
      header("location:escritorio");
      ob_end_flush();
      exit();
    }
  }
?>


text:
<!DOCTYPE html>

	<title>GRADUAÇÃO EM REDES DE COMPUTADORES</title>
	<meta name="João Vitor Leite Filismino RA:1701626"/>
	<link rel="stylesheet" href="css/disciplinas.css" type="text/css"/>

A Impacta

Bolsa de estudos

Conheça a faculdade

Convênio

Indique um amigo

Inter cambio

Transferência

Cursos

Graduação

Pós Graduação e MBA

Cursos Técnicos

Up

Cursos Online

Cursos Livres

Arts e Design

Desenvolvimento

Office

E-commerce e Marketing

Hardware

Redes

Software Livre

Planejamento e Gestão

Eventos

Noticías

Blog

Contatos

Login

	3º Semestre

Comunicação de Dados

Diagnóstico e Gerenciamento de Redes

Legislação e Ética

Língua Brasileira de Sinais - LIBRAS (Optativa)

Oficina de Projeto de Empresa 2 - OPE2

Redes Convergentes

Segurança em Sistemas

Sociedade e Sustentabilidade (Optativa)

Switching

Comunicação de Dados

Comunicação de Dados

Diagnóstico e Gerenciamento de Redes

Entenda os conceitos básicos de administração de configurações e serviços de redes e de protocolos de Gerenciamento de Redes, compreendendo os conceitos de tecnologias de Gerenciamento de Redes e o Gerenciamento alinhado aos negócios. Analise de forma geral incidentes na Infraestrutura de TI, desenvolvendo o gerenciamento de infraestrutura, utilizando ferramentas existentes no mercado.

Legislação e Ética

Legislação e Ética

Língua Brasileira de Sinais - LIBRAS (Optativa)

As Línguas de Sinais (LS) são línguas naturais das comunidades surdas. Ao contrário do que muitos imaginam as Línguas de Sinais não são simplesmente mímicas e gestos soltos, utilizados pelos surdos para facilitar a comunicação. São línguas com estrutura gramaticais próprias. Atribui-se às Línguas de Sinais o status de língua por que elas também são compostas pelos níveis linguísticos: o fonológico, o morfológico, o sintático e o semântico.

Oficina de Projeto de Empresa 2 - OPE2

Oficina de Projeto de Empresa 2 - OPE2

Redes Convergentes

Segurança em Sistemas

Segurança em Sistemas

Sociedade e Sustentabilidade (Optativa)

Oferecer ao aluno uma análise da questão socioambiental considerando os seguintes eixos de abordagem:

(a) a relação sociedade-ambiente e suas implicações em variadas dimensões (econômica, ética, tecnológica e cultural);

(b) significados e implicações do conceito de sustentabilidade;

(c) práticas e ações cidadãs envolvendo a dimensão socioambiental.

O objetivo da disciplina é o de contribuir para a formação de profissionais e cidadãos capacitados e comprometidos eticamente com a problemática socioambiental.

Switching

Switching

		© Impacta 2017. Todos os direitos reservados. Política de privacidade


text:
namespace bp = boost::python;

struct LuaEngine_wrapper : osgWidget::LuaEngine, bp::wrapper< osgWidget::LuaEngine > {

    LuaEngine_wrapper(::osgWidget::WindowManager * arg0=0 )
    : osgWidget::LuaEngine( boost::python::ptr(arg0) )
      , bp::wrapper< osgWidget::LuaEngine >(){
        // constructor

    }

    virtual bool close(  ) {
        if( bp::override func_close = this->get_override( "close" ) )
            return func_close(  );
        else{
            return this->osgWidget::LuaEngine::close(  );
        }
    }

    bool default_close(  ) {
        return osgWidget::LuaEngine::close( );
    }

    virtual bool eval( ::std::string const & arg0 ) {
        if( bp::override func_eval = this->get_override( "eval" ) )
            return func_eval( arg0 );
        else{
            return this->osgWidget::LuaEngine::eval( arg0 );
        }
    }

    bool default_eval( ::std::string const & arg0 ) {
        return osgWidget::LuaEngine::eval( arg0 );
    }

    virtual bool initialize(  ) {
        if( bp::override func_initialize = this->get_override( "initialize" ) )
            return func_initialize(  );
        else{
            return this->osgWidget::LuaEngine::initialize(  );
        }
    }

    bool default_initialize(  ) {
        return osgWidget::LuaEngine::initialize( );
    }

    virtual bool runFile( ::std::string const & arg0 ) {
        if( bp::override func_runFile = this->get_override( "runFile" ) )
            return func_runFile( arg0 );
        else{
            return this->osgWidget::LuaEngine::runFile( arg0 );
        }
    }

    bool default_runFile( ::std::string const & arg0 ) {
        return osgWidget::LuaEngine::runFile( arg0 );
    }

    virtual void setThreadSafeRefUnref( bool threadSafe ) {
        if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
            func_setThreadSafeRefUnref( threadSafe );
        else{
            this->osg::Referenced::setThreadSafeRefUnref( threadSafe );
        }
    }

    void default_setThreadSafeRefUnref( bool threadSafe ) {
        osg::Referenced::setThreadSafeRefUnref( threadSafe );
    }

};

void register_LuaEngine_class(){

    { //::osgWidget::LuaEngine
        typedef bp::class_< LuaEngine_wrapper, bp::bases< osgWidget::ScriptEngine >, osg::ref_ptr< LuaEngine_wrapper >, boost::noncopyable > LuaEngine_exposer_t;
        LuaEngine_exposer_t LuaEngine_exposer = LuaEngine_exposer_t( "LuaEngine", bp::init< bp::optional< osgWidget::WindowManager * > >(( bp::arg("arg0")=bp::object() )) );
        bp::scope LuaEngine_scope( LuaEngine_exposer );
        bp::implicitly_convertible< osgWidget::WindowManager *, osgWidget::LuaEngine >();
        { //::osgWidget::LuaEngine::close

            typedef bool ( ::osgWidget::LuaEngine::*close_function_type)(  ) ;
            typedef bool ( LuaEngine_wrapper::*default_close_function_type)(  ) ;

            LuaEngine_exposer.def(
                "close"
                , close_function_type(&::osgWidget::LuaEngine::close)
                , default_close_function_type(&LuaEngine_wrapper::default_close) );

        }
        { //::osgWidget::LuaEngine::eval

            typedef bool ( ::osgWidget::LuaEngine::*eval_function_type)( ::std::string const & ) ;
            typedef bool ( LuaEngine_wrapper::*default_eval_function_type)( ::std::string const & ) ;

            LuaEngine_exposer.def(
                "eval"
                , eval_function_type(&::osgWidget::LuaEngine::eval)
                , default_eval_function_type(&LuaEngine_wrapper::default_eval)
                , ( bp::arg("arg0") ) );

        }
        { //::osgWidget::LuaEngine::initialize

            typedef bool ( ::osgWidget::LuaEngine::*initialize_function_type)(  ) ;
            typedef bool ( LuaEngine_wrapper::*default_initialize_function_type)(  ) ;

            LuaEngine_exposer.def(
                "initialize"
                , initialize_function_type(&::osgWidget::LuaEngine::initialize)
                , default_initialize_function_type(&LuaEngine_wrapper::default_initialize) );

        }
        { //::osgWidget::LuaEngine::runFile

            typedef bool ( ::osgWidget::LuaEngine::*runFile_function_type)( ::std::string const & ) ;
            typedef bool ( LuaEngine_wrapper::*default_runFile_function_type)( ::std::string const & ) ;

            LuaEngine_exposer.def(
                "runFile"
                , runFile_function_type(&::osgWidget::LuaEngine::runFile)
                , default_runFile_function_type(&LuaEngine_wrapper::default_runFile)
                , ( bp::arg("arg0") ) );

        }
        { //::osgWidget::ScriptEngine::getLastErrorText

            typedef ::std::string const & ( ::osgWidget::ScriptEngine::*getLastErrorText_function_type)(  ) const;

            LuaEngine_exposer.def(
                "getLastErrorText"
                , getLastErrorText_function_type(&::osgWidget::ScriptEngine::getLastErrorText)
                , bp::return_value_policy< bp::copy_const_reference >() );

        }
    }

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Filibuster</title> <link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">

Results for "hs_outlook"

Index

your romantic outlook for today is fair.

your romantic outlook for today is mild.

your romantic outlook for today is stormy.

your romantic outlook for today is fair.

your romantic outlook for today is fair.

your financial outlook for today is good.

your financial outlook for today is good.

your romantic outlook for today is good.

your financial outlook for today is good.

your romantic outlook for today is poor.

your romantic outlook for today is stormy.

your financial outlook for today is good.

your financial outlook for today is mild.

your financial outlook for today is poor.

your romantic outlook for today is stormy.

your financial outlook for today is mild.

your financial outlook for today is poor.

your financial outlook for today is poor.

your romantic outlook for today is stormy.

your romantic outlook for today is stormy.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.codelikethewind</groupId>
	<artifactId>simple-ejb-project</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>simple-ejb-project</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.6</maven.compiler.source>
		<maven.compiler.target>1.6</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.spec.javax.ejb</groupId>
			<artifactId>jboss-ejb-api_3.1_spec</artifactId>
			<version>1.0.2.Final-redhat-3</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.spec.javax.servlet</groupId>
			<artifactId>jboss-servlet-api_3.0_spec</artifactId>
			<version>1.0.2.Final-redhat-2</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.0.0</version>
			</plugin>
		</plugins>
	</build>
</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 9(1): 211 (1979)

#### Original name
Rhodocollybia maculata var. nigra Lennox

### Remarks
null


text:
let _ = require('lodash');

/**
 * Provides methods for converting various values to maps.
 */
export class MapConverter {

    /**
     * Static method for converting values to nullable maps.
     *
     * Conversion cases:
     * - if 'value' is null - null will be returned;
     * - if 'value' is an array - it will be converted to a map, whose keys are the array's indexes (as strings) and whose values
     * correspond to the values at the given indexes;
     * - if 'value' is an object (map) - it will be returned as is;
     * - otherwise - null will be returned.
     *
     * @param value     the value to convert.
     * @returns         the result of the conversion. If 'value' was null or is not convertible - null
     *                  will be returned.
     */
    public static toNullableMap(value: any): any {
        if (value == null)
            return null;
        else if (_.isArray(value)) {
            let map: any = {};
            for (let i = 0; i < value.length; i++)
                map[i.toString()] = value[i];
            return map;
        }
        else
            return _.isObject(value) ? value : null;
    }

    /**
     * Static method for converting values to maps using {@link #toNullableMap}.
     * An empty map will be used as the default value for the conversion.
     *
     * @param value     the value to convert.
     *
     * @see #toNullableMap
     */
    public static toMap(value: any): any {
        return MapConverter.toNullableMap(value) || {};
    }

    /**
     * Static method for converting values to maps using {@link #toNullableMap}.
     * If null is returned by the conversion, then this method will return the default
     * value passed.
     *
     * @param value         the value to convert.
     * @param defaultValue  the default value to return if the conversion returns null.
     *
     * @see #toNullableMap
     */
    public static toMapWithDefault(value: any, defaultValue: any): any {
        return MapConverter.toNullableMap(value) || defaultValue;
    }

}