Monday 14 December 2009

MsgBox / InputBox in JScript

Unfortunately JScript does not have several useful features available in VBScript. The most famous things are MsgBox and InputBox. The following code makes them available in JScript too.

Wednesday 11 November 2009

IEEE754 converter

Tuesday 3 November 2009

Cross-platform date/time definition

Earlier here (in Russian) i have investigated ways how to obtain date and time parts using the CMD.EXE features. After that here (in Russian too) i have simplified this way until two lines of a code. But both ways are platform-dependent - the order of date parts depends on the locale settings.

Recently i found the excelent link (in Russian too) with the description how to obtain the subject platform-independently.

I slightly modified the established method and present it now.

Thursday 29 October 2009

CMD/BAT Librarian

Introduction
Unfortunately CMD.EXE, the command line interpreter in Windows, does not allows to collect favorite scripts under appropriate folders and use them multiple times in the future. So we have to use the "copy-and-paste" technology to migrate some needed functionalities from one script to another.

The script below allows to store debugged scripts under the determined folder, use them mutiple times, compile and link automatically to the final script.

Logfile rotation by CMD/BAT

The script below allows to rotate file (e.g.: logfiles). By default, the length of rotation is 5. It means that this script rotates some file no more than for 5 times.

Let's consider the permanently growing file of some application named as something.log and we'd like to keep records in this file for the long time as much as possible. But for some reason this file is cleaning up periodically or a size of the file affects on the application's performance.

The recent records are available from the file something.log and the previously saved records are available under the name something.log.1, etc until the something.log.5. After the following rotation the content of the last file will be lost and replaced by the content of the previous file (something.log.4 will be copied to the something.log.5) and the first file something.log will be copied to the something.log.1. At the same time the something.log will be truncated.

rotate something.log 10

Sunday 4 October 2009

WHICH: UNIX-to-NT ported

WHICH is unix-world command, implemented using CMD/BAT feature only.

Friday 2 October 2009

Simple Batch Progress Bar

Example 1. Print the bar within the window with '#' as the default filling character
call :progressbar 50
Example 2. The same as above but with an another filling character
call :progressbar 50 *
Example 3. Print the bar in the window title
set progressbar_t=1
call :progressbar 50

Tuesday 8 September 2009

CMD/BAT: GetOptions

This is flexible and useful library to manipulate with arguments in CMD/BAT scripts.

Wednesday 19 August 2009

Substring extraction by CMD

Once i needed to solve the next task. I have a batch script with name corresponding to the following conditions:
  1. the script filename has to be matched the pattern (see below).
  2. this script has to be located within directory tree of free nestion but one of directories of the tree has to be macthed the same pattern.

Wednesday 5 August 2009

Monday 27 July 2009

URL parsing in Javascript

There is very simple way to parse URL in Javascript. Just define new method in the prototype of the String. Of course, it has own shortcomings but in the most cases it covers the wide range of URLs and protocols (http(s), ftp, mailto, etc; the mandatory part of URL, host is considered as domain names, IPs, and localhost separately), and moreover it considers the more complex URLs like jdbc:oracle://localhost:1521.

Thursday 9 July 2009

JS2BAT converter 2

Earlier to embed javascript codes into batch files the JS2BAT tool has ben implemented with batch features only. In this topic the same tool has been implemented in pure javascript. As opposed to the previous version the present one is the more functional and has optional parmeters. Previously the js2bat.js script has been implemented in javascript. After that it has been converted to the js2bat.bat batch script by itself with the following command:
cscript js2bat.js js2bat.js

Tuesday 7 July 2009

JS2BAT converter

This script allows you to embed Javascript codes into the batch-script immediately. So you can stop to worry about creating of an additional batch-wrapper or lost of some specific parameters. Perl distribution has the same functional script pl2bat but for wrapping of perl-scripts with batch-scripts. I am not author of this idea, i just implemented this feature as the standalone tool. The main feature is to write the prolog code that is valid both in a batch and javascript. When launching the batch it runs as batch and calls the javascript interpreter with the same file as javascript file. But the second one skips this prolog as valid javascript comments.

Friday 3 July 2009

Finest code syntax highlighter

Quotation from the Code Syntax Highlighter, the homepage of the project, allowing to embed colorizing of text and fully written on Javascript.
SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript.
It is really true! It is very useful, very flexible and easy to customize. The main idea is to use so-named brushes to colorize codes within <pre /> tags (it is defined by default and customizable too!). Colorizing is simple. You have to link scripts and styles to your pages and add brush via class attribute (like this class="brush:js" for colorizing of Javascript codes).
I decided to use it in my blog and found that it works fine. Unfortunately there is no brushes for cmd/bat scripts and i have implemented this embedding to the blog's layout the code from below.

HOWTO turn a character case via CMD/BAT

Introduction

This example is amazing that fact that it can be extended by non-Latins with no pain. Just add your owned translation table at the end of script in the format UPPER lower. For example, the translation table for Cyrillic characters is following:
А а
Б б
...
Ю ю
Я я
Just remember that the capitals have to be the first with following lowercase letters.

Examples of usage

Capitalize all characters. Results to QWERTY.
CAPS qwerty /u
The first character is capital, and others are in lower case. Results to Qwerty.
CAPS qwerty /uf
Invert the result of the previous example. Both result to qWERTY.
CAPS qwerty /uf /l
CAPS qwerty /lf

Sunday 28 June 2009

Хороша!

Monday 22 June 2009

Честно!

Monday 15 June 2009

WC: Emulation of the unix command

This is curious, joke. It is attempt to emulate the unix-commad wc. Do not consider this as fully featured application. It has essential shortcomings - slower than analogs and it gives great mistakes when counting the number of words. This is related with features of processing of special characters when passing them as arguments.

Validate number arguments within CMD/BAT

@echo off

if "%~1" == "" (
    echo EMPTY
    goto :EOF
)

if "%~1" == "0" (
    echo ZERO
    goto :EOF
)

set /a number_var=%~1 2>nul

if errorlevel 2 (
    echo ILLEGAL
    goto :EOF
)

if %~1 neq %number_var% (
    echo ERROR
    goto :EOF
)

set number_var
goto :EOF

Saturday 13 June 2009

Complex numbers with Javascript

Однажды решили попрактиковаться в реализации комплексных чисел средствами Javascript. Вот что из этого получилось. Особенностью модуля является вычисление всех частей (вещественной, мнимой, модуля и аргумента) комплексного числа на момент его создания. Это ни прибавляет, ни отнимает скорости вычислений, но оптимизирует некоторые вычисления (например, при вычислениях в алгебраической или полярной формах). Описаны арифметические операции, основные функции над комплексными числами (возведение в степень, логарифм, степенная функция, экспонента, квадратный корень и вычисление всех корней). Арифметические операции расширены для операций над несколькими числами.

Tuesday 26 May 2009

О влиянии волосяного покрова из спагетти на вкусовые качества сарделек

Профессор кулинарии Некстлессон сообщил о необычном кулинарном эксперименте по разведению волосатых сосисок. Нами был повторен данный эксперимент.

Saturday 23 May 2009

Сам себе книгоиздатель

Краткая инструкция с иллюстрациями о домашнем книгоиздании.

Wednesday 8 April 2009

How to secure your PC from autostart/autorun viruses on flash

Introduction

This article has been inspired after reading of the another article devoted to mounted disks within Windows XP. To know details follow the link. Here i will briefly explain essentials from that article and will demonstrate how this feature can be applied for the subject. Of course, do not need to accept these instructions with high seriousness.

Sunday 5 April 2009

Prepare a request from an assoc.array

I am continuing (with sorry about this) to free from unused codes in my box. Meet next code - it allows to convert an assoc.array to an URL request and backward.

Highlight of selected words in html texts

Create hex-dump of string

Однажды я упражнялся в алгоритмизации простой задачи на PHP. Вот результат (с небольшими доработками перед отправкой сюда).

Bit collection from integer value

The next example of code that was appeared once without any historical bounds of it's appearance. Look. It collects all bits from an integer value into an array.

Saturday 4 April 2009

Extended floor and ceil functions

I do not remember why i done this. Maybe this was used somewhere. Maybe i had practised in algorithms simply. Do not remember. There are two functions allowing round fractions down/up accordingly divider.

Friday 27 March 2009

JavaScript / JScript Benchmark (en)

Beginning

I will not lie - I do not like to estimate a performance of javascript code. This procedure provides for the main project a lot of "unnecessary" and "senseless" code:
var n = 1000; 
var start = (new Date()).getTime();/
for (var i = 0 ; i < n; i++) {
    // bla-bla-bla ...
}
var stop = (new Date()).getTime();
var duration = stop - start;
var average = duration / n; 
document.writeln(average);
I can presume that all the familiar lines such as these. I may be interested in the performance of a function or method, and possibly, some of program. But I do not want to pollute my working project by some kind of garbage, such as this. Also I do not want this for function that I am trying to estimate - what algorithm is better.
When I finally tired of it - I decided to develop a Benchmark. The objective was to estimate the performance of not only function, but any piece of code, beginning from the line n and ending by line m.

Motivation

Starting this work, I understood - it is possible that this code has been realized already and successfully. Nevertheless I started ab ovo. When finishing I decided to compare my solution with solutions of my predecessors (links are in the bottom of the article). I will not overmodest - despite of some similarities, my solution is better. The argumentation is following - despite of similarity my code is universal essentially.
Then I will show - that is, and how it can be very convenient and simple tool. Partially similarities and differences of the actual solution and it’s predecessors will be consider.

Features of OO-approach in JavaScript

Any piece of code can be a body of nameless function (this is truth for JavaScript especially taking in account it’s special OO realization). E.g.:
var arr = [100, 200, 300, 400]; 
    var result = 0; 
    for (var i = 0; i < arr.length; i++) {
        result += arr[i];
    }
can be transformed to the next
var arr = [100, 200, 300, 400]; 
((function() 
{
    var result = 0; 
    for (var i = 0; i < arr.length; i++) {
        result += arr[i];
    }
})(); 

Realization

This means that for any function you can apply a method which can perform additional actions:
Function.prototype.eval = function()
This method is defined for internal object Function, it is a certain amount of times, while retaining the length function and prints some statistics about the performance.
Let's to examine an example of usage:
var arr = [1, 2, 3, 4];

function sum(arr)
{
   var result = 0;
   for (var i = 0; i < arr.length; i++) {
      result += arr[i];
   }
   return result;
}

// original code
var s = sum(arr);

// modified code
var s = sum.eval(arr);
When comparing the original and modified codes, it can be seen that a difference is minimal. The code is pure until now and the result allows analyzing of information.

Features

This solution does not use timers and can be performed in different environment such as the browser window and standalone applications. Also it consists of the additional code solving problem of platform independency.
What has been implemented additionally? In the difference of analogues this code works in the most of cases - JavaScript/JScript. To reach this feature some additional useful properties has been defined:
- Function.prototype.evalCount - integer parameter keeps the number of iterations, by default is1000.
- Function.prototype.evalDuration - integer parameter keeps duration of the code execution. It is evaluated during a benchmarking process and does not have default value.
- Function.prototype.evalPrint = function() - auxiliary function for output of statistics of the performance. It takes in account differences of environments and launches appropriate output method. By default, it outputs the number of iterations and duration.
Of course, these parameters can be redefined, e.g., change the number of iterations or change the method of the statistics output. And this can be performed both globally via the function’s prototype and locally for the actual function. E.g.:
sum.evalCount = 10240; // 10K iterations
var result = sum.eval(1, 2, 3, 4);

Benefits

In the contrast of analogues the suggested method:
1. allows a light embedding the performance code with minimal modifications of the main code;
2. has extended features of control;
3. independent of the environment and allows to use this extension without modification both JavaScript and JScript (Windows Scripting Host).

The full solution

The solution is environment independent. It has been tested for IE6, IE7, FF2.0.0.15, FF3.0.7 and Windows Scripting Host. It is distributed under the GPL. The source code is available by this link. Ibid - the download link.

References

1. John Resig's blog
2. webtoolkit site

Monday 23 March 2009

Looking over texts within specified tags

Сегодня копался в завалах своего и чужого кода с целью почистить и удалить все, чего я не касался долгое время. Нашел на мой взгляд неплохой код собственного производства. Большой нужды в нем нет - писался одноразово, но хорошо документировано и жалко выкидывать. Смысл функции достаточно прост - найти и вытащить текст, окруженный заданным тегом.

Saturday 21 March 2009

JavaScript / JScript Benchmark

Начало

Не буду лгать - я не люблю оценивать производительность javascript кода. Эта процедура содержит для основного проекта массу "ненужного" и "бессмысленного" кода:
var n = 1000; 
var start = (new Date()).getTime();/
for (var i = 0 ; i < n; i++) {
    // bla-bla-bla ...
}
var stop = (new Date()).getTime();
var duration = stop - start;
var average = duration / n; 
document.writeln(average);
Думаю, всем знакомы строчки, подобные этим. Меня может интересовать производительность функции или метода, а возможно и некоторого участка программы. Но я не хочу засорять свой еще сырой код всяким мусором, подобным этому. Я также не хочу это делать для функций, когда пытаюсь оценить - какой же алгоритм лучше.
Когда мне это окончательно надоело - я решил написать свой Benchmark. Задача заключалась в том, чтобы можно было оценить производительность не только функции, но и любого участка кода, начиная со строки n и заканчивая строкой m.

Мотивация

Начиная работу, я понимал - вполне вероятно, что такой код уже кем-то и весьма успешно реализован. Тем не менее, я начал с нуля. После завершения я решил сравнить свое решение с работами своих предшественников (ссылки в конце). Не буду скромничать - не смотря на некоторое сходство, мое решение лучше. Аргументация следующая - при существенном сходстве реализации мой код в значительной мере более универсален.
Далее я покажу - что есть, и как из него можно получить весьма удобный и простой инструмент. Частично будут рассмотрены сходства и различия настоящего решения и его предшественников.

Особенности ОО-подхода в JavaScript

Любой фрагмент кода (особенно это справедливо для JavaScript с его особым ОО-подходом) может быть телом безымянной функции. Например, код
var arr = [100, 200, 300, 400]; 
    var result = 0; 
    for (var i = 0; i < arr.length; i++) {
        result += arr[i];
    }
может быть преобразован в следующий
var arr = [100, 200, 300, 400]; 
((function() 
{
    var result = 0; 
    for (var i = 0; i < arr.length; i++) {
        result += arr[i];
    }
})(); 

Реализация

Это значит, что для любой функции можно применить некий метод, который может выполнить дополнительные действия, а именно:
Function.prototype.eval = function()
Данный метод определен для встроенного объекта Function, вызывает его определенное количество раз, при этом запоминает длительность выполнения функции и печатает некоторую статистическую информацию о ходе выполнения.
Посмотрим на примере как эго можно использовать:
var arr = [1, 2, 3, 4];

function sum(arr)
{
   var result = 0;
   for (var i = 0; i < arr.length; i++) {
      result += arr[i];
   }
   return result;
}

// исходный код
var s = sum(arr);

// модифицированный код
var s = sum.eval(arr);
То есть, сравнивая исходный и модифицированный код, можно увидеть, что отличия минимальны. Код по прежнему чист, а результат позволяет проанализировать полученную информацию.

Особенности

Данное решение не использует таймеры отчета времени и может выполняться в разных средах, как в окне браузера, так и в самостоятельном приложении. Также содержит некоторый дополнительный код, который решает проблему кроссплатформенности.
Что же было применено дополнительно? В отличия от аналогов, данный пример работает для большинства случаев - JavaScript/JScript. Для этого дополнительно определено несколько полезных свойств:
- Function.prototype.evalCount - целочисленный параметр хранит количество итераций, или количество раз исполнения кода, значение по умолчанию 1000.
- Function.prototype.evalDuration - целочисленный параметр хранит продолжительность выполнения кода.
- Function.prototype.evalPrint = function() - вспомогательная функция для вывода статистики о производительности, учитывает различия сред исполнения и вызывает соответствующий метод для вывода количества итераций и продолжительности исполнения кода.
По умолчанию, производится оценка и выводится время исполнения кода для 1000 итераций. Параметр Function.prototype.evalDuration вычисляется в процессе и не имеет значения по умолчанию.
Естественно, эти параметры можно переопределить, например, изменить количество итераций, или переопределить свой метод отображения статистики. При чем, это можно сделать как глобально через прототип, так и конкретно для определенной функции. Например:
sum.evalCount = 10240; // 10K iterations
var result = sum.eval(1, 2, 3, 4);

Преимущества

Предложенная методика в отличие от аналогов
1. позволяет легко внедрить в свой код возможности оценки производительности с минимальными изменениями основного кода;
2. имеет расширенные возможности контроля;
3. она независима от текущей платформы и позволяет использовать данное расширение без изменений как в среде JavaScript, так и в JScript (Windows Scripting Host).

Полное решение

Решение платформно-независимо. Тестировалось для IE6, IE7, FF2.0.0.15, FF3.0.7 и Windows Scripting Host. Распространяется по лицензии GPL. Листинг исходного кода доступен по этой ссылке. Там же - ссылка на скачивание.

Ссылки по теме

1. John Resig's blog
2. webtoolkit site

Monday 23 February 2009

Для чего это нужно?

Важный вопрос. Возможно, когда-нибудь я смогу ответить на него.

Monday 16 February 2009

Hello, World!

Trying to create the first message in this blog.
<message>
<title>Hello, World!</title>
<say><[!CDATA[
Hello, World!
]]></say>
</message>