Частичный дамп

После импорта дампа выполненного в режиме экспорта схемы, нескольких схем и с взаимодействием между ними, приходится прибегать к массовой раздаче раздать привилегии, бездумно и как-то так
select 'GRANT EXECUTE ON '||owner||'.'||object_name||' TO TTX_EPP;'
from all_objects
where owner = 'NCI'
and object_type='FUNCTION';

select 'GRANT SELECT ON '||owner||'.'||object_name||' TO TTX_EPPW;'
from all_objects
where owner = 'TTX_EPP'
and object_type in ('TABLE', 'VIEW');

ORA-01652: unable to extend temp segment by 128 in tablespace TEMP

Достался старый сервер Oracle 9, с такой проблемой «ORA-01652: unable to extend temp segment by 128 in tablespace TEMP» Для изменения параметров табличного пространства пересоздал его, в момент пересоздания пользователей использующих его не должно быть, иначе получим «ORA-25152: TEMPFILE cannot be dropped at this time»
SELECT tablespace_name, file_name, bytes FROM dba_temp_files WHERE tablespace_name = 'TEMP';
ALTER DATABASE TEMPFILE '/u02/oradata/orcl/temp01.dbf' DROP INCLUDING DATAFILES;
ALTER TABLESPACE temp ADD TEMPFILE '/u02/oradata/orcl/temp01.dbf' SIZE 128m AUTOEXTEND ON NEXT 64m MAXSIZE UNLIMITED;
Можно было просто добавить второй файл к пространству.

Update multiple nodes in SQL XML

Изменить в XML значения в нескольких узлах не получится,
The target of 'replace' must be at most one node, found 'attribute(selectedSum,xdt:untypedAtomic) *'
Выкручиваемся так, в цикле для каждой строки
declare @iCount int;
set @iCount = ( select xmlData.value('count(//*)', 'int') from [Metrolog].[dbo].[m_PWStatus] where deleted is null and pfId=12 and statusId=2 );

declare @i int;
set @i = 1;

declare @repl varchar(30) = '2890659.320';

while (@i <= @iCount)
 begin
 update [Metrolog].[dbo].[m_PWStatus]
  set xmlData.modify('declare namespace ttt="urn:metrolog.fsk-ees.ru"; replace value of (/rows/ttt:row[sql:variable("@i")]/@selectedSum)[1] with sql:variable("@repl")') where deleted is null and pfId=12 and statusId=2;
  update [Metrolog].[dbo].[m_PWStatus]
  set xmlData.modify('declare namespace ttt="urn:metrolog.fsk-ees.ru"; replace value of (/rows/ttt:row[sql:variable("@i")]/@selectedCnt)[1] with "250"') where deleted is null and pfId=12 and statusId=2;
  set @i = @i + 1;
 end

Change the color of address bar in mobile Chrome for Android browser

Зададим цвет адресной строки для Chrome под Android на примере WordPress.
В файл схемы …./header.php в тег добавим <meta name="theme-color" content="#ff66ee"> и увидим такой результат Screenshot_2016-08-30-20-44-13_com.android.chrome

Век живи, век учись, вариант выделения дробной части

Задача, положить дробное число раздельно в два столбца, воспользуемся оператором взятия остатка от деления %, это Лёха подсказал
drop table #test17;

create table #test17(c1 int, c2 decimal(10,10) /*отдадим все 10 знаков на хранение дробной части*/);

insert into #test17
 select c,c from (select 12.34567 c) tt;
-- для MSSQL Arithmetic overflow error converting numeric to data type numeric.
-- The statement has been terminated.
-- или в MySQL Data truncation: Out of range value for column 'c2' at row 1

insert into #test17
 select c,c%1 from (select 12.34567 c) tt;

select * from #test17;

c1	c2
12	0.3456700000

для Оракла функция mod(c, d)

Select a particular option in a SELECT element in jQuery

Выбрать элемент списка с помощью jQuery, столько разных усложнений, а ведь на то она и библиотека, чтобы сделать код проще.
$("#selId").val‌​("val1").cha‌​nge();
-- или если с мультивыбором
$("#selId").val‌​(["val3", "val5"]).cha‌​nge();
а можно и всяко разно
$('#selId option[value="val1"]').‌​attr('selected', 'selected');
$('#selId option').filter(function(i, o) { return $(o).val() == "val1"})
по этому поводу часто идут холивары, но можно заглянуть в код jQuery и увидеть что присвоение значения списку установит свойство selected = true для элемента списка с равным значением.
jQuery.fn.extend({
	val: function( value ) {
		var hooks, ret, isFunction,
			elem = this[0];
......................
		return this.each(function( i ) {
			var val;

......................
			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		});
......................
jQuery.extend({
	valHooks: {
		option: {
			get: function( elem ) {
				var val = jQuery.find.attr( elem, "value" );
				return val != null ?
					val :
					// Support: IE10-11+
					// option.text throws exceptions (#14686, #14858)
					jQuery.trim( jQuery.text( elem ) );
			}
		},
		select: {
			get: function( elem ) {
				var value, option,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one" || index < 0,
					values = one ? null : [],
					max = one ? index + 1 : options.length,
					i = index < 0 ?
						max :
						one ? index : 0;

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// oldIE doesn't update selected after form reset (#2551)
					if ( ( option.selected || i === index ) &&
							// Don't return options that are disabled or in a disabled optgroup
							( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
							( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var optionSet, option,
					options = elem.options,
					values = jQuery.makeArray( value ),
					i = options.length;

				while ( i-- ) {
					option = options[ i ];

					if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {

						// Support: IE6
						// When new option element is added to select box we need to
						// force reflow of newly added node in order to workaround delay
						// of initialization properties
						try {
							option.selected = optionSet = true;

						} catch ( _ ) {

							// Will be executed only in IE6
							option.scrollHeight;
						}

					} else {
						option.selected = false;
					}
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}

				return options;
			}

......................

Difference between decodeURIComponent and decodeURI

Различия в decodeURI и decodeURIComponent, в последнем нет исключений он декодирует все символы.
tt1 = encodeURI(" ; / ? : @ & = + $ , # ")
"%20;%20/%20?%20:%20@%20&%20=%20+%20$%20,%20#%20"
tt2 = encodeURIComponent(" ; / ? : @ & = + $ , # ")
"%20%3B%20%2F%20%3F%20%3A%20%40%20%26%20%3D%20%2B%20%24%20%2C%20%23%20"
tt3 = decodeURI(tt1)
" ; / ? : @ & = + $ , # "
tt4 = decodeURI(tt2)
" %3B %2F %3F %3A %40 %26 %3D %2B %24 %2C %23 "
tt5 = decodeURIComponent(tt1)
" ; / ? : @ & = + $ , # "
tt6 = decodeURIComponent(tt2)
" ; / ? : @ & = + $ , # "
const jschar js_uriReservedPlusPound_ucstr[] =
    {';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '#', 0};

static JSBool
str_decodeURI(JSContext *cx, uintN argc, jsval *vp) {
    JSString *str;

    str = ArgToRootedString(cx, argc, vp, 0);
    if (!str)
        return JS_FALSE;
    return Decode(cx, str, js_uriReservedPlusPound_ucstr, vp);
}

static JSBool
str_decodeURI_Component(JSContext *cx, uintN argc, jsval *vp) {
    JSString *str;

    str = ArgToRootedString(cx, argc, vp, 0);
    if (!str)
        return JS_FALSE;
    return Decode(cx, str, js_empty_ucstr, vp);
}

Transforming XML data into a rowset using the nodes() method and Performance

Преобразуем XML данные из столбца таблицы в табличные используя метод xml nodes() и cross apply.
Пример, три варианта, в первых двух сгенерирована XML с 1000 узлов, в последнем 10000, первый и второй варианты отличаются представлением XML, значения в атрибутах или в тэгах. В третьем, главное отличие, XML сохраняется в переменную, и результат, производительность на несколько порядков выше.
Итог: 8 сек, 12 сек, и 125 мс, если хмл-ка маленькая 10-50 узлов можно и не использовать переменную, иначе придется, или использовать OpenXML.
Если запустить первый вариант с 10К, то будем ждать долго, минут 10 (не дождался прервал на 5), деградация в прогрессии.
with 
t as (
 select * from (values(1),(2),(3),(4),(5),(6),(7),(8),(9))t(gid)
), t2 as (
 select row_number() over (order by t.gid) r,t.* from t, t tt1, t tt2, t tt3, t tt4--, t tt5
), t_xml as (
 select cast((select top(1000) * from t2 for xml raw) as xml) xmlData -- всего 1000 нод
), t_from_xml as (
 select
  x.xCol.value('@r','int') id
   ,x.xCol.value('@gid','int') gid 
from  t_xml b
 cross apply b.xmlData.nodes('/row') as x(xCol)  
)
--select top(1000) * from t2
--select * from t_xml
select * from t_from_xml
with 
t as (
 select * from (values(1),(2),(3),(4),(5),(6),(7),(8),(9))t(gid)
), t2 as (
 select row_number() over (order by t.gid) r,t.* from t, t tt1, t tt2, t tt3, t tt4--, t tt5
), t_xml as (
 select cast((select top(1000) * from t2 for xml path('row')) as xml) xmlData -- всего 1000 нод
), t_from_xml as (
 select
  x.xCol.value('(r/text())[1]','int') id
   ,x.xCol.value('(gid/text())[1]','int') gid 
from  t_xml b
 cross apply b.xmlData.nodes('/row') as x(xCol)  
)
--select top(1000) * from t2
--select * from t_xml
select * from t_from_xml
DECLARE @data xml
with 
t as (
 select * from (values(1),(2),(3),(4),(5),(6),(7),(8),(9))t(gid)
), t2 as (
 select row_number() over (order by t.gid) r,t.* from t, t tt1, t tt2, t tt3, t tt4--, t tt5
), t_xml as (
 select cast((select top(10000) * from t2 for xml path('row')) as xml) xmlData -- всего 1000 нод
), t_from_xml as (
 select
  x.xCol.value('(r/text())[1]','int') id
   ,x.xCol.value('(gid/text())[1]','int') gid 
from  t_xml b
 cross apply b.xmlData.nodes('/row') as x(xCol)  
)
--select top(1000) * from t2
select @data = (select xmlData from t_xml)

select
 x.xCol.value('(r/text())[1]','int') id
  ,x.xCol.value('(gid/text())[1]','int') gid 
from  @data.nodes('/row') as x(xCol)  
sql xml

Update XML stored in a XML column in SQL Server

Изменяем XML в столбце с типом XML, в нашем случае изменяем атрибут и усложнение уровня с сохраненной XML содержится описание схемы, так что мы должны указать пространство имен, иначе получим сообщение что обновили одну строку, но реального обновления данных не будет.

update [MetrologDev].[dbo].[m_PWStatus]
 set xmlData.modify('replace value of (/rows/row[@id=("2686")]/@selectedCnt)[1] with "0"')
  output inserted.xmlData
   where deleted is null and pfId=12 and statusId=2

update [MetrologDev].[dbo].[m_PWStatus]
 set xmlData.modify('declare namespace ttt="urn:metrolog.mneti.ru"; replace value of (/rows/ttt:row[@id=("2686")]/@selectedCnt)[1] with "0"')
  where deleted is null and pfId=12 and statusId=2


Дружим postfix & courier-imap с Let’s Encrypt with auto update

1. Автоматизация letsencrypt.sh

/usr/local/etc/letsencrypt.sh/domains.txt список MX доменов, через пробел. /usr/local/etc/letsencrypt.sh/config.sh добавляем вызов внешнего скрипта:
HOOK=${BASEDIR}/hook.sh
Даем права на выполнения скрипта:
root# chmod 750 /usr/local/etc/letsencrypt.sh/hook.sh
Правим функцию deploy_cert в файле /usr/local/etc/letsencrypt.sh/hook.sh:
function deploy_cert {
 local DOMAIN="${1}" KEYFILE="${2}" CERTFILE="${3}" FULLCHAINFILE="${4}" CHAINFILE="${5}" TIMESTAMP="${6}"

 TLS_DHPARAMS="/usr/local/etc/letsencrypt.sh/dhparams.pem"
 if test ! -f $TLS_DHPARAMS
 then
 /usr/bin/openssl dhparam -outform PEM 4096 > "$TLS_DHPARAMS"
 fi

 cat "${FULLCHAINFILE}" "${KEYFILE}" "$TLS_DHPARAMS" > "/usr/local/etc/letsencrypt.sh/certs/${DOMAIN}/combined.pem"
}
Обновляемся:
root# /usr/local/bin/letsencrypt.sh -c
2. Настройка courier-imap Правим конфигурационные фалы связанные с ssl:
/usr/local/etc/courier-imap/imapd-ssl
/usr/local/etc/courier-imap/pop3d-ssl
TLS_CERTFILE=/usr/local/etc/letsencrypt.sh/certs/mx/combined.pem
TLS_DHPARAMS=/usr/local/etc/letsencrypt.sh/dhparams.pem
3. Настройка postfix Правим конфигурационный файл:
/usr/local/etc/postfix/main.cf
smtpd_tls_cert_file= /usr/local/etc/letsencrypt.sh/certs/mx/cert.pem
smtpd_tls_key_file= /usr/local/etc/letsencrypt.sh/certs/mx/privkey.pem
4. Перегружаем демоны
root# /usr/local/etc/rc.d/courier-imap-imapd-ssl restart
root# /usr/local/etc/rc.d/courier-imap-pop3d-ssl restart
root# /usr/local/etc/rc.d/postfix restart