Autotools стоило бы использовать даже если бы единственным эффектом было бы недопущение идиотов к разработке.
#!/usr/bin/node
function gcd2(a, b) {
return b == 0 ? a : gcd2(b, a % b);
}
// Don't use parseInt() itself in map() - it used to have 2 arguments
var nums = process.argv.map(
function(s) {return parseInt(s)}
).filter( // It will not work if this script or node itself is named as number ;-)
function(t) {return !isNaN(t)}
);
if (nums.length > 0) {
var GCD = nums.reduce(gcd2); // Yeah, we could use lambda here
console.log(GCD);
}
/*
SYNOPSIS:
With GCC >= 4.6:
# gccgo gcd.go -o gcd-go
# ./gcd-go 11 22 33 44 121
With Google Go (6g for amd64, 8g for x86):
# 6g -o gcd-go.o gcd.go
# 6l -o gcd-go-6g gcd-go.o
# ./gcd-go-6g 11 22 33 44 121
GCC makes dynamically linked binary,
but Google Go - statically linked
*/
package main
// Both Google Go and GCC issue an error "imported and not used",
// if imported and not used :-)
import "fmt"
import "flag"
import "strconv"
func gcd2 (a, b uint) uint {
if b == 0 {
return a
}
/* 6g issues an error "function ends without a return statement",
if we use if ... {... return} else {... return}.
But GCC doesn't.
*/
return gcd2(b, a % b)
}
func gcdn (ns []uint) uint {
var r uint // zero by default
for i := range ns {
r = gcd2(r, ns[i])
}
return r
}
func main() {
flag.Parse() // without this 6g will give flag.NArg() = 0 next (WTF?)
n := flag.NArg()
if n > 0 {
ns := make([]uint, n) // We have garbage collector!
// Or: for i := range ns, since range of ns is equal to flag.NArg()
for i := 0; i < n; i++ {
// Drop the second return value (error code):
ns[i], _ = strconv.Atoui(flag.Arg(i))
}
g := gcdn(ns)
fmt.Printf("%v\n", g)
}
}
https://github.com/ip1981/GCD/blob/mast
По системным вызовам Соляриса:
http://my.opera.com/myrkraverk/blog/201
Различия с линуксовой версией:
--- gcd-x86-linux.s 2011-07-04 00:33:43.000000000 +0400
+++ gcd-x86-solaris.s 2011-07-14 20:31:09.000000000 +0400
@@ -68,12 +68,15 @@
# printing the number:
mov $4, %eax # syscall `write'
- mov $1, %ebx # write to stdout
- mov %edi, %ecx # first character to write
mov $buf_end, %edx
sub %edi, %edx # edx is a number of characters to write (buf_end - edi)
inc %edx # + new line
- int $0x80 # do syscall (print the number)
+ push %edx
+ push %edi # first character to write
+ push $1 # write to stdout
+ push $0 # dummy
+ int $0x91 # do syscall (print the number)
+ add $16, %esp # clean stack 16 = 4 * 4 (32 bits!)
ret
@@ -133,6 +136,7 @@
exit:
mov $1, %eax # exit syscall
- xor %ebx, %ebx # exit code = 0
- int $0x80
+ push $0 # exit code = 0
+ push $0 # dummy
+ int $0x91
https://github.com/ip1981/GCD/blob/mast
С отличие от чистого Си, одну и ту же программу можно
использовать и для встроенного unsigned int, и для GMP.
(https://github.com/ip1981/GCD/blob/mas
https://github.com/ip1981/GCD/blob/mast
Перегрузка функций, обобщённое программирование, все дела :-)
( Программа )
Очень приятный язык.
https://github.com/ip1981/GCD/blob/mast
#!/usr/bin/env ruby
def gcd2 a, b
if b == 0
a
else
gcd2 b, a % b
end
end
# http://railspikes.com/2008/8/11/understanding-map-and-reduce
def gcdn ns
ns.reduce{ |a, b| gcd2 a, b }
end
puts gcdn ARGV.collect{ |s| s.to_i }
# ./gcd.rb 121 363 33 11
https://github.com/ip1981/GCD/blob/mast
Невероятный по красоте способ перевода строки в целое число
(http://www.cyberforum.ru/archive/t-214
str2uint_loop: lodsb # going forward from esi # HINT: assert '0' <= al <= '9' lea (%ebx, %ebx, 4), %ebx # ebx = 4*ebx + ebx = 5*ebx ;-) lea -48(%eax, %ebx, 2), %ebx # ebx = 2*ebx + %eax - 48 # ebx is multiplied by 10 each iteration, # eax-48 will be multiplied at the next iteration ;-) loop str2uint_loop ret
Язык в целом приятный, но доступ к командной строке,
стандартизированный только в Фортране 2003, убивает.
https://github.com/ip1981/GCD
! SYNOPSIS:
!
! # gfortran -o gcd-f gcd.f03
! # ./gcd-f 11 22 33 121
!
program GCD
implicit none
integer, allocatable :: ns(:)
integer :: i, n
character*20 :: tmpstr
n = command_argument_count()
allocate(ns(n)) ! allocate memory for numbers given in command line
do i = 1, n
call get_command_argument(i, tmpstr)
ns(i) = str2int(tmpstr)
end do
print *, gcdn(ns)
deallocate(ns)
! If we declare functions first,
! we have to specify its types within
! the `program' section.
! See http://en.wikibooks.org/wiki/Fortran/Fortran_procedures_and_functions
contains
pure integer function str2int (s)
character*(*), intent(in) :: s
read (s, *) str2int
end function
pure recursive integer function gcd2 (a, b) result(GCD)
integer, intent(in) :: a, b
if (b == 0) then
GCD = a
else
GCD = gcd2(b, mod(a, b))
end if
end function gcd2
pure integer function gcdn(n)
integer, intent(in) :: n(:) ! n is an array
integer :: i
gcdn = n(1)
do i = 2, size(n)
gcdn = gcd2(gcdn, n(i))
end do
end function
end program
Наибольший общий делитель на Тикле:
https://github.com/ip1981/GCD/blob/mast
Даны два элемента дерева, надо найти их ближайшего общего предка.
Решение такое. Начинаем с корня.
Если один слева, а другой справа — предок найден (корень).
Если слева никого — идём рекурсивно направо.
Если справа никого — идёи рекурсивно налево.
Если оба элемента на одной ветви, то этот алгоритм не работает.
Ну и фиг с ним, ибо тогда один из элементов является предком другого.
( Код на Си и пример с картинкой )
http://algolist.manual.ru/olimp/rec
Задачи 2 и 3.
Компилировать командой
gcc -Wall -Wextra -ansi -pedantic -lm happy.c -o happy
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
char n[] = "00";
void next (char *n)
{
++(*n);
while (*n > '9') {
*n = '0';
++n;
if (*n != '\0')
++(*n);
else
break;
}
}
int happy (char n[], size_t l)
{
size_t i;
int s = 0;
for (i = 0; i < l/2; ++i)
s += n[i];
for (i = l/2; i < l; ++i)
s -= n[i];
return s;
}
int main ()
{
int i;
size_t l;
size_t count = 0;;
l = strlen(n);
for (i = 0; i < pow(10, l); ++i) {
printf("%s -> ", n);
if (0 == happy(n, l)) {
printf("happy :-)\n");
++count;
}
else
printf("usual :-(\n");
next(n);
}
printf ("Total happy: %lu\n", (unsigned long)count);
return EXIT_SUCCESS;
}
#!/usr/bin/env lua
-- SYNOPSIS:
-- # chmod +x gcd.lua; ./gcd.lua 121 22 33 44
-- # lua gcd.lua 121 33 22
-- http://www.lua.org/pil/6.3.html
function gcd2(a, b)
if b == 0 then
return a
else
return gcd2(b, a % b)
end
end
function gcdn(ns)
r = ns[1]
local r = ns[1]
for i = 2, table.maxn(ns) #ns do
r = gcd2(r, ns[i])
end
return r
end
print(gcdn(arg))
Упростил запрос баланса и, главное,
добавил отправку SMS. Пока только латиницей.
http://lj.rossia.org/users/igorpashev/9
http://www.developershome.com/sms/smsIn
http://www.communica.se/multitech/gprs_
#!/usr/bin/env python3
#coding: utf8
import io
class Modem:
def __init__(self, dev='/dev/ttyUSB1'):
self.stream = io.open(dev, 'w+b', 0)
def __write(self, s):
self.stream.write(str.encode('{}\r\n'.format(s)))
def close(self):
self.stream.close()
def ussd(self, code):
self.__write('AT+CUSD=1,{},15'.format(code))
def balance(self, code='*100#'):
self.ussd(code)
for l in self.stream:
if l.startswith(b'+CUSD'):
msg = l[10:l.rfind(b'"')].decode('ascii')
return bytes.fromhex(msg).decode('utf-16-be')
def sendSMS(self, phone, msg):
self.__write('AT+CMGS="{}"'.format(phone))
self.__write('{}\x1a'.format(msg))
modem = Modem()
modem.sendSMS('+7XXXXXXXXXX', 'test')
![]() |
Альбом: Any key |
Подсмотрел здесь: http://ru.gentoo-wiki.com/wiki/MF62
Переписал на Python 3, сделал расширяемым.
В таком виде показывает баланс и рекламу :-)
Раскрасил так:
pygmentize -f html -O 'noclasses=true' 1.py
#!/usr/bin/env python3
#coding: utf8
import time, io
class Modem:
p = None
def __init__(self, dev='/dev/ttyUSB1'):
self.open(dev)
def open(self, dev):
#self.close()
self.p = io.open(dev, 'w+b', 0)
def write(self, s):
self.p.write(str.encode(s) + b'\r\n')
time.sleep(0.1)
def close(self):
self.p.close()
def ussd(self, code):
self.write('AT+CPBS="SM"')
self.write('AT+CPMS="SM","SM",""')
self.write('AT+ZSNT=0,0,2')
self.write('AT+CUSD=1,' + code + ',15')
for ln in self.p:
if ln.startswith(b'+CUSD'):
msg = ln[10:ln.rfind(b'"')].decode('ascii')
return bytes.fromhex(msg).decode('utf-16-be')
def balance(self, code='*100#'):
return self.ussd(code)
modem = Modem()
print(modem.balance())
Со школьных времён я при изучении нового языка пишу на нём алгоритм Евклида для нахождения наибольшего общего делителя (НОД). Здесь — https://github.com/ip1981/GCD — я начал собирать коллекцию программ на разных языках. У них одна идея: программа ищет НОД для чисел, указанных в командной строке. Возможно, я добавлю чтение из файла, так как главная цель — не НОД, а возможности языка. Я знаю про Rosetta Code, но там каша из кода, написанного разными людьми, не доведённого до конца, местами говнокод.
( НОД на Прологе )P. S. https://docs.google.com/document/pub?id=1
Дано несколько файлов TeX.
Надо построить картинку их зависимостей (какой в каком используется).
![]() |
Альбом: Screenshots |
Зум на 150% работал не правильно,
!!document — доставляет.
diff -urdb djview4-4.6/src/qdjview.cpp djview4-4.6.pin/src/qdjview.cpp
--- djview4-4.6/src/qdjview.cpp 2010-07-05 00:09:53.000000000 +0400
+++ djview4-4.6.pin/src/qdjview.cpp 2010-12-26 12:26:16.000000000 +0300
@@ -477,7 +477,7 @@
actionZoom150 = makeAction(tr("150%", "Zoom|"), false)
<< tr("Magnify 150%")
- << QVariant(200)
+ << QVariant(150)
<< Trigger(this, SLOT(performZoom()))
<< *zoomActionGroup;
@@ -911,7 +911,7 @@
actionZoom100->setChecked(zoom == 100);
actionZoom75->setChecked(zoom == 75);
actionZoom50->setChecked(zoom == 50);
- zoomCombo->setEnabled(!!document);
+ zoomCombo->setEnabled(document);
int zoomIndex = zoomCombo->findData(QVariant(zoom));
zoomCombo->clearEditText();
zoomCombo->setCurrentIndex(zoomIndex);
@@ -930,7 +930,7 @@
actionDisplayForeground->setChecked(mode == QDjVuWidget::DISPLAY_FG);
actionDisplayHiddenText->setChecked(mode == QDjVuWidget::DISPLAY_TEXT);
modeCombo->setCurrentIndex(modeCombo->fi
- modeCombo->setEnabled(!!document);
+ modeCombo->setEnabled(document);
// Rotations
int rotation = widget->rotation();
</font
В какой-то версии DjView4 диапазон печати страниц стал задаваться
нередактируемыми (editable=false) QComboBox.
Это реально заколебало, особенно когда в файле 1000 страниц,
а надо распечатать 567-580, например.
Этот патч исправляет проблему.
Эта проблема есть не только в диалоге печати,
но и в других, например, в диалоге экспорта.
Но меня заколебала именно печать.
Хотя, по-хорошему, задание страниц надо сделать
как-то так:1,3,5-12
И вообще, все диалоги в одном файле — это страшно.
( патч )
> Anyone who has ever peeked under the covers
> and looked into the sources of Qt has most likely noticed
> macros called Q_D and Q_Q.
Да-да, я тоже.
http://www.qtcentre.org/wiki/index.p
Каюсь, грешен.
Наибольший общий делитель нескольких чисел на C#.
Использование:
# gmcs gcd.cs
# mono ./gcd.exe 121 11 33 44
11
# mono ./gcd.exe 2 4 6 8
2
1 using System;
2
3 namespace GCD {
4 class Program {
5 static uint gcd2(uint a, uint b) {
6 uint c;
7 while (b != 0) {
8 c = b;
9 b = a % b;
10 a = c;
11 }
12 return a;
13 }
14
15 static uint gcdn(uint [] n) {
16 uint r = n[0];
17 for (int i = 1; i < n.Length; i++)
18 r = gcd2(r, n[i]);
19 return r;
20 }
21
22 static void Main(string [] argv) {
23 uint [] a = Array.ConvertAll<string, uint>(argv,
24 new Converter<string, uint>
25 (delegate(string s) {return uint.Parse(s);})
26 );
27
28 Console.WriteLine("{0}", gcdn(a));
29 }
30 }
31 }
32
Navigate: (Previous 20 Entries)