Auxiliary Tcl Commands

Beside the listed commands for manipulating chemical and non-chemical objects, the standard Tcl scripting interface is enhanced with a collection of additional commands which do not belong to one of the two big groups. This is a list of these commands:

Mathematical expression enhancements

In addition to these commands, the Tcl math expression engine was extended by the following functions:

bitvector

bitvector subcommand vector ?vector?...

This command provides basic functionality for the processing of bit vectors on a string level. Bit vectors understood by this command consist of 0 and 1 characters, optionally prefixed by a percent or B character. Bitvectors with this encoding style can, for example, be obtained from a Tcl data recall command on chemistry object bitvector data item.

Example:

set vector [ens get $ehandle E_SCREEN]

The following subcommands are available:

bitvector and vector ?vector?...
bitvector or vector ?vector?...
bitvector xor vector ?vector?...
bitvector nand vector ?vector?...
bitvector nor vector ?vector?...

These are the standard boolean operations. nand and nor yields the inverted result of the and and or operations. If not arguments except the first are given, the result is the input vector for and, or, xor , and the inverted input vector for the rest. In case the vectors are of different lengths, they are virtually padded with zero bits to the size of the largest vector.

bitvector not vector

Invert the vector in bit-wise fashion.

bitvector test1 vector ?offset? ?len?
bitvector test0 vecvtor ?offset? ?len?

Return a list of the vector positions (starting with 0) which have a set or unset bit. Optionally, an offset for the first bit to be tested, and the maximum number of bits to be tested may be specified. By default, testing begins with the first vector position (index 0) and continues until the end of the vector. The subcommand test1 may be abbreviated to test .

bitvector create length ?value?

Generated a new vector of the specified length. By default, it is set to all zeros. The value parameter, which may be 0 or 1, can be used to generate a vector with all set bits.

bitvector screen vector1 vector2

Perform a screening operation on the bitvector. This command returns the first index position where a bit is set in the second vector, but not in the first. If all set bits in the second vector have counterparts in the first vector, minus one is returned.

bitvector count vector1 ?vector2?...

Count the total number of set bits in all the specified vectors.

bitvector distance vector1 vector2

Compute the Hamming distance between the vectors.

bread

bread tcl_filehandle format ?var..?

This command reads formatted binary data from an output channel. The specified Tcl channel is automatically configured for binary data for the duration of the command and then restored to the original state.

The command is complementary to the bwrite command described below and uses the same formatting specifications.

Multiple values sharing the same format can be read in one statement with a set of recipient variables is specified. The return value is the value of the last item read. If no variables are used, one item is read and returned, but not stored in a variable.

Example;

set s [bread $channel string16]

bwrite

bwrite tcl_filehandle format data ?data?...

This command writes formatted binary data to an output channel. The specified Tcl channel is automatically configured for binary data for the duration of the command and then restored to the original state.

If more than one data item is specified, the same format is used for all the data items. For most formats, the binary data layout is not changed and it thus platform-dependent. The exception are those formats which are prefixed with an X: These follow the platform-independent XDR encoding standard (RFC 1014) in their layout (network byte order, MSB first), but not in the stored item size (the byte size of smaller objects is not expanded to multiples of four). The following formats are supported:

The string format may contain additional length and pad character specifications. If a pad character is used, it must be supplied as its ISO Latin code. This makes it simple to use zero bytes as filler.

Example:

bwrite stdout string16:[ctype ord x]

writes a string which always occupies exactly 16 bytes. If it is longer, the extra characters are ignored. If it is shorter, it is padded with “x“ characters. A zero byte is not written, because this string has an explicit length.

The bread command provides the complementary functionality to read binary data into variables using the same format specifications as template.

creverse

creverse string

Reverse a string.

Example:

creverse abc

returns cba .

color

color ?-alpha? ?-depth n? ?-hex? ?-name? ?-shade delta? colorname/colorspec

Decode a color name. On Unix systems, color names are looked up in the local X11 color database. On the PC platform, a representative X11 color database dump is compiled into the application. In addition to English color names, the standard hex color notation, such as #rrggbb or #rgb, may be used, with or without alpha channel data. If a hex color notation has 4, 8 or 16 hex digits, the value is interpreted as # rgba , # rrggbbaa and # rrrrggggbbbbaaaa , respectively. In case of 12 hex digits (12 is both divisible by 3 and 4), the interpretation # rrrrggggbbbb takes precedence. Color names are case-insensitive.

By default, a color depth of 16 bits is assumed, and the returned color component values are thus in the range 0..65535. Smaller or larger color component value ranges may be specified by an explicit depth value, which must be in the range between 2 and 24.

If the - shade option is used, the decoded color value is darkened or brightened by the specified amount by component-wise addition before it is output in the selected format. The shading value is scaled according to the selected color depth, i.e. with a color depth of 8, the useful minimum and maximum scale values are -255 and +255, while with a color depth of 16 the limits are -65525 and +65535. The transformed color values are automatically clamped to the white and black extremes, so the output will always be a valid color representation. Shading is not applied to the alpha/opacity channel. A shading value of zero has no effect in any color depth.

The default return format is a list with the decimal RGB values of the decoded color. If the - hex option is set, the output is formatted as a single hex-encoded color value. If the - alpha option is given, the format of the output includes the opacity value as the fourth component in RGBA order, either as an additional list element or appended to the hex string.

With the - name option the command attempts to find the most closely matching color name in the database for the decoded and transformed color values and return that name instead of a color component list or hex encoding.

The command may also be spelled colour instead of color .

Example:

color -depth 8 -hex Red

returns #FF0000.

color -depth 8 -shade -0x10 -hex #808080

returns #707070

daemonize

daemonize ?priority? ?closefiles?

Transform the current process into a daemon process which is decoupled from all control terminals and runs in the background until finished or terminated. The current process is forked, and the old foreground process exited.

By default, the background process priority is unchanged. Alternatively, a new priority may be specified as the first optional argument. If it not an empty string, an attempt is made to set the process priority to the new value. No error message is generated when the attempt fails. Useful priority values depend on the platform. On Linux, the range is 0...20, with 20 being the lowest priority. Increasing the priority, by using a value lower than the current process value, requires non-standard permissions, usually an effective application user ID of root.

By default, all open file handles are closed. If the optional closefiles parameter is set to 0, most file handles are kept open. An exception are the standard input, output and error channels. These are always redirected to /dev/null, regardless of the option value. Note that the closing of the file descriptors does not automatically invalidate any Tcl scripting language references to these, such as standard Tcl file or socket handles, or toolkit molfile handles. These should be explicitly closed by the application script before this function is called. Otherwise, any use of these stale handles results in errors.

This command is only available on Unix-based platforms.

decode

decode mode data ?key?

This command decodes a number of commonly encountered encoding formats for string and binary data. The decoded data is returned as command result. The mode parameter decides which decoding scheme is used:

The decoded data may contain zero-bytes and other special characters and may thus need special care in further processing. The counterpart of the decode command is the encode command, which can be used to encode data in all recognized decoder formats.

For historical reasons, the - zlib* variants can also be invoked as the same command starting with - zip* .

encode

encode mode data ?mode_arg?

This command is the counterpart to the decode command. It is not completely identical, tough - the decoder automatically recognizes certain variants of encoding schemes, which need to be specified in detail on the encoder side. The encoded datam which may be binary, is returned as command result. The possible encoding modes are:

The result of this command is likely to contain zero bytes and other special characters. Further processing of this data may require caution.

The - zlib* encoding variants can also be invoked as the same command starting with - zip* .

fcgi

fcgi subcommand ?args?

This command manages I/O when running an application script as an FastCGI ( FCGI ) Web application. Only selected interpreters provide this command, for example the standard tclcactvs and the stand-alone csweb variant.

In addition to providing the fcgi command, these interpreters also register additional pre-opened Tcl channels f cgi-stdin , fcgi-stdout and fcgi-stderr. Reading from or writing to these channels with the normal Tcl I/O commands directly moves the data to or from the FCGI server communication channels.

The following subcommands are supported:

fcgi accept ?redirect? ?autoexit?

This command enables FCGI -style socket communication with the Web server controlling this application and is usually the first command in an FCGI application.

If the redirect flag is set (it is set by default), the stdout , stderr and stdin Tcl channels are redirected to the corresponding FCGI multiplex socket. All normal Tcl I/O commands automatically use the multiplex socket instead of the standard channels if they are referring implicitly or explicitly to the standard channels. In addition, Web-typical properties like E_GIF , E_VRML , E_PICT_IMAGE , E_EPS_IMAGE , E_SVG_IMAGE , E_EMF_IMAGE and X_GIF are aware of this redirection and also send their output to the socket in case it is sent to one of the standard channels instead of a disk file. The current redirection status is mirrored in the read-only control variable ::cactvs(fcgi_redirect) .

If the autoexit flag is set (it is also set by default), the application automatically exits if the socket communication results in an error or EOF . The return value is a status code and zero in case a normal communication was initiated. In case automatic exiting is disabled, a negative status code is returned if there is an error.

fcgi finish ?redirect?

This command finishes the processing of a request. All buffered output is flushed to the server. The next request can then be waited for by a new call to fcgi accept .

If the redirect flag is set (it is set by default), any existing stdout , stderr and stdin redirections the toe FCGI socket are canceled. All standard channels as seen by the script interpreter and certain image properties (see description of fcgi accept command) are reconnected to their original streams. The current redirection status is mirrored in the read-only control variable ::cactvs(fcgi_redirect).

fcgi puts ?-nonewline? ?channel? data

This command is the same as the standard Tcl puts command, except that it operates on the stdout and stderr equivalents of the FCGI communication model. In case a channel is specified, only stdout and stderr are possible argument values. The command is primarily useful in case the automatic redirection feature of the fcgi accept command was not used. Output is only possible after the invocation of an fcgi accept command and before the issue of a closing fcgi finish command.

fcgi read

This command reads the FCGI equivalent of stdin until EOF is encountered and returns the data as a byte vector. In case FCGI redirection is active, the standard Tcl read command can be used as an equivalent.

fcgi redirect ?on/off?

This command may be used to explicitly invoke or cancel the redirection of the standard Tcl channels stdin , stdout and stderr to the FCGI equivalents. In case no boolean redirection argument is given, the current redirection status is reported. In case a new status is set, the command returns the previous status. The current redirection status is also mirrored in the read-only control variable ::cactvs(fcgi_redirect).

fcgi status code

This command can be used to set the exit status when the automatic exiting feature of the fcgi accept command is used. This command may be called any time.

Example:

while {[fcgi accept]>=0} {
			set data [read stdin]
			if {$data==””} { set data $env(QUERY_STRING) }
			uncgi $data params
			do_something $params(form_url_arg1) $params(form_url_arg2)
			fcgi finish
}

This code snippet shows a typical main loop in an FCGI application. Standard I/O redirection is used for convenience, and in case there are any communication errors with the Web server, or shutdown instructions, like closing of the stdin channel, are received from the server, the application exists. If the application scripts exits, it is (in a typical set-up, this depends on the Web server configuration) be restarted by the Web server at a later time when the next request comes in.

fetch

fetch ?-agent agent? ?-cookie cookie? -header no/yes/exclusive? \			?-modified time_in_secs? ?-password password? \			?-referer referer? ?-setcookie cookie? ?-timeout nsecs? \			?-tofile 0/1? ?-user username? url ?statusvar?

This command is used to retrieved data from network locations identified by URLs. The default action is to fetch the data and return is as uninterpreted byte data, but without protocol header information. The following options can be used to modify the command action:

The url argument is a standard Internet URL. The exact types of supported URLs vary with the interpreter and, for database URLs, also depend on loaded database I/O modules. A basic set consisting of the file:, http:, ftp: and gopher: protocols and URL encoding standards is always supported. FTP transfer uses passive mode where possible. All standard protocol drivers also support the transport of user id and password information.

If a status variable parameter is specified, it is interpreted as the name of a Tcl array variable which is created if necessary, reset and filled with status information. Its elements are size (the download data size, without header), lastmodified (the remote file modification date), location (the last download URL, which can be different from the original retrieval URL in case of redirects), mimetype (the mime type of the data, as perceived by the remote server), various cookie data variants (see below) and finally status for the integer return status code.

The elements for the cookie data element encoding variants are named cookies (a list of all received cookies in Netscape format), cookiedicts (the same as list of dictionaries), and individual per-cookie elements cookie%d and cookiedict%d, where the placeholder is the cookie index starting with zero. The Netscape cookie format is a tab-separated string of six elements encoding the cookie domain, its domain access flag, the path, secure access flag, expiration date, cookie name and value. Splitting these strings to access individual data items should be done explicitly on the tab character since implicit list conversion is not reliable for this encoding. In the dictionary list and individual cookie dictionary encoding variants, the dictionaries contain the same information properly isolated under the keys domain , domainaccess , path , secureconnection , expiration , name and value . The individual cookie strings are simplified data representations pre-formatted in the style “name=value” or “ name=value; Path=path” (the latter only if an explicitly path was specified) which is usually the proper form to use when constructing a custom MIME header with a Cookie: or SetCookie: tag.

If the program is run in -header exclusive mode, the command result is a list of the status variable values size , lastmodified , mimetype , code , location and cookies , in the order listed, instead of the fetched data.

The modification time as well as cookie expiration dates in the status are returned as an integer (seconds since midnight, Jan 1 st , 1970, epoch ), suitable for formatting by means of the standard Tcl clock format command. If a modification or expiration date could not be determined, the reported time value is minus one.

The mime type information may contain, after a semicolon separator, additional encoding information if reported in this fashion by the server.

Example:

set data [fetch -timeout 10 ftp://$user:$passwd@$host/$path/$file v_status]
set mimetype $v_status(mimetype)

filecheck

filecheck type filename

This command is used to check formats and attributes of files. The result is either 1, if the file is of the checked type, or 0 if it is not. In case of errors, such as a non-existing file, a standard error condition is raised. These file type checks are currently supported:

These tests operate by examining the first bytes of a file, not by a simple match of suffixes. File checks which rely on platform-specific binary data layout information only work for the current platform. On a Sun, a OSX bundle will not be recognized, and vice versa.

ldelete

ldelete ?mode? list pattern ?pattern?...

Delete elements from a list. The first optional parameter selects the match mode for the patterns. If can be one of - exact , - nocase , - substring , - regexp , - glob or - index . The standard option list terminator “--” may also be used. The default mode is exact . The index mode expects element indices starting with 0 as pattern arguments.

All list elements which match any of the patterns are removed. The command returns the shortened list, preserving the order of the surviving elements.

Example:

ldelete -regexp [list a aa ad] {a[abc]+} 

returns “a ad”.

lineintersect

lineintersect x1 y1 x2 y2 x3 y3 x4 y4
lineintersect {x1 y1} {x2 y2} {x3 y3} {x4 y4}

Test whether the line segments from x1/y1 to x2/y2 crosses the line segment from x3/y3 to x4/y4.

The return value is a simple boolean flag. It does not report the intersection coordinates.

lsearch

lsearch ?modeflags? list pattern

This is an extended, but compatible version of the standard Tcl lsearch command.

The mode flags may be any combination of - exact , - nocase , - substring , - regexp , - glob , - first , - all and the option terminator “--”. The default mode is the combination of glob and first , the same as for the standard lsearch command.

Just as the standard command, matching list indices are returned. In mode first, which corresponds to the default behavior, the result is the list index >= 0 of the first matching element, or -1 if the pattern cannot be found. In mode all, a list of the indices of all matching list elements is returned, or an empty list if no element matches.

Example:

lsearch -exact -all {a b c a b c} a

returns “0 3”.

lsum

lsum nmbers...

Sum up all number arguments and return the result. All arguments must be numbers.

lvardelete

lvardelete ?mode? listvar pattern ?pattern?...

Delete elements from a list variable. The first optional parameter selects the match mode for the patterns. If can be one of - exact , - nocase , - substring , - regexp , - glob or - index . The standard option list terminator “--” may also be used. The default mode is exact . The index mode expects element indices starting with 0 as pattern arguments.

All list elements which match any of the patterns are removed from the variable. Additionally, the command returns the shortened list, preserving the order of the surviving elements.

Example:

set mylvar [list a b c d]; lvardelete myar b d

returns “a c” and sets the variable to the same value.

mail

mail ?-debug 0/1? ?-file filename? ?-from from_address? ?-secure 0/1? ?-smtphost hostname? ?-smptpassword password? ?-stmpport port? ?-smptuser userid? recipient_address_list ?subject? ?body?

Send a simple iso-encoded plain-text email message to one or more recipients. The only required argument is the recipient email address list. Without subject and body arguments, an empty message is sent. If the recipient address list is an empty list, or only contains empty elements, the command silently does nothing. Address list elements which are not empty strings and ignored must pass a simple email address pattern test before a mail delivery attempt is made.

The optional smtp* arguments specify the access parameters to the mail host. If these options are not set, they are read from the corresponding control variable elements, i.e. ::cactvs(smpt_host) , ::cactvs(smpt_port) , etc. If the - secure option is set, an attempt is made to use encrypted smpts communication instead of the plain smtp protocol, though the initial protocol negotiation still uses plain smtp if the smtp port is not explicitly set to 465. In absence of an - from argument, the sender address is copied from ::cactvs(user_email) . There is no required relationship between the from address and the mail host access parameters. The default smtp port used by this command is 587, not the old standard 25.

Experience teaches that talking to mail servers can be tricky. When the - debug option is set, trace output from the communication attempts is printed on standard error. This is highly useful to pinpoint connection problems.

Finally, the - file option allows the direct upload of an existing, readable file as the message. The file contents are sent as message data, not as an attachment. If both an upload file and a body argument are specified, the file is inserted first.

The message content is sent as plain IsoLatin (ISO8859-1) encoded message. The nature of line-break characters in the message is not preserved, and additional line breaks are inserted if any line is longer than 998 characters, the maximum line length in a standard smtp message.

This command currently neither supports pop-before-smtp authorization, nor the sending of attachments.

Example:

mail -smtphost smtp.gmail.com -smtpuser $user -smtppassword $pw \
			-secure 1 wdi@xemistry.com “Hi” "This\nis a message\n"

Above sample command sends a message via Google mail. Of course, a Gmail account bound to the user and password variables must exist for this command to succeed.

mailcap

mailcap mimetype

Return the standard opener/viewer for files of the specified MIME type. The result is dependent of the local configuration.On Windows, the command attempts to find a suitable opener in the registry, and if it is found, the return value usually contains Windows-specific placeholder tags.

Example:

mailcap chemical/pdb

might return something like “rasmol -pdb %s”

parse

parse base64 arg
parse casrn arg
parse color arg
parse datauri arg
parse dictionary arg
parse doi arg
parse domain arg
parse element arg
parse elementlist arg
parse email arg
parse formula arg
parse hash arg
parse hex arg
parse inchi arg
parse inchikey arg
parse ipaddr arg
parse jme arg
parse lillyrule arg
parse list arg
parse minimol arg
pasre nativequery arg
parse orcid arg
parse propertylist arg
parse query arg
parse queryformula arg
parse retrievallist arg
parse sln arg
parse smarts arg
parse smiles arg
parse superatom arg
parse uuid arg
parse xml arg

This command checks whether the argument can be parsed as the data type indicated. The result is a boolean value. No error is raised if the parsing fails, and the parsed data structure is discarded. The following data types are currently understood:

passwd

passwd encode cleartext_pw ?salt?
passwd decode encrypted_pw cleartext_pw

The first command variant encodes a clear-text password with the standard Unix crypt() algorithm. A salt value for the password generation may be specified as exactly two letters from the set “a-zA-Z0-9./”. If no salt is specified, a random value is used. The command returns the encoded version of the clear text.

The second variant returns 0 or 1, depending on whether the clear text password matches the encrypted version or not.

This command is supported on Windows, the crypt() function is provided by a compatibility function compiled into the library code.

Example:

passwd encode topsecret XX

yields something like “XX9Kadd0cpq.o”.

passwd decode XX9 topsecret

returns 0, while

passwd decode XX9Kadd0cpq.o topsecret

returns 1. Note that without the specification of a salt parameter the encoded result is different each time in a random fashion. However, the password check works without knowing the salt with encrypted passwords encoded with each possible salt.

post

post ?-agent agent? ?-boundary text? ?-cookie cookietext? ?-contenttype type? ?-cookie cookietext? ?-debug 0/1? ?-host hostname? ?-language languagecode? ?-password pwd? ?-raw? ?-referer referer? ?-setcookie cookie? ?-timeout nsecs? ?-uploads uploaddictionary? ?-user username? ?-xheader headerline? url ?fielddictionary/rawdata? ?statusvar?

Assemble the code for a HTTP or HTTPS POST message in (by default) multipart/form-data encoding, transmit it to a remote server and read the response.

In the standard command mode, the field dictionary parameter is a list of field names and their contents to include in the POST message. The transfer format is binary, so it is possible to send byte array data. The default individual field mime format is text/plain , but PNG and GIF images as field data are automatically recognized and sent as image/png and image/gif, respectively. In order to mirror the data encoding characteristics of file upload HTML form elements faithfully, an optional uploads dictionary can be provided. It is a key/value set where the keys are field names that are file upload elements in the emulated Web form. They also need to be contained in the field dictionary as field name / field data pair. Field names only present in the uploads directory are ignored. The upload dictionary values are the filename attribute of the transmitted fields. The encoding of transmitted data for fields in this dictionary is modified so that the content type is always set to application/octet-stream instead of text/plain . Whether the configuration of the upload dictionary is required or not when emulating the submission of forms with upload fields depends on the extent of the data analysis performed on the side of the contacted server, but its use does not potentially introduce new problems. File contents are not automatically opened and read. Their contents must be provided in the field dictionary.

If the - raw flag is set, no interpretation of the field dictionary parameter takes place. Instead, the value of this parameter is transmitted verbatim as byte sequence in the message body. In this mode, it is assumed that it already contains all field formatting and only needs to be augmented with the HTTP header data.

The other optional parameters allow the setting of additional fields in the header of the POST command. The -boundary attribute is the MIME separator string. Its default value is a random string that is highly unlikely to occur in any transmitted data. The default content type for the form submission is multipart/form-data , but this may be adjusted with the - contenttype parameter. The short argument forms multipart (or formdata ) and urlencoded select the standard encodings multipart/form-data and application/x-www-form-urlencoded . Other values of this option are sent verbatim to the server after a Content-Type: keyword. The additional attributes of file upload fields are ignored in urlencoded mode.

The argument of the - language option is passed to the Accept-Language: HTTP header field. By default the Host: HTTP header is extracted from the destination URL, but a custom value can be set with the - host option. The - xheader parameter allows the inclusion of a custom line in the header. It should be provided without linefeeds, and must contain the header field name. The other parameters have the same meaning as in the related fetch command.

If the name of a status variable is specified, it is created or reset in the local namespace, and filled with the elements status (the HTTP server error code, 200 for normal retrieval), size (the length of the received content in bytes), cookies (a list of all cookies received in Netscape string format), cookiedicts (a list of cookies in dictionary form), location (the response URL, which can be different from the command argument in case of server redirection), lastmodified (the modification time stamp of the result data, if available, -1 otherwise) and contenttype and mimetype (the MIME type of the response). In addition, every cookie is individually stored as element cookiedict%d , starting with index zero and with the seven elements domain , domainaccess , path , secureconnection , expiration , name and value that are contained in the standard Netscape cookie encoding. The variable element names are compatible to those used in the fetch command.

It is possible to omit the field dictionary argument if an empty message is to be sent. The URL may also contain field arguments in URL encoding, but whether these are recognized in addition to the data in the field dictionary depends on the destination server configuration.

Example:

set data [post -contenttype urlencoded -cookie $c -debug 0 \
-xheader "X-CSRFToken: [dict get $dcsrf value]" \
-referer https://mcule.com/search/ \
https://mcule.com/search/post \
[dict create csrfmiddlewaretoken [dict get $dcsrf value] mode exact structure_2 $mdata
]]

python

python eval expression
python exec statements

Execute a Python command or expression. This command is only available in interpreters which include a Python subsystem.

For the eval variant, only a single statement may be processed, and the result of that statement is returned to Tcl . Longer statement blocks can be processed with the exec command variant, but in that case the result is always an empty string if no error occurs. This is a limitation of the Python API . In case an error is raised, its description is transferred back as Tcl result string, and the command also reports an error.

The Python interpreter version is 3.3. It is fully featured with access to the complete Python standard library, and can be instructed to import additional modules.

At this time, only a single primary Python interpreter exists in Python-enabled toolkit applications. It is mutex-protected and can be called from multiple Tcl threads, but not simultaneously. Property computation Python slave interpreters are internally used, but not accessible via this command.

The Python interpreter has already imported the pycactvs and sys Python modules. All pycactvs functions and other objects are explicitly imported and can by used without a module prefix. The pycactvs.tcl() and pycactvs.tcl1() functions allow scripts to double back and execute a Tcl command in the main Tcl interpreter from within Python.

Examples:

set five [python eval “2+3”]
python exec “print(‘hello world’)”
set eh [python eval “tcl(‘ens create CCC’)”]

The first example computes a simple expression in Python and returns the result. It is automatically efficiently encoded as a Tcl integer object.

The last example executes a command in the Python interpreter, which itself turns back to the Tcl interpreter to execute an ens create statement. Toolkit objects are shared between the Python and Tcl interpreters. The newly created ensemble object is known and accessible in both languages simultaneously.

quote

quote arg

Perform an efficient string quoting operation. The result is a string which contains only 7-bit printable characters. Characters outside this range are encoded as backslash-encoded octets or standard backslash escape sequences such as ’\t’ or ’\\’. The code for this command was copied from the Tcl Netscape plug-in.

random

random limitval ?sequencesize ?seedval|reset?
random seed ?seedval‘?
random reset
random hex32 ?seedval/reset?
random hex64 ?seedval/reset?
random hex128 ?seedval/reset?
random uuid

Generate integer pseudo-random numbers. In the simplest command variant, the limitval parameter is an upper exclusive bound. The returned pseudo-random number is in the range 0 to limit-1 . By default, only a single number is returned. If a non-empty sequencesize parameter is added, the specified number of pseudo-random numbers is returned as a list. If the third optional parameter is reset , the random number generator is reset to its default start state. Alternatively, a numerical seed value can is used to initialize it to a different initial state before computing the random numbers..The random numbers are always the same sequence for a given initial state. If this is not desired, some pseudo-random seed, such as the current clock click value, should be used.

The random seed and random reset command variants can be used to manipulate the state without starting the random number generation. The seed subcommand without a seed argument uses a combination of a high-resolution timer and the process ID as seed value and is the recommended method to set up the generator for non-repeatable randomness.

The random hexxx variants directly return hex string encodings of 32, 64 or 128 bit integers, which possess fixed string lengths of 8, 16 and 32 characters, respectively. Optionally, this operation again can be combined with a reset operation or a seed value.

The uuid subcommand generates a new UUID. This function is independent of the normal random state.

This command is thread-aware. Every script thread has its own random state, and random number generation or state manipulation in one thread has no effect on any other interpreter thread. The uuid subcommand is the sole exception - it is not thread-aware, and not coupled to the thread-local random state of the other commands.

This random number command overrides the standard TclX command of the same name and provides a superset of its functionality, in addition to thread-awareness.

Example:

random seed
foreach r [random 16 8] {...}

rpc

rpc bynumber servicenumber
rpc byname servicename

Look up RPC services by name or service number. If the service can be found, the result is a list consisting of the service name, the service number, and a list of all name aliases.

This command is supported on Linux/Unix only.

screen

screen ?-aromatch lenient|normal|strict? ?-frags? ?-hydrogens ignore|match|mark? ?-mode ligands|smarts? ?-nobondorder? ?-tauto? ehandle patternlist ?exactmatchvar?

Perform fragment-based bit screening on an ensemble object. If the - frags option is not set, he result is a bit vector of the same length as the pattern list, with bits set to zero or one depending on whether a pattern fragment matches or not. If - frags option is set, the return value is a list of the patterns which match, copied verbatim from the pattern list argument.

If the optional exact match variable parameter is given, it is the name of a Tcl variable which is set to one if the input ensemble is of exactly the same connectivity (without stereochemistry or isotopes) as one of the pattern fragments. If no pattern is an exact match, it is set to zero.

The expected format of the pattern list depends on the match mode. The default match mode is ligands , which can be explicitly set by supplying the argument to - mode . The other possible match mode is smarts , set by -mode smarts .

In smarts mode, the patterns are normal SMARTS strings. These are cached internally, so if patterns are reused, and the total number of patterns is not too large for the cache, they are not decoded anew for every command invocation.

In ligands mode, a simpler pattern language which is faster to decode and match is used. The patterns are either two element symbols, connected by a bond symbol (- for single bond, = for double, * for triple, # for quadruple, ~ for aromatic - note that this is different from SMILES!), or an element, followed by a sequence of bracketed ligands, each with a preceding bond symbol. Patterns like these describe one central atom (the first element in the pattern), with one or more ligands. Examples are “P=O” or “C(-Cl)(=O)” or “C(-H)(~C)(~C)” . For internal reasons, all multiple bonds in a pattern must be written before any aromatic bond.

The - aro option controls how aromatic systems in the ensemble are matched. The default is normal , meaning that single and double bonds in SMARTS patterns match aromatic bonds in the ensemble, regardless of their Kekulé bond order, and single bonds in ligands patterns match aromatic ensemble bonds. In strict mode, non-aromatic bonds in the pattern do not match aromatic ensemble bonds. This mode has an effect only for smarts matching, not ligand matching. The aro match mode lenient only has an effect on matching ligand patterns. If not selected, ligand pattern double bonds do not match aromatic ensemble bonds. If the mode is lenient , they do.

If the - tauto flag is set, the matching of both ligand and SMARTS patterns is further modified. In ligands mode, tautomeric ensemble bonds (as per property B_ISTAUTOMERIC ) are excluded from any match which requires an exact bond order match. In smarts mode, the matched fragment must be compatible with a tautomeric form with shifted bond orders and relocated hydrogen atoms. This flag is intended to be used to construct a screening bit string for tautomer-tolerant substructure searches. Because less patterns can be positively identified to be matching under these circumstances, these bit strings have generally less bits set, and are therefore less effective filters.

If the - nobondorder flag is set, bond orders of pattern fragments of both types are ignored.

The - hydrogen option controls how patterns with hydrogen atoms are handled. By default, in mode match , they are matched like any other pattern. In mode ignore , patterns with hydrogen never match. This is the mode to use if a screen vector for superstructure search is constructed. In mode mark , any pattern which contains a hydrogen atom reports a match, and any pattern which does not a mismatch. This mode is intended to be used for construction of bit masks for the removal of any bits from a screen vector which are hydrogen-dependent. This allows for example the re-use of a substructure screen vector for superstructure search.

tmpdir

tmpdir

This command returns the current directory for temporary files (“/tmp” or „C:/temp“ or similar).

tmpname

tmpname ?prefix? ?directory? ?suffix?

Generate a valid name for a temporary file. The file name prefix as well as suffix may be specified, as well as the directory. If these parameters are omitted, a temporary file in the standard tmp directory and with a file name prefix derived from the application name (obtained via invoking the command infox appname ) is generated. If the directory name parameter is empty, the default tmp file directory is used.

Example:

tmpname myapp {} .res

returns something like /tmp/mya2462.res , dependent on the operating system and local set-up.

uncgi

uncgi ?-noreset? cgi_string ?arrayvar? ?notrimfields? ?fieldname default?...

This command decodes CGI data, as it is delivered to a CGI application from data input in a WWW form via the Web server. It automatically recognizes the two standard transfer formats application/x-www-form-urlencoded and multipart/form-data and adjusts the decoding process accordingly.

The cgi_string input data can be obtained either from the QUERY_STRING environment variable ( PUT forms, or direct CGI URLs), or from reading the stdin channel ( POST forms). A typical code snippet in case the data submission method is not known is:

fconfigure stdin -translation binary
set data [read stdin]
if {$data==””} { set data $env(QUERY_STRING) }
uncgi $data params

The return value of this command is a dictionary with name/value pairs. This dictionary can be read into an array variable by the standard array set Tcl command. If the optional arrayvar parameter is used, an array variable of that name is automatically created or reset and filled with the decoded data in the form of array elements.

By default, leading and trailing white space is removed from the decoded data. Fields for which this white space removal should not be performed can be listed as a standard Tcl list in the notrimfields parameter. These fields are decoded without any processing.

Note that it is generally advisable to set the stdin input channel to binary mode before reading the CGI data. On Unix, this is likely to be a no-op, but the transfer of binary data on Windows usually does not work at all without this setting.

For security reasons, certain XML/HTML-style tags, including their inner text if they possess it, are automatically removed from the input data. The currently deleted tag list is <embed> , <frame> , <iframe> , <img> , <object> , <script> and <style> . This tag deletion cannot be suppressed.

Data of type multipart/form may transfer additional parameter attributes for the data together with the actual content. In case of file uploads from Web forms, the original client-side file name is captured in an additional result element named by appending “_filename” to the basic data field name. The MIME type of the data, if transmitted, is similarly stored in an extra element with the appended name part “_type”.

A single unnamed field in the data string is accepted by the decoder. The data is stored as element unnamed in the decoded result.

In case a field name is occurring more than once in a data string, the additional instances are appended to the first instance as list elements. The final content of the decoded field is then a list of all values found in the input.

If an output variable parameter is used, all existing array elements are removed before decoding starts. In case results should be accumulated, the - noreset option can be used to suppress the variable reset step.

After the parameter listing fields not to be trimmed an arbitrarily long list of pairs of field names and their default values can be specified. If a field name listed there was not present in the input data, it is set in the result list and array variable with the default value following the field name.

Example:

URL: http://www.example.com/cgi-bin/doit.tcl?a=alpha&b=beta&b=gamma

The data sent by invoking the CGI script via this direct URL can be decoded in the doit.tcl script with the statement

uncgi $env(QUERY_STRING) params

An array variable named params is set up, or reset if already present, and it contains exactly two elements: Element a with value “alpha”, and element b with value “beta gamma”

unzip

unzip nested_list ?index?

Extract a list of indexed elements from a nested list. From each element of the nested input list, the element indicated by the index parameter is selected and appended to the result list. If the index parameter is omitted, the default is zero. If a selected list element does not exist, an empty string is substituted.

Example:

set l2 [unzip {{a 1} {b 2}} 1]

The l2 variable is set to a list with elements 1 and 2.

vec

vec subcommand ?args?

This command provides a couple of useful 3D vector manipulation commands. Internally, the vectors are standard Tcl list objects, with floating-point element objects, so operations are not blazingly fast but still reasonably effective for routine vector arithmetic. Vectors are not objects, there is nothing to destroy when they are no longer needed. This simple utility command only supports vectors and points of 3 dimensions.

Vectors can be decoded from a variety of string representations. A vector can be made from

The following subcommands are understood:

vec add v1 v2 ?v3...?
vec plus v1 v2 ?v3...?
vec + v1 v2 ?v3...?

Add two or more vectors. The return value is the vector sum.

vec angle v1 v2
vec deg v1 v2

Compute the vector angle between v1 and v2 in degrees. See also rad subcommand.

vec create arg1 ?arg2 arg3?

Generate a vector. If only one argument is given, any of the standard representations is accepted. In case three arguments are provided, they are internally concatenated and this list submitted to the decoding procedure. The command result, if the arguments could be decoded, is the numerical vector representation. In the single-argument form, this command can be bypassed by directly using the vector data as argument to other vector commands.

vec dot v1 v2
vec * v1 v2

Compute the dot product of the two vectors. The result is a floating point value.

vec fitline p1 p2 ?p3...?

Fit a line to a set of points. The return value is a line point and the direction vector.

vec fitplane p1 p2 p3 ?p4...?

Fit a plane to a set of points. The result is returned in Hesse normal form: The closest distance of a plane point to the origin, and the normal vector of the plane.

vec len v1
vec len p1 p2 ?p3...?

If only a single argument is specified, interpret it as vector and compute its length. In case multiple arguments are used, compute the length of the straight, acyclic path between the points.

vec dist p1 p2 ?p3...?

Return a list of the distances between point one and two, two and three, and so on. For two arguments, the result is the same as using vec len , but if there are additional points, the individual distances between the waypoints are returned as a list instead of the total length of the path.

vec midpoint v1 v2 ?v3...?
vec centroid v1 v2 ?v3...?

These command aliases compute the centroid of the points passed as argument. The return value are the centroid point coordinates.

vec negate v1

Negate the vector. This is equivalent to scaling with minus one.

vec normalize v1
vec unit v1

Normalize vector to length one. The normalized vector elements are the return value.

vec plane v1 v2 ?v3...?

Compute a plane (fitted in case more than two vectors are specified) spanned by the specified vectors. The result are two orthogonal plane vectors.

vec planenormal p1 p2 p3

Get the normal vector of the plane specified by the three points.

vec product v1 v2
vec crossproduct v1 v2
vec x v1 v2

Compute the vector cross product of the two passed vectors. The return value is the cross product vector. The subcommand may be abbreviated as cross or prod .

vec pt_line_dist pt l_anchor l_vec

Compute the distance between a point (coordinates in first argument) and a line in 3D space (specified by an anchor point on the line and the direction vector).

vec pt_plane_dist pt l_anchor l_vec

Compute the distance between a point (coordinates in first argument) and a plane in 3D space (specified by an anchor point on the plane and the plane normal vector).

vec rad v1 v2

Compute the vector angle between v1 and v2 in radians. See also angle/deg subcommand.

vec scale v1 floatval

Scale length of vector v1 by the specified floating point factor. The return value is the scaled vector.

vec subtract v1 v2 ?v3...?
vec minus v1 v2 ?v3...?
vec - v1 v2 ?v3...?

Subtract one or more vectors from v1. The return value is the result of the subtraction.

zip

zip list1 ?listn?..

Merge one or more lists. The result is a nested list where each element is a sequence of input list elements at the corresponding position. The size of the largest input list determines the output. If any input lists are shorter than another input list, empty elements are substituted.

Example:

set l [zip {a b c} {1 2}]

The result is a single list „ {a 1} {b 2} {c {}}

It is possible and sometime useful to use only a single argument list. Here, every element is reformatted so that itself is a proper nested list. Example:

set l [zip {a {b c} d}]

The result is a list „ {a {{b c}} d} “ with an extra nesting level to protect the middle element so that it can a reclaimed unchanged by un-zipping with a command like

set l0 [unzip $l 0]