Проста програмка на Excel за изчисляване на съпротивлението на coil-а за изпарител на електронна цигара.
Най-интересното във файла е, че съм използвал именувани полета, за да създам нещо като база данни от която се извличат данните.
Файла може да се изтегли от тук: Ohm Calculator – e-cigarette
Category Archives: Programming
PHP-file UTF-8 encoding
Попаднах на стар хостинг (с php 5.2.3), който прецаква енкодинга при ъплауд на php-файлове. Изключително досаден проблем. Пробвах да вкарвам разни дивотии в .htaccess, но нищо не помогна. Ей такива неща опитах:
AddDefaultCharset utf-8 AddCharset utf-8 .php DefaultLanguage en-US
Единствения шанс, който ми остана беше да накарам интерпретатора да каже на сървара, че файла трябва да се излъчи в UTF-8 encoding. По-долния код се поставя преди рендването на съдържанието:
<?php header('Content-Type: text/html; charset=utf-8'); ?> |
Доста удобно за моя стил на програмиране :).
JavaScript обекно ориентирано програмиране – наследяване (пример)
Един много прост пример за наследяване на клас в JavaScript.
В случая имам клас Shape (форма), който ще разширя с клас за правоъгълник (Rectangle), който на свой ред ще разширя с клас за квадрат (Square).
<html> <head> <script type="text/javascript"> var Shape = function() {name: 'Shape'}; Shape.prototype.toString = function() {return this.name;}; var Rectangle = function(width, height) {this.width = width; this.height = height; this.shape = 'Rectangle';}; Rectangle.prototype = new Shape; Rectangle.prototype.constructor = Rectangle; Rectangle.prototype.area = function() {return this.width * this.height;}; var Square = function(width) {this.width = width; this.shape = 'Square';}; Square.prototype = new Rectangle(); Square.prototype.constructor = Square; Square.prototype.area = function() {return this.width * this.width;}; myShape = new Square(6); </script> </head> <body> myShape = new Square(6) ==><br/> <script type="text/javascript">document.write(myShape.width);</script> </body> </html> |
==========================================================
По-горния код е интересен, но тъй като съм го копирал и преработвал, без много да му вниквам, не е мисля, че е добър.
Ето така го оптимизирах, след като попрочетох малко за ООП-то на JavaScript:
var Shape = function () {}; var Triangle = function(w, h) { this.width = w; this.heigh = h; } Triangle.prototype = new Shape(); Triangle.prototype.getArea = function () {return this.width * this.heigh; }; // ====== Kvadrat var Square = function (l) { this.width = l; this.heigh = l; }; Square.prototype = new Triangle(); // ======== Examples var square = new Square(4), triangle = new Triangle(2, 5); print(square.getArea()); print(triangle.getArea()); |
За да стартирам кода използвам SublimeText2 с инсталирана приставка за стартиране на команди от шела Turtlestein, а за JavaScript интерпретатор използвам SpiderMonkey 1.8.5 for Windows.
Simple JavaScript rich text format editor
Прост, базов RTF редактор за сайт
Дълго съм се чудил кой е най-подходящия JavaScript Wysiwyg редактор с най-много възможности за напасване към сайт. Ползвал съм NicEdit, TinyMCE и други, които сам съм писал, неподдържащи rich text format (RTF). Обаче напасването на тези редактори към различни дизайни е развибащо от към бачкане и тестване в различните браузери. Реших да почопля няколко такива редактора и да разбера кое е толкова загадъчно и сложно, за да се напише подобен редактор. Истината е тривиална и се казва – iFrame. Този таг се ползва в почти всички подобни редактори, точно заради поддръжката му на RTF. При събмитване на формата, цялото съдържание на iform се подава на textarea, който си седи удобно скрит.
Това е моят редактор, без CSS-форматиране, като в примера добавям и опция за обработка на текста от базата данни, където присъства без тагове, с ексейпнати малко по-рискови символи.
<?php $field = '<a href="aloooha">Test\'ed. kavicha</a> dyra, byra.<br />Още текст и още "кирилица".'; $clearpost = $field; if(isset($_POST['button'])){ echo $_POST['myTextArea']; $clearpost = $_POST['myTextArea']; } //$clearpost = preg_replace('@delete|select|insert|update|where@i',"", $clearpost); // Почистване на //$clearpost = preg_replace('/[\x7f-\xff]/', "", $clearpost); // Clear Dirty Data $clearpost = preg_replace("/;/", ";", $clearpost); $clearpost = preg_replace("/\*/", "*", $clearpost); $clearpost = preg_replace("/\r\n/", "<br />", $clearpost); $clearpost = preg_replace("/\r/", "<br />", $clearpost); $clearpost = preg_replace("/\n/", "<br />", $clearpost); $clearpost = preg_replace("/</", "<", $clearpost); $clearpost = preg_replace("/=/", "=", $clearpost); $clearpost = preg_replace("/>/", ">", $clearpost); $clearpost = preg_replace("/\'/", "'", $clearpost); $clearpost = preg_replace("/\`/", "`", $clearpost); $clearpost = preg_replace("/\"/", """, $clearpost); if (!get_magic_quotes_gpc()) $clearpost = preg_replace('@\\\@', "\", $clearpost); else { $clearpost = stripslashes($clearpost); $clearpost = preg_replace('@\\\@', "\", $clearpost); } $clearpost = preg_replace("/'/", "\'", $clearpost); // Ескейпване на единичната кавичка, за да може да се показва в iframe!!! ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=windows-1251" /> <script src="wiswyg_ned/nedEditor.js"></script> <script type="text/javascript"> window.onload=function(){ iFrameOn(); if(isIE){ var myFrame = document.getElementById('richTextField'); var frameDoc = myFrame.contentDocument || myFrame.contentWindow; if (frameDoc.document){ frameDoc = frameDoc.document; } frameDoc.write ('<?php echo html_entity_decode($clearpost, ENT_QUOTES); ?>') ; } else { window.frames['richTextField'].document.body.innerHTML = '<?php echo html_entity_decode($clearpost, ENT_QUOTES); ?>' ; } } </script> </head> <!-- <body onLoad="iFrameOn();" > --> <body> <form action="" enctype="multipart/form-data" name="myForm" id="myform" method="post"> <div id="wysiwyg_cp" style="padding:8px; width:700px;"> <input type="button" onClick="iBold()" value="B"> <input type="button" onClick="iUnderline()" value="U"> <input type="button" onClick="iItalic()" value="I"> <input type="button" onClick="iFontSize()" value="Text Size"> <input type="button" onClick="iForeColor()" value="Text Color"> <input type="button" onClick="iHorizontalRule()" value="HR"> <input type="button" onClick="iUnorderedList()" value="UL"><br /> <input type="button" onClick="iOrderedList()" value="OL"> <input type="button" onClick="iLink()" value="Link"> <input type="button" onClick="iUnLink()" value="UnLink"> <input type="button" onClick="iImage()" value="Image"> <input type="button" onClick="iRemoveFormat()" value="Remove Format"> </div> <!-- Hide(but keep)your normal textarea and place in the iFrame replacement for it --> <textarea style="display:none;" name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea> <iframe name="richTextField" id="richTextField" ></iframe> <br /> <input type="submit" name="button" id="button" value="Make Changes" onClick="javascript:submit_form();"/> </form> </body> </html> |
Съдръжанието на JavaScript файла:
// Check Browser var isOpera = !!(window.opera && window.opera.version); // Opera 8.0+ var isFirefox = testCSS('MozBoxSizing'); // FF 0.8+ var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; // At least Safari 3+: "[object HTMLElementConstructor]" var isChrome = !isSafari && testCSS('WebkitTransform'); // Chrome 1+ var isIE = /*@cc_on!@*/false || testCSS('msTransform'); // At least IE6 function testCSS(prop) { return prop in document.documentElement.style; } //==================== function iFrameOn(){ richTextField.document.designMode = 'On'; //window.frames['richTextField'].document.body.innerHTML = '<a href="aloooha">Aloha</a> dyra, byra.<br />Още текст има тук.'; } function iRemoveFormat(){ richTextField.document.execCommand('removeformat',false,null); } function iBold(){ richTextField.document.execCommand('bold',false,null); } function iUnderline(){ richTextField.document.execCommand('underline',false,null); } function iItalic(){ richTextField.document.execCommand('italic',false,null); } function iFontSize(){ var size = prompt('Enter a size 1 - 7', ''); richTextField.document.execCommand('FontSize',false,size); } function iForeColor(){ var color = prompt('Define a basic color or apply a hexadecimal color code for advanced colors:', ''); richTextField.document.execCommand('ForeColor',false,color); } function iHorizontalRule(){ richTextField.document.execCommand('inserthorizontalrule',false,null); } function iUnorderedList(){ richTextField.document.execCommand("InsertOrderedList", false,"newOL"); } function iOrderedList(){ richTextField.document.execCommand("InsertUnorderedList", false,"newUL"); } function iLink(){ var linkURL = prompt("Enter the URL for this link:", "http://"); richTextField.document.execCommand("CreateLink", false, linkURL); } function iUnLink(){ richTextField.document.execCommand("Unlink", false, null); } function iImage(){ var imgSrc = prompt('Enter image location', ''); if(imgSrc != null){ richTextField.document.execCommand('insertimage', false, imgSrc); } } function submit_form(){ var theForm = document.getElementById("myform"); theForm.elements["myTextArea"].value = window.frames['richTextField'].document.body.innerHTML; theForm.submit(); } |
Сорс кода: wiswyg_by_ned.rar
Demo нa кода.
JScript Dot_NET GUI example
За да се програмира под .NET платформата е достатъчно да се инсталира някоя версия на фреймърка.
След инсталацията на .NET фреймуърк автоматично се инсталират няколко компилатора:
csc.exe – компилатор за C Sharp (C#)
jsc.exe – компилатор за JScript .Net
vbc.exe – компилатор за Visual Basic .Net
В момента имам инсталиран .Net framework 2.0 и работя с него, но предполагам, че и при по-новите версии ситуацията ще е подобна. Компилаторите се намират в директорията: C:\WINDOWS\ServicePackFiles\i386>
Аз харесвам JScript като структуриране на програмите и ще използвам него за конкретния пример. Както и в други GUI-примери, ще използвам и сега примерна програма за конвертиране на температура от Целзий до Фаренхайт.
Преди да поставя реалния код, ще покажа базов, рамкиращ код за това как се програмира подобна програма с графичен интерфейс:
import System; import System.Drawing; import System.Collections; import System.Windows.Forms; import System.ComponentModel; import Accessibility; public class Exercise extends System.Windows.Forms.Form { // var ...; function Exercise(){ InitializeComponent(); this.button1.add_Click(this.button1_Click); } function button1_Click(sender : Object, e : System.EventArgs){ //... } function InitializeComponent(){ // iniciirat se wsi4ki komponenti ot GUI-to this.textBox1 = new System.Windows.Forms.TextBox(); // ... } } var frmPledge : Exercise = new Exercise(); frmPledge.ShowDialog(); |
На база на този пример попълваме целия необходим код. Помогнах си за интерфейса с SharpDevelop 3.2 – чудесна програма за .NET програмиране. За съжаления програмата нативно не поддържа JScript, за това от нея копирам само кода за формата, като леко го промених. Програмата изглежда така:
Кода е сравнително лесен за писане и разбиране. Самото exe е едва 8kb. С включения сорс код може да се изтегли от тук: fahrenheit to celsius
import System; import System.Drawing; import System.Collections; import System.Windows.Forms; import System.ComponentModel; import Accessibility; public class Exercise extends System.Windows.Forms.Form { var button1 : System.Windows.Forms.Button; var textBox1 : System.Windows.Forms.TextBox; var textBox2 : System.Windows.Forms.TextBox; function Exercise(){ InitializeComponent(); this.button1.add_Click(this.button1_Click); } function button1_Click(sender : Object, e : System.EventArgs){ var Faren : double; var Celsius : double; Faren = ConvertToDouble(this.textBox1.Text); if(!isNaN(Faren)){ Celsius = (Faren - 32)*5/9; this.textBox2.Text = Celsius.ToString(); } else { this.textBox2.Text = "Wrong format"; } } function ConvertToDouble(valueto){ var ddd = valueto.ToString(System.Globalization.CultureInfo.InvariantCulture) return ddd; } function InitializeComponent(){ // iniciirat se wsi4ki komponenti ot GUI-to this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.textBox2 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(12, 12); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 20); this.textBox1.TabIndex = 0; // // button1 // this.button1.Location = new System.Drawing.Point(118, 10); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 1; this.button1.Text = "Convert"; this.button1.UseVisualStyleBackColor = true; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(199, 12); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(100, 20); this.textBox2.TabIndex = 2; // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(311, 46); this.Controls.Add(this.textBox2); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Name = "Exercise"; this.Text = "faren_to_celsius"; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; } } var frmPledge : Exercise = new Exercise(); frmPledge.ShowDialog(); |
За да се компилира този код до изпълнимо exe правим следното:
- запазваме сорс-кода в файла, примерно far_to_cel.js
- отваряме команден прозорец cmd (Start -> Run -> cmd). Или натискаме шифт и кликаме в директорията със сорс-кода, след това избираме “Open command window here”.
- след като сме позиционирали cmd в директорията със сорс-файла ще трябва да извикаме компилатора jsc.exe:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\jsc.exe /t:winexe far_to_cel.js
Ако не се покаже грешка, значи сме компилирали всичко нормално.
===================
Прилагам същата програмка, но написана на C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | using System; using System.Windows.Forms; using System.Drawing; using System.Text.RegularExpressions; using System.Globalization; public class CelToFar : Form { Button button1; TextBox textBox1; TextBox textBox2; public CelToFar() { button1 = new Button(); button1.Text = "Calculate"; button1.AutoSize = false; button1.Location = new Point(80, 15); button1.Size = new Size(75, 23); textBox1 = new TextBox(); textBox1.Location = new Point(12, 12); textBox1.Name = "textBox1"; textBox1.Font = new Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); textBox1.Size = new Size(60, 40); textBox1.Text = ""; textBox2 = new TextBox(); textBox2.Location = new Point(165, 12); textBox2.Name = "textBox2"; textBox2.Font = new Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); textBox2.Size = new Size(60, 40); textBox2.Text = ""; button1.Click += new EventHandler(ButtonClicked); this.Controls.Add(button1); this.Controls.Add(textBox1); this.Controls.Add(textBox2); this.Height = 120; this.Width = 255; this.StartPosition = FormStartPosition.CenterScreen; this.Visible = true; } public void ButtonClicked(object source, EventArgs e) { string FarenTxt = this.textBox1.Text; double Faren; double Celsius; Regex rgx = new Regex(@"^[\d\.]*$"); if(rgx.IsMatch(FarenTxt) && !String.IsNullOrEmpty(FarenTxt)){ Faren = Convert.ToDouble(FarenTxt, CultureInfo.InvariantCulture); Celsius = (Faren - 32)*5/9; this.textBox2.Text = System.Math.Round((decimal)Celsius, 3).ToString(CultureInfo.InvariantCulture); } else { this.textBox2.Text = "Wrong format"; } } static void Main() { Application.Run(new CelToFar()); } } |
Запазваме файла с името Far_to_celsius.cs, след което компилиарнето на кода става по подобен начин:
1 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /t:winexe Far_to_celsius.cs |
wxPerl example TextCtrl – Button getValue(), appendValue()
Един интересен пример с WxPerl, който може да ми е полезен, ако реша да програмирам GUI за Windows.
За примера съм инсталирал:
Perl 5.10.1.1008 в директорията D:\installed\perl
Wx 0.9914
Alien-wxWidgets 0.61
Win32-GUI 1.06
Целия пакет с разни други полезни модули може да се изтегли от тук:
ActivePerl-5.10.1.1008-Win32+Win32GUI+WxPerl.rar
Програмата в примера не прави нищо собено, но е достатъчна базова информация, за да се започне скромна диалогова програмка. В общи линии, при натискане на бутон взима текста от едното поле и го добавя към другото поле:
#!/usr/bin/perl -w use strict; use Wx; package MyFrame; use Wx qw (wxVERTICAL wxTOP wxGROW wxHORIZONTAL wxTE_MULTILINE wxFIXED_MINSIZE wxLEFT ); use base 'Wx::Frame'; # import the event registration function use Wx::Event qw(EVT_BUTTON); sub new { my $ref = shift; my $self = $ref->SUPER::new( undef, # parent window -1, # ID -1 means any 'wxPerl rules', # title [-1, -1], # default position [430, 360], # size ); my $panel = Wx::Panel->new( $self, # parent window -1, # ID ); my $button = Wx::Button->new( $panel, # parent window -1, # ID 'Click me!', # label [30, 20], # position [-1, -1], # default size ); $self->{txt} = Wx::TextCtrl->new( $panel, # parent window -1, # control identifier "Type your message here", # default text value [10, 50], # text control position [x, y] [400, 20], # text control size [width, height] # style: wxTE_MULTILINE=The text control allows multiple lines ); $self->{txt2} = Wx::TextCtrl->new( $panel, # parent window -1, # control identifier "", # default text value [10, 100], # text control position [x, y] [400, 200], # text control size [width, height] wxTE_MULTILINE, #=The text control allows multiple lines style => wxTE_MULTILINE ); # register the OnClick method as an handler for the # 'button clicked' event. The first argument is a Wx::EvtHandler # that receives the event EVT_BUTTON( $self, $button, \&OnClick ); return $self; } # this method receives as its first parameter the first argument # passed to the EVT_BUTTON function. The second parameter # always is a Wx::Event subclass sub OnClick { my( $self, $event ) = @_; if (my $rr = $self->{txt}->GetValue()) { print $rr."\n"; $self->{txt2}->AppendText($rr."\n"); } $self->SetTitle( 'Clicked' ); } package MyApp; use base 'Wx::App'; sub OnInit { my $frame = MyFrame->new; $frame->Show( 1 ); } package main; my $app = MyApp->new; $app->MainLoop; |
Кода може да се компилира с Cava Packager 2.0. Това чудо прави страхотни екзета от Perl-скриптове, като добавя всички необходими модули.
Калкулатор за пресмятане на течност за електронни цигари
C read text file line by line
Код, който чете от текстов файл ред по ред:
#include <stdio.h> int main ( void ){ static const char filename[] = "file.txt"; FILE *file = fopen ( filename, "r" ); if ( file != NULL ) { char line [ 128 ]; /* maximum line size */ while ( fgets ( line, sizeof line, file ) != NULL ) { /* read a line */ fputs ( line, stdout ); /* write the line */ } fclose ( file ); } else { perror ( filename ); /* why didn't the file open? */ } return 0; } |
C external command output – popen (_popen)
C external command output – popen (_popen)
Прилагам два кода на C, които прихващат резултат от изпълнение на конзолна програма и ред по ред го принтират към стандартния изход:
#include <stdio.h> #include <stdlib.h> int main( void ){ char psBuffer[128]; FILE *pPipe; if( (pPipe = _popen( "ping 10.317.112.201", "rt" )) == NULL ) exit( 1 ); while(fgets(psBuffer, 128, pPipe)) { if(strstr(psBuffer,"TTL")) printf("Ima ping\n"); printf(psBuffer); } /* Close pipe and print return value of pPipe. */ if (feof( pPipe)) { printf( "\nProcess returned %d\n", _pclose( pPipe ) ); } else { printf( "Error: Failed to read the pipe to the end.\n"); } } |
#include <stdio.h> #include <stdlib.h> int main( int argc, char *argv[] ){ FILE *fp; int status; char path[1035]; /* Open the command for reading. */ fp = popen("dir ..", "r"); // Dir one directory Up if (fp == NULL) { printf("Failed to run command\n" ); exit; } /* Read the output a line at a time - output it. */ while (fgets(path, sizeof(path)-1, fp) != NULL) { if(strstr(path,"Edit")){ // check file/dir name contains 'Edit' printf("%s", path); } } /* close */ pclose(fp); return 0; } |
И в двата кода използвам функцията strstr(), която проверява, дали върнатия стринг съдържа определен текст.
C string array and pointers
Няколко примера, които описват почти едно и също нещо – обхождане на елементи на масив с пойнтери. Много важно е да се схване, че масивите от стрингове всъщност представляват масиви от пойнтери от тип char!!!!
Костваше ми много време, докато се убедя, че е така, но не всеки може лесно да свикне да мисли на C :).
Пример 1
#include <stdio.h> int main(){ char words[][18] = {"edno", "dve", "tri", "chetiri", "pet"}; int i; for (i = 0; i < 5; i++){ char *words_ptr = *(words + i); printf("words_ptr + %d = %s \n", i, words_ptr); } return 0; } |
Пример 2
#include <stdio.h> char words[][18] = {"edno", "dve", "tri", "chetiri", "pet"}; char *ptr; int main(){ int i; for (i = 0; i < 5; i++) { printf("--%s--\n",words + i); ptr = *(words + i); printf("ptr + %d = %s \n", i, ptr); } return 0; } |
Пример 3
#include <stdio.h> char *words[] = {"edno", "dve", "tri", "chetiri", "pet"}; int main(){ int i; for (i = 0; i < 5; i++) { printf("ptr + %d = %s \n", i, *(words + i)); } return 0; } |