Electronic Elves Residence

Mysql field value constraint, not equal to zero

drop table if exists kucha;

create table kucha (`photo_id` int(10) unsigned NOT NULL);

insert into kucha (photo_id) values (1),(2),(0),(3),(0),(4);

delimiter $

create trigger ne_srat_v_kuchu before insert on kucha for each row
if NEW.photo_id = 0 THEN
signal sqlstate '45000' set message_text = "Please do not insert zeroes into this table";
end if;

delimiter ;

insert into kucha (photo_id) values (5);

insert into kucha (photo_id) values (2),(0),(3),(0),(4);

Recursive generator of recursive calling different functions

$generator = null;
$generator = function ($depth, $f, $each) use (&$generator) {
    if ($depth == 0) {
        return $f;
    $next_function = $generator($depth - 1, $f, $each);
    return function () use ($depth, $next_function, $each) {

$f = function() {
    echo "Last function\n";
    echo new \Exception();
$each = function($depth) {
    echo "This is $depth function\n";

$top = $generator(40, $f, $each);

php include mechanism

1. cwd/$include_path/$filepath
include_path empty string "", empty entry "something:", dot "." are all the same if include_path contains absolute path entries only then php automatically adds empty entry "" and tries that path
consider file hierarchy
include 'includee.php';
include 'classes/includee.php';

include_path is empty and cwd is /project and run classes/includer.php
tries for includee.php
/project/./includee.php (via cwd+include_path)
/project/classes/includee.php (via __DIR__)
tries for classes/includee.php
/project/./classes/includee.php (via cwd+include_path)

include_path is empty and cwd is /project/www and run ../classes/includer.php
tries for includee.php
/project/www/./includee.php (via cwd+include_path)
tries for classes/includee.php
/project/www/./classes/includee.php (via cwd+include_path)
/project/classes/classes/includee.php (via __DIR__)
/project/www/classes/includee.php (via cwd+include_path(auto))

include_path is /etc and cwd is /project/www and run ../classes/includer.php
tries for includee.php
/etc/includee.php (via include_path)
/project/classes/includee.php (via __DIR__)
tries for classes/includee.php
/etc/classes/includee.php (via include_path)
/project/classes/classes/includee.php (via __DIR__)
/project/www/classes/includee.php (via cwd+include_path(auto))

What Is in a Fart?

What Is in a Fart? A fart is composed of five major ingredients, and less than one percent hydrogen sulfide gas and mercaptans. The composition of a fart is 59 percent nitrogen, 21 percent hydrogen, 9 percent carbon dioxide, 7 percent methane, and 4 percent oxygen.
Why Do Some Farts Smell Worse Than Others? Sulfur causes the smell produced when farting. The more sulfur that is present in the diet, the more smelly the flatulence. Some common foods that include sulfur are cabbage, beans, eggs, and cheese.
Why Are Some Farts Louder Than Others? There are a few different factors that affect the noise produced by flatulence. This includes the tightness of the sphincter, the amount of gas, and the force behind the fart.
Do All Cultures Disapprove of Flatulence in Public? While most cultures feel that farts should be suppressed in polite company, there are some cultures that not only don't mind letting them fly in public, but they actually enjoy it. For example, the Indian tribe Yanomami from South America actually uses flatulence as a way of saying hello. In China, you can actually get a job as a professional fart-smeller! In ancient Rome, Emperor Claudius, fearing that holding farts in was bad for the health, passed a law stating that it was acceptable to break wind at banquets.
Can Farts Be Lit on Fire? While lighting farts on fire may seem like a cool party trick, it is quite dangerous. The methane and hydrogen found in a fart make it very flammable.
How Often Do People Fart? We know everyone farts, but how often? While many women will not admit to it, most individuals experience flatulence at least 14 times each day.
Is There Any Way to Prevent Flatulence? Flatulence is both natural and unavoidable. Corpses even have flatulence for up to three hours after death.
What Happens to Someone Holding in a Fart? Some people are not comfortable with flatulence. If they hold this in all day, the body will release the gas once the muscles relax. This often happens during sleep.
How much do people fart? On average, you'll pass about half a liter of gas a day.
Is Holding in Farts Bad for Health? There are disagreements on whether or not holding in flatulence is actually harmful. Some say it cannot hurt because it is part of a natural process. Others say holding in farts can cause bloating, hemorrhoids, and other uncomfortable symptoms.
How Fast Does Flatulence Leave the Body? Flatulence travels at speeds of up to ten miles per hour. The speed of a fart depends on the amount of pressure built up behind it.
What Species Farts the Most? Surprisingly, termites fart more than any other species. Termite flatulence is the second largest natural source of methane emissions, measuring between 2 and 22 Teragrams each year.
What Other Species Fart? The top ten farting animals are the following:1. Termites2. Camels3. Zebras4. Sheep5. Cows6. Elephants7. Dogs8. Humans9. Gerbils
What foods make you fart? Some of the food that cause flatulence are good for you. Cauliflower, Brussels sprouts, beans, broccoli, cabbage, and bran are the most common culprits. Fructose, the sugar found in fruit, and dairy products also cause more flatulence. Some foods, like eggs and meat, can cause stinkier farts because they are rich in sulfur.
Is it true you fart after death? It is true that you fart after you die. There is proof that you can't escape passing wind, even after you're dead! Up to three hours after the body dies, gasses continue to escape from both ends of the digestive tract, resulting in burping or farting noises. This phenomenon is due to muscles contracting and expanding before rigor mortis sets in.


What exactly is "iowait"?
To summarize it in one sentence, 'iowait' is the percentage of time the CPU is idle AND there is at least one I/O in progress.
Each CPU can be in one of four states: user, sys, idle, iowait. Performance tools such as vmstat, iostat, sar, etc. print out these four states as a percentage. The sar tool can print out the states on a per CPU basis (-P flag) but most other tools print out the average values across all the CPUs. Since these are percentage values, the four state values should add up to 100%.
The tools print out the statistics using counters that the kernel updates periodically (on AIX, these CPU state counters are incremented at every clock interrupt (these occur at 10 millisecond intervals). When the clock interrupt occurs on a CPU, the kernel checks the CPU to see if it is idle or not. If it's not idle, the kernel then determines if the instruction being executed at that point is in user space or in kernel space. If user, then it increments the 'user' counter by one. If the instruction is in kernel space, then the 'sys' counter is incremented by one.
If the CPU is idle, the kernel then determines if there is at least one I/O currently in progress to either a local disk or a remotely mounted disk (NFS) which had been initiated from that CPU. If there is, then the 'iowait' counter is incremented by one. If there is no I/O in progress that was initiated from that CPU, the 'idle' counter is incremented by one.
When a performance tool such as vmstat is invoked, it reads the current values of these four counters. Then it sleeps for the number of seconds the user specified as the interval time and then reads the counters again. Then vmstat will subtract the previous values from the current values to get the delta value for this sampling period. Since vmstat knows that the counters are incremented at each clock tick (10ms), second, it then divides the delta value of each counter by the number of clock ticks in the sampling period. For example, if you run 'vmstat 2', this makes vmstat sample the counters every 2 seconds. Since the clock ticks at 10ms intervals, then there are 100 ticks per second or 200 ticks per vmstat interval (if the interval value is 2 seconds). The delta values of each counter are divided by the total ticks in the interval and multiplied by 100 to get the percentage value in that interval.
iowait can in some cases be an indicator of a limiting factor to transaction throughput whereas in other cases, iowait may be completely meaningless. Some examples here will help to explain this. The first example is one where high iowait is a direct cause of a performance issue.
Example 1: Let's say that a program needs to perform transactions on behalf of a batch job. For each transaction, the program will perform some computations which takes 10 milliseconds and then does a synchronous write of the results to disk. Since the file it is writing to was opened synchronously, the write does not return until the I/O has made it all the way to the disk. Let's say the disk subsystem does not have a cache and that each physical write I/O takes 20ms. This means that the program completes a transaction every 30ms. Over a period of 1 second (1000ms), the program can do 33 transactions (33 tps). If this program is the only one running on a 1-CPU system, then the CPU usage would be busy 1/3 of the time and waiting on I/O the rest of the time - so 66% iowait and 34% CPU busy.
If the I/O subsystem was improved (let's say a disk cache is added) such that a write I/O takes only 1ms. This means that it takes 11ms to complete a transaction, and the program can now do around 90-91 transactions a second. Here the iowait time would be around 8%. Notice that a lower iowait time directly affects the throughput of the program.
Example 2:
Let's say that there is one program running on the system - let's assume that this is the 'dd' program, and it is reading from the disk 4KB at a time. Let's say that the subroutine in 'dd' is called main() and it invokes read() to do a read. Both main() and read() are user space subroutines. read() is a libc.a subroutine which will then invoke the kread() system call at which point it enters kernel space. kread() will then initiate a physical I/O to the device and the 'dd' program is then put to sleep until the physical I/O completes. The time to execute the code in main, read, and kread is very small - probably around 50 microseconds at most. The time it takes for the disk to complete the I/O request will probably be around 2-20 milliseconds depending on how far the disk arm had to seek. This means that when the clock interrupt occurs, the chances are that the 'dd' program is asleep and that the I/O is in progress. Therefore, the 'iowait' counter is incremented. If the I/O completes in 2 milliseconds, then the 'dd' program runs again to do another read. But since 50 microseconds is so small compared to 2ms (2000 microseconds), the chances are that when the clock interrupt occurs, the CPU will again be idle with a I/O in progress. So again, 'iowait' is incremented. If 'sar -P <cpunumber>' is run to show the CPU utilization for this CPU, it will most likely show 97-98% iowait. If each I/O takes 20ms, then the iowait would be 99-100%. Even though the I/O wait is extremely high in either case, the throughput is 10 times better in one case.

Example 3:
Let's say that there are two programs running on a CPU. One is a 'dd' program reading from the disk. The other is a program that does no I/O but is spending 100% of its time doing computational work. Now assume that there is a problem with the I/O subsystem and that physical I/Os are taking over a second to complete. Whenever the 'dd' program is asleep while waiting for its I/Os to complete, the other program is able to run on that CPU. When the clock interrupt occurs, there will always be a program running in either user mode or system mode. Therefore, the %idle and %iowait values will be 0. Even though iowait is 0 now, that does not mean there is NOT a I/O problem because there obviously is one if physical I/Os are taking over a second to complete.

Example 4:
Let's say that there is a 4-CPU system where there are 6 programs running. Let's assume that four of the programs spend 70% of their time waiting on physical read I/Os and the 30% actually using CPU time. Since these four programs do have to enter kernel space to execute the kread system calls, it will spend a percentage of its time in the kernel; let's assume that 25% of the time is in user mode, and 5% of the time in kernel mode. Let's also assume that the other two programs spend 100% of their time in user code doing computations and no I/O so that two CPUs will always be 100% busy. Since the other four programs are busy only 30% of the time, they can share that are not busy.
If we run 'sar -P ALL 1 10' to run 'sar' at 1-second intervals for 10 intervals, then we'd expect to see this for each interval:
cpu %usr %sys %wio %idle 0 50 10 40 0 1 50 10 40 0 2 100 0 0 0 3 100 0 0 0 - 75 5 20 0
Notice that the average CPU utilization will be 75% user, 5% sys, and 20% iowait. The values one sees with 'vmstat' or 'iostat' or most tools are the average across all CPUs.
Now let's say we take this exact same workload (same 6 programs with same behavior) to another machine that has 6 CPUs (same CPU speeds and same I/O subsytem). Now each program can be running on its own CPU. Therefore, the CPU usage breakdown would be as follows:
cpu %usr %sys %wio %idle 0 25 5 70 0 1 25 5 70 0 2 25 5 70 0 3 25 5 70 0 4 100 0 0 0 5 100 0 0 0 - 50 3 47 0
So now the average CPU utilization will be 50% user, 3% sy, and 47% iowait. Notice that the same workload on another machine has more than double the iowait value.

The iowait statistic may or may not be a useful indicator of I/O performance - but it does tell us that the system can handle more computational work. Just because a CPU is in iowait state does not mean that it can't run other threads on that CPU; that is, iowait is simply a form of idle time.

О раздражении

Причины возникновения раздражения:
1. Умные люди говорят, что нас раздражает в людях то, что свойственно нам самим. А точнее то, что мы не хотим в себе принимать и признавать. Тех черт характера, которых у нас нет, в другом человеке можем просто не заметить, либо отнесемся к ним равнодушно.
2. Люди не оправдывают наши ожидания. Чем ближе нам человек, чем более "своим" мы его считаем, тем больше от него требуем. Но у него-то свои цели и устремления и он не должен, да и не может сделать нас счастливыми.
3. Нас часто раздражают чужие успехи. Это происходит потому, что мы сравниваем свои слабые стороны с сильными сторонами других людей. Этому нас учили родители, учителя, да все наше общество, в котором поощряется соревнование, которое нетерпимо к ошибкам, которое плевать хотело на индивидуальность и личные склонности человека.
4. Мы с головой погружены в материальность, считаем ценными материальные вещи, те, за которые отдаем деньги (которые так тяжело зарабатывать!) и совершенно не ценим истинные ценности - человеческие взаимоотношения, то, что достается нам бесплатно. Мы любим вещи и пользуемся людьми. То есть, по большому счету, относимся к людям, как к вещам.
5. Мы не живем настоящим, а терзаемся прошлым и беспокоимся о будущем. Как часто, вместо того, чтобы наслаждаться радостью настоящего момента, дарить и принимать всю любовь, уважение, признательность, мы портим все дело воспоминаниями о нашей негативной реакции на какие-либо поступки человека, либо страхами о будущем, что нам эту любовь и уважение не удастся удержать.
6. Таково созданное нами общество. И чтобы изменить его, нужно начать с себя. То есть за все общество в ответе каждый в отдельности и все вместе. Конечно же, вы скажете: ну что может сделать один человек? Я лично всегда задаю себе такой вопрос: "Если не я, то кто?" Ответственность - другое название свободы.
Что из этого получается:
1. Нелюбовь и неприятие себя порождает нелюбовь окружающих, потому что мир вокруг - это лишь отражение мира внутри.
2. Негативные эмоции (которые и есть сама жизнь) раскрашивают всю нашу реальность в соответствующие тона. Мы сами притягиваем так называемую "черную" полосу.
3. Раздражаясь, мы отдаем свою силу. То есть заявляем Вселенной, что эти люди могут оказывать влияние на нашу жизнь. И Вселенная конечно же отвечает всегда одно и тоже: "Слушаю и повинуюсь." (Фильм Секрет)
Что с этим делать:
1. Помнить, всегда помнить, пока это не станет ощущаться всем существом, что мы - одно, что мы едины. Что нельзя победить за счет других, но можно - вместе . Что каждая душа пришла в этот мир для того чтобы решать свои задачи, и никто ничего вам не должен.
2. Принять себя целиком, полюбить, перестать сравнивать себя с другими. Принять как свои достоинства, так и свои недостатки, ибо "в каждом темном уголке души могут таиться сокровища". А когда мы примем и полюбим себя, мы автоматически полюбим и примем других таких, какие они есть.
3. Взять на себя ответственность за всех людей, которых мы притягиваем в свою жизнь. Каждый встреченный нами человек показывает нам нас, люди лишь зеркало наших отношений с миром.
4. Мы всегда вольны сами выбирать как реагировать на поведение другого человека. Мы можем не реагировать автоматически, рефлекторно (обижаться на оскорбление или радоваться похвале), а сами выбрать, создавать свои чувства, то есть быть креативными в этом вопросе. Дипак Чопра "Семь Духовных Законов Успеха"

Prepare OS X 10.11 El Capitan DVD iso image for Zalman VE-200

hdiutil create -size 16674816b ~/Desktop/osx-10.11

hdiutil attach -nomount ~/Desktop/osx-10.11.dmg
/dev/disk3          	GUID_partition_scheme
/dev/disk3s1        	EFI
/dev/disk3s2        	Apple_HFS

diskutil partitionDisk /dev/disk3 1 APM HFS+ INSTALL_ELCAPITAN R

hdiutil attach /Applications/Install\ OS\ X\ El\ Capitan.app/Contents/SharedSupport/InstallESD.dmg -noverify -nobrowse -mountpoint /Volumes/install_app

asr restore --source /Volumes/install_app/BaseSystem.dmg --target /Volumes/INSTALL_ELCAPITAN --erase

rm /Volumes/OS\ X\ Base\ System/System/Installation/Packages

cp -rvp /Volumes/install_app/Packages /Volumes/OS\ X\ Base\ System/System/Installation/

cp -rvp /Volumes/install_app/BaseSystem.chunklist /Volumes/OS\ X\ Base\ System/

cp -rvp /Volumes/install_app/BaseSystem.dmg /Volumes/OS\ X\ Base\ System/ 

hdiutil detach /dev/disk4

hdiutil detach /dev/disk3

How to install php 5.6 extensions with php 5.5 system-wide installed

emakhrov@ezhbadoo ~/D/s/p/e/xml$ ~/php56/bin/phpize ;and ./configure --prefix=/Users/emakhrov/php56 --with-php-config=/Users/emakhrov/php56/bin/php-config ; and make install

xml extension:
sed -i -e 's#ext/xml/##' ext/xml/php_xml.h

RRD howto

mysql -p -e 'select amount, created from site.balance where acc = 3 and created > now() - interval 10 day order by created' > 1

rrdtool create test.rrd --start 1400100500 --step 600 DS:ololo:GAUGE:600:U:U RRA:AVERAGE:0.5:1:1441

tail +2 1 | php -R 'list ($v, $t) = explode("\t", $argn, 2); $t = strtotime($t); $t = floor($t / 60) * 60; $cmd= "rrdtool update test.rrd $t:$v"; system($cmd); echo "$cmd\n";'

rrdtool graph test.svg -a SVG -D --start 1425601000 --end 1426519000 -l 0 -w 800 -h 800 DEF:rofl=test.rrd:ololo:AVERAGE 'LINE2:rofl#FF0000'

php -S