Набираем
"su"
"data2ext --enable" (без кавычек и пробел перед двумя --).Должно написать data to ext enabled.
"reboot"
понедельник, 16 декабря 2013 г.
пятница, 13 декабря 2013 г.
Google ‘ORGANIC’ versus ‘PAID’ using only referrer's url
‘ORGANIC’ VS ‘PAID’
![]() |
Paid Adwords |
![]() |
Organic (Natural) |
For differentiate paid
keywords (from google adwords) from
organic keywords (from natural google search) using referral URL we must look
at URL path if it contain “aclk” then it AdWords, also “sa=l” or “sa=L” must be
set, also look at “adurl” (but it only for new).
Example : http://www.google.ru/aclk?sa=L&ai=CGQe9IKiqUre0Dcb57Abu64CABqmNzboEmeuhqXvPyIIJCAAQASgCUNCU__78_____wFghAXIAQGpAq-L8S2ZvUQ-qgQlT9Ddw9sbMjt6r62EdrGu_psl8xtrz1o3ltazQPTiTFX1Yrd6BboFEwiSy4-fyKy7AhUyBtsKHYoMAPPKBQCAB8Gp0i6QBwE&ei=IKiqUpK7BrKM7AaKmYCYDw&sig=AOD64_1pMv15FgOb54PR1JPhxPdW5MkL_Q&rct=j&q=buy+used+cars&sqi=2&ved=0CCgQ0Qw&adurl=https://www.tqmbazaar.com
In addition to the new google url format
there are three others:
- google.com/search (old format)
- google.com/url (new format)
- google.com/ie (mobile search)
- google.com/webhp (contains #hash query)
- google.com/aclk (adwords)
#hash query example: http://www.google.com/webhp#hl=en&q=flowers&btnG=Google+Search&aq=f&oq=flowers&fp=g9hIhDHDw6.
Resume
Here described new google’s url
construction for finding differences between “organic” and “paid” referrals
using URL.
Sources:
- https://gqs-decoder.appspot.com/
- https://github.com/beschulz/ved-decoder
- https://www.drivingbusinessonline.com.au/articles/whats-the-difference-between-seo-and-google-adwords/
- http://jwebnet.net/advancedgooglesearch.html#imgRestrict
- https://developers.google.com/search-appliance/documentation/50/xml_reference
- http://www.rankpanel.com/blog/google-search-parameters/
- http://analytics.blogspot.co.uk/2009/04/upcoming-change-to-googlecom-search.html
- http://www.t75.org/2012/06/deconstructing-googles-url-search-parameters/
- http://www.seomanontroppo.com/google-news-analytics-stuff/
- http://moz.com/blog/decoding-googles-referral-string-or-how-i-survived-secure-search
- https://support.google.com/adwords/answer/2404246?hl=en
- https://www.en.adwords-community.com/t5/Manage-ads/Dynamic-Destination-URL/td-p/200110/page/2
- http://gqs-decoder.blogspot.com/2013/08/google-referrer-query-strings-debunked-part-1.html
вторник, 10 декабря 2013 г.
Delphi's TDateTime to unixtime using PHP
if we have binary file wich was created using Delphi, and it's contain binary representation of TDateTime, you may read data using php the next way
function DelphiTimeToUnix(){
$fp = fopen("./dumped/file-1007.sta", "rb");
if ($fp) {
$i = 8;
$data = fread($fp, $i); //Data
$number = unpack("d", $data);
$current_tz = date_default_timezone_get();
date_default_timezone_set('UTC');
$unix_start = 25569.0; //Unix start representation in a Delphi's format
echo date("F j, Y, g:i a", ($number[1] - $unix_start + 0.00000001) * 86400) . PHP_EOL;
function UnixToDelphiTime(){
$current_tz = date_default_timezone_get();
date_default_timezone_set('UTC');
$unix_start = 25569.0; //Unix start representation in a Delphi's format
echo date( ($number[1] - $unix_start + 0.00000001) * 86400) . PHP_EOL;
The delphi dumps date as "double" which allocate 8 bytes for store
function DelphiTimeToUnix(){
$fp = fopen("./dumped/file-1007.sta", "rb");
if ($fp) {
$i = 8;
$data = fread($fp, $i); //Data
$number = unpack("d", $data);
$current_tz = date_default_timezone_get();
date_default_timezone_set('UTC');
$unix_start = 25569.0; //Unix start representation in a Delphi's format
echo date("F j, Y, g:i a", ($number[1] - $unix_start + 0.00000001) * 86400) . PHP_EOL;
}
}function UnixToDelphiTime(){
$current_tz = date_default_timezone_get();
date_default_timezone_set('UTC');
$unix_start = 25569.0; //Unix start representation in a Delphi's format
echo date( ($number[1] - $unix_start + 0.00000001) * 86400) . PHP_EOL;
}
The delphi dumps date as "double" which allocate 8 bytes for store
sources:
вторник, 20 августа 2013 г.
четверг, 15 августа 2013 г.
jQuery Download Plugin
http://stackoverflow.com/a/14717637/2564525
The answer mentioning "jQuery Plugin for Requesting Ajax-like File Downloads" got me headed down the right direction, but it didn't work entirely for my situation since I have a complex object and array of objects to pass in as my search criteria/filter data. I figured I'd share my code in case someone else runs into this situation too.
$.download = function (url, data, method) {
if (url && data) {
//convert the data object into input HTML fields
var inputs = '';
var convertToInput = function (key, keyStr, obj) {
if (typeof obj === 'undefined') {
return;
} else if (typeof obj === "object") {
for (var innerKey in obj) {
if (obj.hasOwnProperty(innerKey)) {
var innerKeyStr = '';
if (keyStr === '') {
innerKeyStr = innerKey.toString();
} else {
innerKeyStr = keyStr + "[" + innerKey.toString() + "]";
}
convertToInput(innerKey, innerKeyStr, obj[innerKey]);
}
}
return;
} else if ($.isArray(obj)) {
obj.forEach(function (item) {
convertToInput(key, keyStr + "[]", item);
});
return;
}
inputs += "";
};
convertToInput(null, '', data);
//send request
jQuery('
+ url + '" method="' + (method || 'post') + '">' + inputs + '
').appendTo('body').submit().remove();
};
};
$.download('/api/search?format=csv', searchData, 'POST');
It probably doesn't make much of a difference, but to provide some context, I've got a javascript and knockout UI calling into WebAPI, MVC4, and nHibernate. The 'format=csv' part of the query string triggers a MediaTypeFormatter to convert the returned models into a CSV file type. If I leave that off, then I get the models back from the API and can populate a Slick grid for display.
вторник, 6 августа 2013 г.
Drupal Questions
Для тех, кто не имеет опыта с web и drupal:
Environment:
- Установить Linux. Это может быть Ubuntu, Debian, OpenSUSE, Fedora, Linux Mint. Мы используем Ubuntu.
- Установить AMP stack (Apache, PHP 5.3, MySQL, phpmyadmin)
- NetBeans 7
Drupal:
- Установить Drupal 7 (не из пакетов, a c drupal.org)
- Плюсом будет знание о drush и умение его использовать.
Разобраться c темами :
- Ноды (node)
- Система хуков (hooks)
- Система теминга (theme)
- Блоки (blocks)
- Drupal coding standarts http://drupal.org/coding-standards
- Таксономия (taxonomy)
- Уметь создавать тип материала, добавлять ему поля разных типов.
- Создавать несколько нод этого типа.
- Добавлять к ним комментарии.
Познакомится с модулями:
1. http://drupal.org/project/views
Вывести список нод этого материала, отсортированных по количеству комментариев.
Вывести список нод этого материала, отсортированных по количеству комментариев.
2. http://drupal.org/project/panels
Вывести на панели рядом два списка с сортировкой по комментариям в разных направлениях. Попробовать разобраться с ctools плагинами для панелей.
Вывести на панели рядом два списка с сортировкой по комментариям в разных направлениях. Попробовать разобраться с ctools плагинами для панелей.
3. http://drupal.org/project/admin_menu
Установить, разобраться зачем он нужен.
Установить, разобраться зачем он нужен.
Лучшие учебные пособия - drupal.org, php.net
Для опытных:
Как работает веб:
- AMP стек, объяснить как работает с момента ввода адреса сайта, до момента полной прогрузки страницы.
- Протокол HTTP, Методы Post и Get
Основные вопросы по Drupal
Hook.
- Что такое хук, зачем нужны и как используются?
- Список наиболее популярные хуков (hook_menu, hook_theme, hook_form_alter, hook_nodeapi, hook_user …)
- Как создать свой хук?
- hook_theme, для чего используется? Как его можно использовать? Куда ложить файлы шаблонов? Как именовать препроцессы?
- hook_menu, как создать свой меню итем? Основные правила при создании меню итема. Когда нужно выносить коллбэк в отдельный файл. Какие типы меню итемов бывают?
- hook_views_* - основные хуки, как и для чего используются?
- hook_schema - что такое, зачем нужен, пример
- hook_update - правила написания, как работает
- hook_install, hook_uninstall - зачем использовать, примеры
- menu в drupal, как это работает?
Coding standards.
- Правила именования модулей, функций, файлов модулей.
- Drupal coding standards, основные моменты
- db_query(), db_select() и другие функции для работы с БД, основные правила.
- Когда нужно создавать свой модуль?
Forms.
- Как создать форму?
- Как отрисовать форму программно?
- Как изменить чужую форму?
- Типы элементов, основные свойства.
- Теминг формы
- validate, submit, after_build, pre_render формы.
- System settings forms
- AHAH. Что такое, как использовать?
Content
- Content-type - что такое? как создать? основные правила создания
- Fields - типы полей, правило именования
- Build mode - что такое и как это использовать?
- Как друпал хранит поля в базе
Views.
- Зачем нужен? Примеры использования
- Типы дисплеев, типы шаблоны, стили.
- Что такое relationship во вьюхе? Как это работает?
- Аргументы, как это использовать?
Panels.
- Что это панель, регион, вариант, пэйн?
- Стандартные панели. Что такое selection rules?
- Panels everywhere - для каких целей и как использовать?
Ctools plugins.
- Content-type - что такое и когда стоит использовать? Отличие от блоков.
- Style - что такое, для чего применяется?
- Context - что такое, для чего применяется?
- Access - что такое, для чего применяется?
- Layout - что такое? как создать свой лэйаут?
Token.
- Что такое токен и для чего используются, примеры?
- Как создать свой собственный токен?
Image.
- Основные image style экшены (Scale, Resize, Scale & Crop, Canvas, Overlay)
- Как программно отрисовать картинку без презета/с презетом?
- Как работает модуль image?
Input format.
- Plain text, Filtered text - отличие, когда что нужно использовать?
- Input format - для чего нужны? Примеры.
Features.
- Для чего нужен? Примеры использования.
JS, CSS, JSS
- Способы подключения собственного JS
- Что такое Drupal.settings? Примеры использования.
- Behavior, что такое и зачем использовать?
- Основные стандарты кодинга в JS
Cache
- drupal_static(), cache_set(), cache_get().
- Что такое memcache? Зачем и как использовать?
- Boost, что такое, как работает? Когда надо использовать?
Apachesolr
- Что такое, как настроить?
- Как добавить/исключить контент-тайпы/поля из индексации
- Как затемить вывод результатов?
- Фасеты, что это такое
среда, 10 июля 2013 г.
php_svn.dll for x86 php 5.3
http://fragfrog.nl/blog/142/SVN%20integration%20for%20PHP%20with%20pvp_svn/
вторник, 9 июля 2013 г.
среда, 3 июля 2013 г.
How to make multiple updates using a single query in MySQL
source : http://blog.bubble.ro/how-to-make-multiple-updates-using-a-single-query-in-mysql/
However, you can do a very interesting trick. You can combine an UPDATE with a CASE like this:
How to make multiple updates using a single query in MySQL
April 20, 2008 - Posted by Indy
As you might know it’s quite easy to make multiple INSERTs in a single query, like this:
INSERT INTO mytable
(id, title)
VALUES
('1', 'Lord of the Rings'),
('2', 'Harry Potter');
However, for some strange reason you can’t do multiple changes to a table in a single UPDATE query like this:
UPDATE mytable
SET (title='Great Expectations' WHERE id='1'),
(title='War and Peace' WHERE id='2');
However, you can do a very interesting trick. You can combine an UPDATE with a CASE like this:
UPDATE mytable SET title = CASE
WHEN id = 1 THEN 'Great Expectations';
WHEN id = 2 THEN 'War and Peace';
ELSE title
END;
The ELSE title is very important, otherwise you will overwrite the rest of the table with NULL.
You might wonder why on earth you’d want to make multiple updates in a single query. Here’s an example that might not be so obvious:
Let’s say you want to make a page view counter for your shop, but you want to implement caching for your pages and running an SQL UPDATE query for each page is out of the question. An efficient solution would be to make a logfile with each view as a new line appended in a file.
Here’s an example of logfile, with each view logged on a single line using this format:IP | PRODUCT_ID
78.32.43.2|3
54.133.87.54|2
85.83.93.91|4
The append part is most important, since it’s the only file writing mode that can be used with multiple processes (remember that you have MANY viewers at the same time, and if only 2 of them try to write a file at the same time your file will be pretty much screwed – no, you don’t lose the file itself, you just lose the content, which is even more important).
An alternative would be to use file locking, but it’s really really inefficient when you have lots of visitors (digg effect anyone?). However, the append mode is optimized by the operating system and stores the content in a buffer, making sure the content is write properly.
So, the best solution would be to make a logfile and then process this file with a cron job. It’s very easy to do that, but the challenge lies in updating the database. Here’s where the multiple updates in a single query trick comes into play.
You can just create a long query to update the database and run it only once instead of hundreds of small queries (which in case you didn’t figure it out, would bring your database to its knees in many cases).
So we can make a script to parse our logfile like this:
$logfile = 'logfile.txt';
$views = array();
$ip_db = array();
$lines = file($logfile);
$cnt = count($lines);
for ($i=0; $i<$cnt; $i++)
{
if (preg_match('/([0-9.]+)\|([0-9]+)/', $lines[$i], $regs))
{
$ip = $regs[1];
$id = $regs[2];
if (!isset($ip_db[$ip]))
{
$ip_db[$ip] = 1;
$views[$id]++;
}
}
}
if (empty($views))
{
exit;
}
$query = "UPDATE products SET views = CASE ";
$idlist = '';
reset($views);
while (list($id, $val) = each($views))
{
$query .= " WHEN id = ".$id." THEN views + ".$val." ";
$idlist .= $id.',';
}
$idlist = substr($idlist, 0, -1);
$query .= "
END
WHERE id IN (".$idlist.")";
// run $query
Simple and efficient. And did I mention it’s also free?
Download link: parse_logfile.php
Important update:
Just as Jesper pointed out using transactions instead of CASE can make a huge difference.
Here are the results of some tests made on a 316,878 records database using both MyISAM and InnoDB storage engine.
InnoDB
Rows updated | Transactions time (in seconds) | CASE time (in seconds) |
---|---|---|
400 | 6s | 11s |
1000 | 20s | 17s |
30000 | (too long) | (too long) |
MyISAM
Rows updated | Consequent queries time (in seconds) | CASE time (in seconds) |
---|---|---|
400 | 0s | 6s |
1000 | 0s | 13s |
30000 | 10 | (too long) |
As you can see the results are very interesting. You can clearly see the difference of both storage engine and transactions (at least for MyISAM). In other words, if you use MyISAM (and many people do), use transactions for multiple updates. If you use InnoDB switch to MyISAM and them use transactions.
The CASE method seems to be efficient only for few updates (so you can make a cron job to run updates more frequently), but overall you can see clearly that you can still use transactions and get better results.
I hope the method described in this post helped you or at least gave you more ideas on how to use it for any of your projects, and if you didn’t know about transactions, maybe you should give it more attention (I sure will from now on).
Second (and hopefully final) update:
After a bit of research I figured out MyISAM doesn’t support transactions (yes, silly me), so the tests above were done using simple consequent queries (modified up there as well). However, it seems MySQL does some internal optimizations and runs themvery efficiently. If you have a busy database it’s a good idea to do a LOCK TABLE query before the batch update though (and of course don’t forget to UNLOCK the table when done).
Also after a few suggestions I got to a much faster version (read the comments below – Thanks, guys).
So here’s the final CASE version:
UPDATE mytable SET title = CASE
WHEN id = 1 THEN ‘Great Expectations’
WHEN id = 2 THEN ‘War and Peace’
...
END
WHERE id IN (1,2,...)
Although it doesn’t beat the speed of normal queries run in a row, it can still get close enough.
Also, since many people asked why bother that much when you can just run the normal queries, you can consider this an experiment to find alternatives. Also, keep in mind that in order to gain advantage of MySQL optimizations all those UPDATE queries need to be run in a batch. Running each UPDATE query when the page is viewed for example is not the same thing (and that’s pretty much the problem I wanted to solve as efficiently as possible).
Also, as a final note, you should always run an OPTIMIZE TABLE query after all these updates.
понедельник, 3 июня 2013 г.
Zend i18n & l10n
MySQL: cравнение даты (datetime) через оператор BETWEEN
http://tigor.com.ua/blog/2008/08/23/date_comparison_by_between_operator_of_mysql/
Примеры запросов с BETWEEN и без него:
Оператор BETWEEN идеально подходит для сравнения диапазона между датами (datetime). Но тут есть подводные камни. Например, есть задача — выбрать данные из таблицы за некоторый промежуток времени (с ’2008-08-14′ по ’2008-08-23′).
Рекомендации:
1. Выполняя любые сравнения, приводить все данные к одному типу.
2. Если один операнд имеет значение типа TIMESTAMP или DATETIME, а другой является константой, операнды сравниваются как значения типа TIMESTAMP. А это значит, что если была строка в виде ’2008-08-14′, то она автоматически преобразуется в TIMESTAMP ’2008-08-14 00:00:00′ и это влияет на результат запроса.
3. Над данными, которые участвуют в условиях сравнения желательно не делать никаких операций — это позволяет для них использовать индексы, иначе они игнорируются.
1. Выполняя любые сравнения, приводить все данные к одному типу.
2. Если один операнд имеет значение типа TIMESTAMP или DATETIME, а другой является константой, операнды сравниваются как значения типа TIMESTAMP. А это значит, что если была строка в виде ’2008-08-14′, то она автоматически преобразуется в TIMESTAMP ’2008-08-14 00:00:00′ и это влияет на результат запроса.
3. Над данными, которые участвуют в условиях сравнения желательно не делать никаких операций — это позволяет для них использовать индексы, иначе они игнорируются.
Примеры запросов с BETWEEN и без него:
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
| # Поле created_at - тип DATETIME # КОРРЕКТНЫЕ ЗАПРОСЫ # 1: Индексы для created_at поля не используются. # Условие BETWEEN '2008-08-14' AND '2008-08-23' # преобразуется в BETWEEN '2008-08-14 00:00:00' AND '2008-08-23 00:00:00' . SELECT * FROM news WHERE DATE (created_at) BETWEEN '2008-08-14' AND '2008-08-23' ; # 2: Оператор BETWEEN не используем, но тоже не самый лучший вариант, индексы не используются SELECT * FROM news WHERE DATE (created_at) >= '2008-08-14' AND DATE (created_at) <= '2008-08-23' ; # 3: Строки '2008-08-14 00:00:00' и '2008-08-23 23:59:59' не приведены к типу данных DATE SELECT * FROM news WHERE created_at BETWEEN '2008-08-14 00:00:00' AND '2008-08-23 23:59:59' ; # 4: Самый лучший вариант, привели к типу DATETIME, индексы будут использоваться SELECT * FROM news WHERE created_at BETWEEN STR_TO_DATE( '2008-08-14 00:00:00' , '%Y-%m-%d %H:%i:%s' ) AND STR_TO_DATE( '2008-08-23 23:59:59' , '%Y-%m-%d %H:%i:%s' ); ############################# # НЕПРАВИЛЬНЫЕ ЗАПРОСЫ # 5: Строки '2008-08-14' и '2008-08-23' преобразуются в TIMESTAMP и дополняются '00:00:00' SELECT * FROM news WHERE created_at >= '2008-08-14' AND created_at <= '2008-08-23' ; # 6: Аналогично запросу 5 SELECT * FROM news WHERE created_at BETWEEN STR_TO_DATE( '2008-08-14' , '%Y-%m-%d' ) AND STR_TO_DATE( '2008-08-23' , '%Y-%m-%d' ); |
Получаем самый лучший запрос:
1
2
3
| SELECT * FROM news WHERE created_at BETWEEN STR_TO_DATE( '2008-08-14 00:00:00' , '%Y-%m-%d %H:%i:%s' ) AND STR_TO_DATE( '2008-08-23 23:59:59' , '%Y-%m-%d %H:%i:%s' ); |
Подписаться на:
Сообщения (Atom)