Web messages format document number что это
Web messages format document number что это
MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.
Note: MessageFormat differs from the other Format classes in that you create a MessageFormat object with one of its constructors (not with a getInstance style factory method). The factory methods aren’t necessary because MessageFormat itself doesn’t implement locale specific behavior. Any locale specific behavior is defined by the pattern that you provide as well as the subformats used for inserted arguments.
Patterns and Their Interpretation
The FormatType and FormatStyle values are used to create a Format instance for the format element. The following table shows how the values map to Format instances. Combinations not shown in the table are illegal. A SubformatPattern must be a valid pattern string for the Format subclass used.
Usage Information
Here are some examples of usage. In real internationalized programs, the message format pattern and other static strings will, of course, be obtained from resource bundles. Other parameters will be dynamically determined at runtime.
The following example creates a MessageFormat instance that can be used repeatedly:
For more sophisticated patterns, you can use a ChoiceFormat to produce correct forms for singular and plural:
You can create the ChoiceFormat programmatically, as in the above example, or by using a pattern. See ChoiceFormat for more information.
When a single argument is parsed more than once in the string, the last match will be the final result of the parsing. For example,
Likewise, parsing with a MessageFormat object using patterns containing multiple occurrences of the same argument would return the last match. For example,
Synchronization
Message formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
Nested Class Summary
Modifier and Type | Class and Description |
---|---|
static class | MessageFormat.Field |
Constructor Summary
Method Summary
Modifier and Type | Method and Description |
---|---|
void | applyPattern(String pattern) |
Methods inherited from class java.text.Format
Methods inherited from class java.lang.Object
Constructor Detail
MessageFormat
MessageFormat
Method Detail
setLocale
getLocale
applyPattern
toPattern
setFormatsByArgumentIndex
If an argument index is used for more than one format element in the pattern string, then the corresponding new format is used for all such format elements. If an argument index is not used for any format element in the pattern string, then the corresponding new format is ignored. If fewer formats are provided than needed, then only the formats for argument indices less than newFormats.length are replaced.
setFormats
If more formats are provided than needed by the pattern string, the remaining ones are ignored. If fewer formats are provided than needed, then only the first newFormats.length formats are replaced.
Since the order of format elements in a pattern string often changes during localization, it is generally better to use the setFormatsByArgumentIndex method, which assumes an order of formats corresponding to the order of elements in the arguments array passed to the format methods or the result array returned by the parse methods.
setFormatByArgumentIndex
If the argument index is used for more than one format element in the pattern string, then the new format is used for all such format elements. If the argument index is not used for any format element in the pattern string, then the new format is ignored.
setFormat
Since the order of format elements in a pattern string often changes during localization, it is generally better to use the setFormatByArgumentIndex method, which accesses format elements based on the argument index they specify.
getFormatsByArgumentIndex
If an argument index is used for more than one format element in the pattern string, then the format used for the last such format element is returned in the array. If an argument index is not used for any format element in the pattern string, then null is returned in the array.
getFormats
Since the order of format elements in a pattern string often changes during localization, it’s generally better to use the getFormatsByArgumentIndex method, which assumes an order of formats corresponding to the order of elements in the arguments array passed to the format methods or the result array returned by the parse methods.
format
The text substituted for the individual format elements is derived from the current subformat of the format element and the arguments element at the format element’s argument index as indicated by the first matching line of the following table. An argument is unavailable if arguments is null or has fewer than argumentIndex+1 elements.
format
format
formatToCharacterIterator
The text of the returned AttributedCharacterIterator is the same that would be returned by
parse
parse
See the parse(String, ParsePosition) method for more information on message parsing.
parseObject
See the parse(String, ParsePosition) method for more information on message parsing.
Web messages format document number что это
This repo was migrated to the monorepo
Formats ICU Message strings with number, date, plural, and select placeholders to create localized messages.
This package aims to provide a way for you to manage and format your JavaScript app’s string messages into localized strings for people using your app. You can use this package in the browser and on the server via Node.js.
This implementation is based on the Strawman proposal, but there are a few places this implementation diverges.
Note: This IntlMessageFormat API may change to stay in sync with ECMA-402, but this package will follow semver.
Messages are provided into the constructor as a String message, or a pre-parsed AST object.
The string message is parsed, then stored internally in a compiled form that is optimized for the format() method to produce the formatted string for displaying to the user.
Common Usage Example
A very common example is formatting messages that have numbers with plural labels. With this package you can make sure that the string is properly formatted for a person’s locale, e.g.:
The message syntax that this package uses is not proprietary, in fact it’s a common standard message syntax that works across programming languages and one that professional translators are familiar with. This package uses the ICU Message syntax and works for all CLDR languages which have pluralization rules defined.
Supports plural, select, and selectordinal message arguments.
Optimized for repeated calls to an IntlMessageFormat instance’s format() method.
Supports defining custom format styles/options.
Supports escape sequences for message syntax chars, e.g.: «\\
Modern Intl Dependency
This package assumes that the Intl global object exists in the runtime. Intl is present in all modern browsers (IE11+) and Node (with full ICU). The Intl methods we rely on are:
Loading Intl MessageFormat in a browser
Loading Intl MessageFormat in Node.js
Simply require() this package:
NOTE: Your Node has to include full ICU
To create a message to format, use the IntlMessageFormat constructor. The constructor takes three parameters:
IntlMessageFormat uses Intl.NumberFormat.supportedLocalesOf() to determine which locale data to use based on the locales value passed to the constructor. The result of this resolution process can be determined by call the resolvedOptions() prototype method.
This method returns an object with the options values that were resolved during instance creation. It currently only contains a locale property; here’s an example:
Once the message is created, formatting the message is done by calling the format() method on the instance and passing a collection of values :
Note: A value must be supplied for every argument in the message pattern the instance was constructed with.
User Defined Formats
Define custom format styles is useful you need supply a set of options to the underlying formatter; e.g., outputting a number in USD:
In this example, we’re defining a USD number format style which is passed to the underlying Intl.NumberFormat instance as its options.
This example shows how to use the ICU Message syntax to define a message that has a plural label; e.g., «You have 10 photos» :
This software is free to use under the Yahoo! Inc. BSD license. See the LICENSE file for license text and copyright information.
About
[MIGRATED] Format a string with placeholders, including plural and select support to create localized messages.
Formatting Messages
Contents
Overview
Messages are user-visible strings, often with variable elements like names, numbers and dates. Message strings are typically translated into the different languages of a UI, and translators move around the variable elements according to the grammar of the target language.
For this to work in many languages, a message has to be written and translated as a single unit, typically a string with placeholder syntax for the variable elements. If the user-visible string were concatenated directly from fragments and formatted elements, then translators would not be able to rearrange the pieces, and they would have a hard time translating each of the string fragments.
MessageFormat
The ICU MessageFormat class uses message «pattern» strings with variable-element placeholders (called “arguments” in the API docs) enclosed in
Complex Argument Types
Certain types of arguments select among several choices which are nested MessageFormat pattern strings. Keeping these choices together in one message pattern string facilitates translation in context, by one single translator. (Commercial translation systems often distribute different messages to different translators.)
It is tempting to cover only a minimal part of a message string with a complex argument (e.g., plural). However, this is difficult for translators for two reasons: 1. They might have trouble understanding how the sentence fragments in the argument sub-messages interact with the rest of the sentence, and 2. They will not know whether and how they can shrink or grow the extent of the part of the sentence that is inside the argument to make the whole message work for their language.
Recommendation: If possible, use complex arguments as the outermost structure of a message, and write full sentences in their sub-messages. If you have nested select and plural arguments, place the select arguments (with their fixed sets of choices) on the outside and nest the plural arguments (hopefully at most one) inside.
Note: In a plural argument like in the example above, if the English message has both =0 and =1 (up to =offset +1) then it does not need a “ one ” variant because that would never be selected. It does always need an “ other ” variant.
Note: The translation system and the translator together need to add “ one ”, “ few ” etc. if and as necessary per target language.
Quoting/Escaping
Argument formatting
There are also several ways to control the formatting.
Predefined styles (recommended)
Skeletons (recommended)
Date skeletons:
Number formatter skeletons:
Format the parameters separately (recommended)
This offers maximum control, and is preferred to using custom format objects (see below).
String patterns (discouraged)
These can be used for numbers, dates, and times, but they are locale-sensitive, and they therefore would need to be localized by your translators, which adds complexity to the localization, and placeholder details are often not accessible by translators. If such a pattern is not localized, then users see confusing formatting. Consider using skeletons instead of patterns in your message strings.
Allowing translators to localize date patterns is error-prone, as translators might make mistakes (resulting in invalid ICU date formatter syntax). Also, CLDR provides curated patterns for many locales, and using your own pattern means that you don’t benefit from that CLDR data and the results will likely be inconsistent with the rest of the patterns that ICU uses.
It is also a bad internationalization practice, because most companies only translate into “generic” versions of the languages (French, or Spanish, or Arabic). So the translated patterns get used in tens of countries. On the other hand, skeletons are localized according to the MessageFormat locale, which should include regional variants (e.g., “fr-CA”).
Custom Format Objects (discouraged)
The MessageFormat class allows setting custom Format objects to format arguments, overriding the arguments’ pattern specification. This is discouraged: For custom formatting of some values it should normally suffice to format them externally and to provide the formatted strings to the MessageFormat.format() methods.
Some of these methods (the ones corresponding to the original JDK MessageFormat API) address the top-level arguments in their order of appearance in the pattern string, which is usually not useful because it varies with translations. Newer methods address arguments by argument number (“index”) or name.
Examples
The following code fragment created this output: “At 4:34 PM on March 23, there was a disturbance in the Force on planet 7.”
Формат часто используется вместе с RTMP Adobe для установления соединений и команд управления доставкой потокового мультимедиа. В этом случае данные AMF инкапсулируются в блок, который имеет заголовок, который определяет такие вещи, как длина и тип сообщения (будь то «эхо-запрос», «команда» или мультимедийные данные).
СОДЕРЖАНИЕ
Анализ формата
AMF был представлен в Flash Player 6, и эта версия называется AMF0. Он оставался неизменным до выпуска Flash Player 9 и ActionScript 3.0, когда новые типы данных и языковые функции потребовали обновления под названием AMF3. В Flash Player 10 добавлены векторные и словарные типы данных, задокументированные в пересмотренной спецификации от января 2013 года.
Adobe Systems опубликовала спецификацию протокола двоичных данных AMF в декабре 2007 года и объявила, что поддержит сообщество разработчиков, чтобы сделать этот протокол доступным для всех основных серверных платформ.
Автономный пакет AMF
Длина | Имя | Тип | По умолчанию |
---|---|---|---|
16 бит | версия | uimsbf | 0 или 3 |
16 бит | количество заголовков | uimsbf | 0 |
количество заголовков * 56 + бит | заголовок-тип-структура | двоичный | свободная форма |
16 бит | счетчик сообщений | uimsbf | 1 |
количество сообщений * 64 + бит | структура типа сообщения | двоичный | свободная форма |
Длина | Имя | Тип | По умолчанию |
---|---|---|---|
16 бит | заголовок-имя-длина | uimsbf | 0 |
длина имени-заголовка * 8 бит | заголовок-имя-строка | UTF-8 | пустой |
8 бит | должен понимать | uimsbf | 0 |
32 бит | длина заголовка | simsbf | Переменная |
длина заголовка * 8 бит | AMF0 или AMF3 | двоичный | свободная форма |
Длина | Имя | Тип | По умолчанию |
---|---|---|---|
16 бит | target-uri-length | uimsbf | Переменная |
длина целевого URI * 8 бит | target-uri-string | UTF-8 | Переменная |
16 бит | длина ответа-uri | uimsbf | 2 |
длина ответа-URI * 8 бит | ответ-URI-строка | UTF-8 | «/ 1» |
32 бит | длина сообщения | simsbf | Переменная |
длина сообщения * 8 бит | AMF0 или AMF3 | двоичный | свободная форма |
uimsbf: целое число без знака, сначала старший бит
simsbf: целое число со знаком, сначала старший бит
Формат определяет различные типы данных, которые можно использовать для кодирования данных. Adobe заявляет, что AMF в основном используется для представления графов объектов, которые включают именованные свойства в форме пар ключ-значение, где ключи закодированы как строки, а значения могут быть любого типа данных, таких как строки или числа, а также массивы и другие объекты. XML поддерживается как собственный тип. Каждый тип обозначается одним байтом, предшествующим фактическим данным. Значения этого байта следующие (для AMF0):
Объекты AMF начинаются с (0x03), за которым следует набор пар ключ-значение, и заканчиваются (0x09) в качестве значения (которому предшествует 0x00 0x00 в качестве пустой ключевой записи). Ключи кодируются как строки с подразумеваемым байтом (0x02) ‘определение типа’ (не включаемым в сообщение). Значения могут быть любого типа, включая другие объекты, и таким образом можно сериализовать целые графы объектов. И ключам объекта, и строкам предшествуют два байта, обозначающие их длину в байтах. Это означает, что строкам предшествуют три байта, включая байт типа 0x02. Нулевые типы содержат только свое определение типа (0x05). Числа кодируются как числа с плавающей запятой двойной точности и состоят из восьми байтов.
В качестве примера при кодировании объекта ниже в коде actionscript 3.
Данные, хранящиеся в ByteArray:
Шестнадцатеричный код | ASCII | |||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
03 00 04 6e 61 6d 65 02 00 04 4d 69 6b 65 00 03 61 67 65 00 40 3e 00 00 00 00 00 00 00 05 61 6c 69 61 73 02 00 04 4d 69 6b 65 00 00 09 |
Value | Meaning |
---|---|
FORMAT_MESSAGE_ALLOCATE_BUFFER 0x00000100 | The function allocates a buffer large enough to hold the formatted message, and places a pointer to the allocated buffer at the address specified by lpBuffer. The lpBuffer parameter is a pointer to an LPTSTR; you must cast the pointer to an LPTSTR (for example, (LPTSTR)&lpBuffer ). The nSize parameter specifies the minimum number of TCHARs to allocate for an output message buffer. The caller should use the LocalFree function to free the buffer when it is no longer needed. If the length of the formatted message exceeds 128K bytes, then FormatMessage will fail and a subsequent call to GetLastError will return ERROR_MORE_DATA. In previous versions of Windows, this value was not available for use when compiling Windows Store apps. As of WindowsВ 10 this value can be used. Windows ServerВ 2003 and WindowsВ XP:В В If the length of the formatted message exceeds 128K bytes, then FormatMessage will not automatically fail with an error of ERROR_MORE_DATA. |
FORMAT_MESSAGE_ARGUMENT_ARRAY 0x00002000 | The Arguments parameter is not a va_list structure, but is a pointer to an array of values that represent the arguments. This flag cannot be used with 64-bit integer values. If you are using a 64-bit integer, you must use the va_list structure. |
FORMAT_MESSAGE_FROM_HMODULE 0x00000800 | The lpSource parameter is a module handle containing the message-table resource(s) to search. If this lpSource handle is NULL, the current process’s application image file will be searched. This flag cannot be used with FORMAT_MESSAGE_FROM_STRING. If the module has no message table resource, the function fails with ERROR_RESOURCE_TYPE_NOT_FOUND. |
FORMAT_MESSAGE_FROM_STRING 0x00000400 | The lpSource parameter is a pointer to a null-terminated string that contains a message definition. The message definition may contain insert sequences, just as the message text in a message table resource may. This flag cannot be used with FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM. |
FORMAT_MESSAGE_FROM_SYSTEM 0x00001000 | The function should search the system message-table resource(s) for the requested message. If this flag is specified with FORMAT_MESSAGE_FROM_HMODULE, the function searches the system message table if the message is not found in the module specified by lpSource. This flag cannot be used with FORMAT_MESSAGE_FROM_STRING. If this flag is specified, an application can pass the result of the GetLastError function to retrieve the message text for a system-defined error. |
FORMAT_MESSAGE_IGNORE_INSERTS 0x00000200 | Insert sequences in the message definition such as %1 are to be ignored and passed through to the output buffer unchanged. This flag is useful for fetching a message for later formatting. If this flag is set, the Arguments parameter is ignored. |
В
The low-order byte of dwFlags can specify the maximum width of a formatted output line. The following are possible values of the low-order byte.
Value | Meaning |
---|---|
0 | There are no output line width restrictions. The function stores line breaks that are in the message definition text into the output buffer. |
FORMAT_MESSAGE_MAX_WIDTH_MASK 0x000000FF | The function ignores regular line breaks in the message definition text. The function stores hard-coded line breaks in the message definition text into the output buffer. The function generates no new line breaks. |
В
If the low-order byte is a nonzero value other than FORMAT_MESSAGE_MAX_WIDTH_MASK, it specifies the maximum number of characters in an output line. The function ignores regular line breaks in the message definition text. The function never splits a string delimited by white space across a line break. The function stores hard-coded line breaks in the message definition text into the output buffer. Hard-coded line breaks are coded with the %n escape sequence.
[in, optional] lpSource
The location of the message definition. The type of this parameter depends upon the settings in the dwFlags parameter.
dwFlags Setting | Meaning |
---|---|
FORMAT_MESSAGE_FROM_HMODULE 0x00000800 | A handle to the module that contains the message table to search. |
FORMAT_MESSAGE_FROM_STRING 0x00000400 | Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. |
В
If neither of these flags is set in dwFlags, then lpSource is ignored.
The message identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.
The language identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.
If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only. If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND. If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order:
A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in lpBuffer.
This buffer cannot be larger than 64K bytes.
If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the size of the output buffer, in TCHARs. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer.
The output buffer cannot be larger than 64K bytes.
[in, optional] Arguments
An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on.
The interpretation of each value depends on the formatting information associated with the insert in the message definition. The default is to treat each value as a pointer to a null-terminated string.
By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments. The state of the va_list argument is undefined upon return from the function. To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start.
If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values. Each insert must have a corresponding element in the array.
Return value
If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
Within the message text, several escape sequences are supported for dynamically formatting the message. These escape sequences and their meanings are shown in the following tables. All escape sequences start with the percent character (%).
The format string can include a width and precision specifier for strings and a width specifier for integers. Use an asterisk () to specify the width and precision. For example, %1!.*s! or %1!*u!.
If you do not use the width and precision specifiers, the insert numbers correspond directly to the input arguments. For example, if the source string is «%1 %2 %1» and the input arguments are «Bill» and «Bob», the formatted output string is «Bill Bob Bill».
However, if you use a width and precision specifier, the insert numbers do not correspond directly to the input arguments. For example, the insert numbers for the previous example could change to «%1!*.*s! %4 %5!*s!».
The insert numbers depend on whether you use an arguments array (FORMAT_MESSAGE_ARGUMENT_ARRAY) or a va_list. For an arguments array, the next insert number is n+2 if the previous format string contained one asterisk and is n+3 if two asterisks were specified. For a va_list, the next insert number is n+1 if the previous format string contained one asterisk and is n+2 if two asterisks were specified.
If you want to repeat «Bill», as in the previous example, the arguments must include «Bill» twice. For example, if the source string is «%1!*.*s! %4 %5!*s!», the arguments could be, 4, 2, Bill, Bob, 6, Bill (if using the FORMAT_MESSAGE_ARGUMENT_ARRAY flag). The formatted string would then be «В В Bi Bob В В Bill».
Repeating insert numbers when the source string contains width and precision specifiers may not yield the intended results. If you replaced %5 with %1, the function would try to print a string at address 6 (likely resulting in an access violation).
Floating-point format specifiers—e, E, f, and g—are not supported. The workaround is to use the StringCchPrintf function to format the floating-point number into a temporary buffer, then use that buffer as the insert string.
Inserts that use the I64 prefix are treated as two 32-bit arguments. They must be used before subsequent arguments are used. Note that it may be easier for you to use StringCchPrintf instead of this prefix.
Any other nondigit character following a percent character is formatted in the output message without the percent character. Following are some examples.
Format string | Resulting output |
---|---|
%% | A single percent sign. |
%b | A single space. This format string can be used to ensure the appropriate number of trailing spaces in a message text line. |
%. | A single period. This format string can be used to include a single period at the beginning of a line without terminating the message text definition. |
%! | A single exclamation point. This format string can be used to include an exclamation point immediately after an insert without its being mistaken for the beginning of a format string. |
%n | A hard line break when the format string occurs at the end of a line. This format string is useful when FormatMessage is supplying regular line breaks so the message fits in a certain width. |
%r | A hard carriage return without a trailing newline character. |
%t | A single tab. |
В
Security Remarks
Examples
The FormatMessage function can be used to obtain error message strings for the system error codes returned by GetLastError. For an example, see Retrieving the Last-Error Code.
The following example shows how to implement the previous example using va_list.
- телец к какой стихии относится по гороскопу
- Как играть на якутском варгане