Идея |
|
Метки: бизнес идея |
Корректное отображение русских шрифтов в командной строке Windows |
|
|
Использование putty и ssh ключей в Windows |
|
Метки: Использование putty и ssh ключей в Windows |
djvu на iPad |
|
Метки: djvu на iPad |
java random |
int randomNumber = Math.abs( random.nextInt() % UPPER_LIMIT );
|
Метки: java random |
Рабочие примеры реализации алгоритмов - AES, DES, RSA : Bouncy Castle (cryptography) |
import java.io.*;
import java.math.*;
import java.security.*;
import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.params.*;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.crypto.encodings.*;
import org.bouncycastle.crypto.generators.*;
import org.bouncycastle.crypto.modes.*;
import org.bouncycastle.crypto.paddings.*;
import org.bouncycastle.crypto.digests.*;
import org.bouncycastle.crypto.signers.*;
public class CryptoEngine {
private byte [] AESkey;
private byte [] AESinitV;
private byte [] salt;
private RSAKeyParameters RSAprivKey;
private RSAKeyParameters RSApubKey;
public CryptoEngine () {
try {
Class c = this.getClass();
InputStream is;
is = c.getResourceAsStream("/keys/AESkey.dat");
AESkey = readFromStream(is);
is.close();
is = c.getResourceAsStream("/keys/AESinitV.dat");
AESinitV = readFromStream(is);
is.close();
SecureRandom sr = new SecureRandom();
salt = new byte [16];
sr.nextBytes(salt);
is = c.getResourceAsStream("/keys/RSAmod.dat");
BigInteger RSAmod = new BigInteger(readFromStream(is));
is.close();
is = c.getResourceAsStream("/keys/RSAprivExp.dat");
BigInteger RSAprivExp = new BigInteger(readFromStream(is));
is.close();
is = c.getResourceAsStream("/keys/RSApubExp.dat");
BigInteger RSApubExp = new BigInteger(readFromStream(is));
is.close();
is = c.getResourceAsStream("/keys/RSAdp.dat");
BigInteger RSAdp = new BigInteger(readFromStream(is));
is.close();
is = c.getResourceAsStream("/keys/RSAdq.dat");
BigInteger RSAdq = new BigInteger(readFromStream(is));
is.close();
is = c.getResourceAsStream("/keys/RSAp.dat");
BigInteger RSAp = new BigInteger(readFromStream(is));
is.close();
is = c.getResourceAsStream("/keys/RSAq.dat");
BigInteger RSAq = new BigInteger(readFromStream(is));
is.close();
is = c.getResourceAsStream("/keys/RSAqInv.dat");
BigInteger RSAqInv = new BigInteger(readFromStream(is));
is.close();
RSAprivKey = new RSAPrivateCrtKeyParameters(RSAmod, RSApubExp,
RSAprivExp, RSAp, RSAq, RSAdp, RSAdq, RSAqInv);
RSApubKey = new RSAKeyParameters(false, RSAmod, RSApubExp);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
public void generateAESKey () throws Exception {
SecureRandom sr = new SecureRandom();
AESkey = new byte [16];
sr.nextBytes(AESkey);
AESinitV = new byte [16];
sr.nextBytes(AESinitV);
}
public void generateRSAKeyPair () throws Exception {
SecureRandom sr = new SecureRandom();
BigInteger pubExp = new BigInteger("10001", 16);
RSAKeyGenerationParameters RSAKeyGenPara =
new RSAKeyGenerationParameters(pubExp, sr, 1024, 80);
RSAKeyPairGenerator RSAKeyPairGen = new RSAKeyPairGenerator();
RSAKeyPairGen.init(RSAKeyGenPara);
AsymmetricCipherKeyPair keyPair = RSAKeyPairGen.generateKeyPair();
RSAprivKey = (RSAPrivateCrtKeyParameters) keyPair.getPrivate();
RSApubKey = (RSAKeyParameters) keyPair.getPublic();
}
public byte [] AESLiteEncrypt (byte [] toEncrypt) throws Exception {
BufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESLightEngine()));
// If initV is not given, the program will assume all zeros
ParametersWithIV piv = new ParametersWithIV (
(new KeyParameter(AESkey)), AESinitV);
cipher.init(true, piv);
byte[] result = new byte[cipher.getOutputSize(toEncrypt.length)];
int len = cipher.processBytes(toEncrypt, 0, toEncrypt.length, result, 0);
try {
cipher.doFinal(result, len);
} catch (CryptoException ce) {
result = (new String("Cipher error")).getBytes();
ce.printStackTrace();
}
return result;
}
public byte [] AESLiteDecrypt (byte [] toDecrypt) throws Exception {
BufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESLightEngine()));
ParametersWithIV piv = new ParametersWithIV (
(new KeyParameter(AESkey)), AESinitV);
cipher.init(false, piv);
byte[] result = new byte[cipher.getOutputSize(toDecrypt.length)];
int len = cipher.processBytes(toDecrypt, 0, toDecrypt.length, result, 0);
try {
cipher.doFinal(result, len);
} catch (CryptoException ce) {
result = (new String("Cipher error")).getBytes();
ce.printStackTrace();
}
return result;
}
public byte [] AESFastEncrypt (byte [] toEncrypt) throws Exception {
BufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESFastEngine()));
// If initV is not given, the program will assume all zeros
ParametersWithIV piv = new ParametersWithIV (
(new KeyParameter(AESkey)), AESinitV);
cipher.init(true, piv);
byte[] result = new byte[cipher.getOutputSize(toEncrypt.length)];
int len = cipher.processBytes(toEncrypt, 0, toEncrypt.length, result, 0);
try {
cipher.doFinal(result, len);
} catch (CryptoException ce) {
result = (new String("Cipher error")).getBytes();
ce.printStackTrace();
}
return result;
}
public byte [] AESFastDecrypt (byte [] toDecrypt) throws Exception {
BufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESFastEngine()));
ParametersWithIV piv = new ParametersWithIV (
(new KeyParameter(AESkey)), AESinitV);
cipher.init(false, piv);
byte[] result = new byte[cipher.getOutputSize(toDecrypt.length)];
int len = cipher.processBytes(toDecrypt, 0, toDecrypt.length, result, 0);
try {
cipher.doFinal(result, len);
} catch (CryptoException ce) {
result = (new String("Cipher error")).getBytes();
ce.printStackTrace();
}
return result;
}
// Get use password to generate symmetric key with (or without IV)
// To be used in an AES underlying cipher
private CipherParameters getAESPasswdKey (char [] passwd) throws Exception {
PBEParametersGenerator generator =
new PKCS12ParametersGenerator(new SHA1Digest());
generator.init(
PBEParametersGenerator.PKCS12PasswordToBytes(passwd),
salt, 1024);
// Generate a 128 bit key w/ 128 bit IV
ParametersWithIV key =
(ParametersWithIV)generator.generateDerivedParameters(128, 128);
// Generate a 128 kit key
// CipherParameters key = generator.generateDerivedParameters(128);
return key;
}
// Password based encryption using AES
public byte [] AESPasswdEncrypt (byte [] toEncrypt, char [] passwd)
throws Exception {
ParametersWithIV key = (ParametersWithIV) getAESPasswdKey(passwd);
// The following code uses an AES cipher to
// encrypt the message
BufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESFastEngine()));
cipher.init(true, key);
byte[] result = new byte[cipher.getOutputSize(toEncrypt.length)];
int len = cipher.processBytes(toEncrypt, 0, toEncrypt.length, result, 0);
try {
cipher.doFinal(result, len);
} catch (CryptoException ce) {
result = (new String("Cipher error")).getBytes();
ce.printStackTrace();
}
return result;
}
// Password based decryption using AES
public byte [] AESPasswdDecrypt (byte [] toDecrypt, char [] passwd)
throws Exception {
ParametersWithIV key = (ParametersWithIV) getAESPasswdKey(passwd);
// The following code uses an AES cipher to
// decrypt the message
BufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESFastEngine()));
cipher.init(false, key);
byte[] result = new byte[cipher.getOutputSize(toDecrypt.length)];
int len = cipher.processBytes(toDecrypt, 0, toDecrypt.length, result, 0);
try {
cipher.doFinal(result, len);
} catch (CryptoException ce) {
result = (new String("Cipher error")).getBytes();
ce.printStackTrace();
}
return result;
}
// Get use password to generate a triple DES symmetric key
private DESedeParameters getDESedePasswdKey (char [] passwd)
throws Exception {
PBEParametersGenerator generator =
new PKCS12ParametersGenerator(new SHA1Digest());
generator.init(
PBEParametersGenerator.PKCS12PasswordToBytes(passwd),
salt, 1);
KeyParameter rawKey =
(KeyParameter) generator.generateDerivedParameters(128);
byte [] keyBytes = rawKey.getKey();
DESedeParameters.setOddParity(keyBytes);
DESedeParameters key = new DESedeParameters(keyBytes);
return key;
}
// Password based encryption using DESede
public byte [] DESedePasswdEncrypt (byte [] toEncrypt, char [] passwd)
throws Exception {
DESedeParameters key = (DESedeParameters) getDESedePasswdKey(passwd);
BufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(
new CBCBlockCipher(new DESedeEngine()));
cipher.init(true, key);
byte[] result = new byte[cipher.getOutputSize(toEncrypt.length)];
int len = cipher.processBytes(toEncrypt, 0, toEncrypt.length, result, 0);
try {
cipher.doFinal(result, len);
} catch (CryptoException ce) {
result = (new String("Cipher error")).getBytes();
ce.printStackTrace();
}
return result;
}
// Password based decryption using DESede
public byte [] DESedePasswdDecrypt (byte [] toDecrypt, char [] passwd)
throws Exception {
DESedeParameters key = (DESedeParameters) getDESedePasswdKey(passwd);
BufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(
new CBCBlockCipher(new DESedeEngine()));
cipher.init(false, key);
byte[] result = new byte[cipher.getOutputSize(toDecrypt.length)];
int len = cipher.processBytes(toDecrypt, 0, toDecrypt.length, result, 0);
try {
cipher.doFinal(result, len);
} catch (CryptoException ce) {
result = (new String("Cipher error")).getBytes();
ce.printStackTrace();
}
return result;
}
// Public key encrypt using RSA
public byte [] RSAEncrypt (byte [] toEncrypt) throws Exception {
if (RSApubKey == null)
throw new Exception("Generate RSA keys first!");
AsymmetricBlockCipher eng = new RSAEngine();
eng = new PKCS1Encoding(eng);
eng.init(true, RSApubKey);
return eng.processBlock(toEncrypt, 0, toEncrypt.length);
}
// private key decrypt
public byte [] RSADecrypt (byte [] toDecrypt) throws Exception {
if (RSAprivKey == null)
throw new Exception("Generate RSA keys first!");
AsymmetricBlockCipher eng = new RSAEngine();
eng = new PKCS1Encoding(eng);
eng.init(false, RSAprivKey);
return eng.processBlock(toDecrypt, 0, toDecrypt.length);
}
// RSA signature
public byte [] RSASign (byte [] toSign) throws Exception {
if (RSAprivKey == null)
throw new Exception("Generate RSA keys first!");
SHA1Digest dig = new SHA1Digest();
RSAEngine eng = new RSAEngine();
PSSSigner signer = new PSSSigner(eng, dig, 64);
signer.init(true, RSAprivKey);
signer.update(toSign, 0, toSign.length);
return signer.generateSignature();
}
// RSA signature verification
public boolean RSAVerify (byte [] mesg, byte [] sig) throws Exception {
if (RSApubKey == null)
throw new Exception("Generate RSA keys first!");
SHA1Digest dig = new SHA1Digest();
RSAEngine eng = new RSAEngine();
PSSSigner signer = new PSSSigner(eng, dig, 64);
signer.init(false, RSApubKey);
signer.update(mesg, 0, mesg.length);
return signer.verifySignature(sig);
}
private byte [] readFromStream (InputStream is) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] b = new byte[1];
while ( is.read(b) != -1 ) {
baos.write(b);
}
byte[] result = baos.toByteArray();
baos.close();
return result;
}
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: Рабочие примеры реализации алгоритмов - AES DES RSA : Bouncy Castle (cryptography) |
Ehcache в качестве RESTful сервера кеширования и PHP |
|
|
Integrating Java with C++ |
|
Метки: Integrating Java with C++ |
PostgreSQL оптимизация |
|
Метки: PostgreSQL |
PostgreSQL в веб-приложениях |
|
Метки: PostgreSQL в веб-приложениях |
Tomcat clustering |
Эта заметка посвящена тому, как развернуть кластер из Tomcat серверов и настроить простую балансировку нагрузки для кластера.
Начнем сначала. Зачем нужен кластер? Обычным приложениям, которые обслуживают относительно небольшой поток пользователей и к которым не предъявляются серьезные требования со стороны бизнеса, кластер, возможно и не пригодится.
Совсем по-другому обстоят дела с теми приложениями, которые являются ключевыми для функционирования бизнеса, к примеру, приложения которые обрабатывают биллинговые операции. Если “ляжет” сервис такого рода, то некоторый бизнес-процесс, тоже перестанет функционировать.
Назначение кластера: повысить общую устойчивость и масштабируемость системы. Устойчивость системы повышается за счет того, что запросы пользователей обрабатываются не одним сервером, а сразу несколькими. Поэтому в случае сбоя одного из серверов, или при необходимости перезагрузки, сервис будет продолжать нормально функционировать.
Что касается масштабируемости: увеличить производительность системы можно за счет расширения кластера. То есть, если два сервера не справляются с задачей, то довольно просто поставить третий, подключить его к кластеру и увеличить производительность системы на 50%. Надо заметить, что расширять кластер таким образом бесконечно нельзя, есть некоторые сдерживающие факторы: к примеру, объем трафика, который необходим для передачи данных сессий между нодами кластера. Об этом чуть позже.
В этой заметке приведен рецепт развертывания кластера из нескольких Tomcat серверов на одной рабочей станции. Необходимые компоненты: дистрибутив Tomcat 5.0.28 (можно 5.5.xx – процесс ничем не отличается), Apache HTTP server 2.0.59 + mod_jk.
Шаг 1. Разворачиваем первый Tomcat.
Выберите директорию для установки Tomcat серверов кластера. Разархивируйте первый дистрибутив. Запустите сервер и убедитесь, что все работает. Теперь у нас есть установленный Tomcat, на котором уже запущено несколько приложений. Работу кластера мы будем тестировать на примере приложения jsp-examples из дистрибутива.
Шаг второй. Настроим Apache HTTP + mod_jk.
Первый вопрос, который возникает на этом шаге: зачем _одному_ Tomcat’у (ведь кластера еще нет) нужен еще и Apache, если Tomcat и сам неплохо справляется с обработкой HTTP запросов? Ответ, который предоставляют разработчики, довольно неожиданный: Tomcat действительно неплохо работает с HTTP запросами, но в реальном мире, где на сервер сыплются тонны некорректных запросов и оборванных соединений – Apache справляется куда лучше. Второй нюанс: Tomcat все же написан на Java. Цена кроссплатформенности Java – это невозможность оптимизировать код под конкретную платформу. И снова-таки Apache лишен этого недостатка.
Таким образом в нашей архитектуре Apache HTTP server будет выступать в качестве “фильта” между пользователями и Tomcat серверами. На следующих шагах Apache будет выполнять еще и функцию распределителя нагрузки.
1. Установите Apache.
2. Запустите Apache и убедитесь что он работает: зайдите на http://localhost – там должна быть стартовая страничка Apache.
3. Скачайте mod_jk необходимой версии, переименуйте файл в mod_jk.so и поместите его в папку modules.
4. В файл httpd.conf добавляем такие строки:
LoadModule jk_module modules/mod_jk.so
# Path to workers.properties
JkWorkersFile conf/workers.properties
# Path to jk logs
JkLogFile logs/mod_jk.log
# Jk log level [debug/error/info]
JkLogLevel info
# Jk log format
JkLogStampFormat \"[%a %b %d %H:%M:%S %Y] \"
# JkOptions for forwarding
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
# JkRequestLogFormat set the request format
JkRequestLogFormat \"%w %V %T\"
JkMount /jsp-examples alpha
JkMount /jsp-examples/* alpha
5. В папке conf создаем файл workers.properties. Содержимое этого файла будет таким:
workers.tomcat_home=C:/apps/cluster/alpha
workers.java_home=C:/apps/jdk1.5.0_11
worker.list=alpha
worker.alpha.port=8009
worker.alpha.host=localhost
worker.alpha.type=ajp13
Естественно, вместо указанных путей укажите собственные.
Теперь поправим конфигурацию Tomcat:
6. Убедимся, что AJP коннектор настроен именно так:
\"8009\"
enableLookups=\"false\" redirectPort=\"8443\" debug=\"0\"
protocol=\"AJP/1.3\" />
7. Перезагружаем Tomcat и Apache. Убедимся, что все работает так как надо:
Если в браузере набрать http://localhost/jsp-examples/ - должна отобразиться страница с примерами jsp из дистрибутива Tomcat. Если страничка есть - значит все работает.
Поздравляю, теперь обработкой HTTP запросов занимается Apache.
Шаг третий. Добавим в кластер еще один сервер и настроим балансировку нагрузки.
1. Разархивируем еще один дистрибутив Tomcat.
2. В server.xml поправим конфигурацию так, чтобы не было конфликтов портов:
\"8006\" shutdown=\"SHUTDOWN\" debug=\"0\">
...
\"8081\"
maxThreads=\"150\" minSpareThreads=\"25\" maxSpareThreads=\"75\"
enableLookups=\"false\" redirectPort=\"8443\" acceptCount=\"100\"
debug=\"0\" connectionTimeout=\"20000\"
disableUploadTimeout=\"true\" />
...
\"8010\"
enableLookups=\"false\" redirectPort=\"8443\" debug=\"0\"
protocol=\"AJP/1.3\" />
...
3. Поправим workers.properties, чтобы нагрузка баллансировалась между двумя нодами:
workers.tomcat_home=C:/apps/cluster/alpha
workers.java_home=C:/apps/jdk1.5.0_11
worker.list=balancer
worker.alpha.port=8009
worker.alpha.host=localhost
worker.alpha.type=ajp13
worker.alpha.lbfactor=1
worker.bravo.port=8010
worker.bravo.host=localhost
worker.bravo.type=ajp13
worker.bravo.lbfactor=1
worker.balancer.type=lb
worker.balancer.balance_workers=alpha,bravo
4. Поправим httpd.conf:
JkMount /jsp-examples balancer
JkMount /jsp-examples/* balancer
5. Чтобы понимать, на какую ноду мы попали, поправим файлы webapps\\jsp-examples\\index.html в обеих нодах. В первой ноде добавим строку \"Alpha\", а во второй \"Bravo\". Теперь будет видно, какой из серверов в действительно обрабатывает запрос.
5. Запустим только что установленный Tomcat (теперь работает две ноды).
6. Перезапустим Apache.
7. Набираем в браузере http://localhost/jsp-examples/
8. Смотрим, какая нода обрабатывает наш запрос и останавливаем соответствующий Tomcat.
9. Обновляем страницу в браузере - теперь запрос обрабатывает другая нода (и никаких 404 :-))
Только что мы проимитировали ситуацию, когда одна из нод кластера перестала функционировать. Как видно - переключение на работающую ноду прошло абсолютно прозрачно для пользователя (если бы не надписи \"Alpha\" и \"Bravo\" пользователь даже не узнал-бы о переключении).
Шаг четвертый. Настаиваем репликацию сессий.
При существующей архитектуре, данные сессии пользователя при крахе ноды будут утеряны. Это далеко не всегда допустимо. На этом шаге мы настроим репликацию сессий: Tomcat ноды будут обмениваться данными о сессиях. Таким образом, если одна из нод упадет - копии сессии останутся на остальных нодах и пользователь сможет продолжить нормально работать.
На данном этапе элементы кластера не знают о существовании друг-друга. Фактически, все что надо сделать для репликации сессий это \"познакомить\" их.
К сожалению, в комплекте примеров jsp нет страниц, которые демонстрируют использование сессий. Поэтому прийдется немного повозиться, чтобы получить возможность проверить репликацию.
Создадим страничку session.jsp с таким содержанием:
\"Content-Type\" content=\"text/html; charset=windows-1251\">
Для ноды bravo создадим точно такую же страницу, только вместо alpha будем устанавливать строку \"bravo\".
1. Убедимся, что сейчас репликация сессий не работает:
1.1. Зайдем на http://localhost/jsp-examples/session.jsp, заметим, какая нода обработала запрос.
1.2. Остановим соответствующую ноду.
1.3. Обновим в браузере страницу: как видно, вторая нода понятия не имеет о том, какие объекты добавляла в сессию первая нода.
1.4. Остановим обе ноды.
Теперь, собственно, репликация.
1. В server.xml для ноды alpha прописываем
\"Catalina\" defaultHost=\"localhost\" debug=\"0\" jvmRoute=\"alpha\">
2. В server.xml для ноды bravo прописываем
\"Catalina\" defaultHost=\"localhost\" debug=\"0\" jvmRoute=\"bravo\">
2. Раскомментируем блок Cluster нод alpha и bravo
3. В блоке Cluster ноды alpha устанавливаем
\"org.apache.catalina.cluster.mcast.McastService\"
mcastAddr=\"228.0.0.4\"
mcastBindAddress=\"127.0.0.1\"
mcastPort=\"45564\"
mcastFrequency=\"500\"
mcastDropTime=\"3000\"/>
\"org.apache.catalina.cluster.tcp.ReplicationListener\"
tcpListenAddress=\"auto\"
tcpListenPort=\"4001\"
tcpSelectorTimeout=\"100\"
tcpThreadCount=\"6\"/>
4. Аналогично для bravo
\"org.apache.catalina.cluster.mcast.McastService\"
mcastAddr=\"228.0.0.4\"
mcastBindAddress=\"127.0.0.1\"
mcastPort=\"45564\"
mcastFrequency=\"500\"
mcastDropTime=\"3000\"/>
\"org.apache.catalina.cluster.tcp.ReplicationListener\"
tcpListenAddress=\"auto\"
tcpListenPort=\"4002\"
tcpSelectorTimeout=\"100\"
tcpThreadCount=\"6\"/>
5. В web.xml приложения jsp-examples обеих нод добавляем параметр :
\"http://java.sun.com/xml/ns/j2ee\"
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\"
version=\"2.4\">
JSP 2.0 Examples.
...
...
5. Повторяем тест на репликацию описанный выше. Теперь, при переходе между нодами, данные из сессии пользователя не будут утеряны.
Заключение.
В этой заметке описан способ настройки кластера Tomcat серверов. Мы использовали HTTP сервер Apache для обработки HTTP запросов и для баллансировки нагрузки между серверами.
Для того чтобы добавить в кластер новую ноду необходимо сделать следующее:
1. Разархивировать дистрибутив tomcat.
2. В server.xml указать
\"xxxx\" shutdown=\"SHUTDOWN\" debug=\"0\">
тут xxxx - значение порта, которое не будет конфликтовать с другими портами кластера
3. Поправляем http коннектор
\"xxxx\"
maxThreads=\"150\" minSpareThreads=\"25\" maxSpareThreads=\"75\"
enableLookups=\"false\" redirectPort=\"8443\" acceptCount=\"100\"
debug=\"0\" connectionTimeout=\"20000\"
disableUploadTimeout=\"true\" />
тут xxxx - значение порта, которое не будет конфликтовать с другими портами кластера
4. Указать параметры AJP коннектора:
\"yyyy\"
enableLookups=\"false\" redirectPort=\"8443\" debug=\"0\"
protocol=\"AJP/1.3\" />
yyyy - аналогично
5. Указать значение jvmRoute для Catalina
\"Catalina\" defaultHost=\"localhost\" debug=\"0\" jvmRoute=\"myNextNode\">
значение jvmRoute должно быть уникальным для каждой ноды кластера.
6. Раскомментировать блок Cluster и в нем настроить
\"org.apache.catalina.cluster.mcast.McastService\"
mcastAddr=\"228.0.0.4\"
mcastBindAddress=\"127.0.0.1\"
mcastPort=\"45564\"
mcastFrequency=\"500\"
mcastDropTime=\"3000\"/>
\"org.apache.catalina.cluster.tcp.ReplicationListener\"
tcpListenAddress=\"auto\"
tcpListenPort=\"zzzz\"
tcpSelectorTimeout=\"100\"
tcpThreadCount=\"6\"/>
zzzz - аналогично предыдущим.
В workers.properties добавить описание worker'a для новой ноды
worker.myNextNode.port=yyyy
worker.myNextNode.host=localhost
worker.myNextNode.type=ajp13
worker.myNextNode.lbfactor=1
...
worker.balancer.balance_workers=alpha,bravo,myNextNode
В результате мы получили кластер с баллансировщиком нагрузки, который относительно легко расширяется и который умеет передавать данные сессий между нодами.
Лично мне не удалость настроить для кластера Tomcat серверов Deployment Farm - замечательная возможность кластера, которая позволяет поставлять обновленное приложение одновременно на весь кластер.
Второй нюанс - кластером нельзя управлять динамически: поменяв workers.properties необходимо перезагрузить Apache.
А в остальном - довольно неплохо. Счастливой кластеризации.
* This source code was highlighted with Source Code Highlighter.
|
Метки: Tomcat clustering |
md5() + соль. Хранение паролей в базе данных |
// $user – информация о пользователе из таблицы user
if (md5(md5($_POST['password']).$user['salt']) == $user['password']) {
// проверка прошла успешно. логиним!
}
function generateSalt() {
$salt = '';
$length = rand(5,10); // длина соли (от 5 до 10 сомволов)
for($i=0; $i<$length; $i++) {
$salt .= chr(rand(33,126)); // символ из ASCII-table
}
return $salt;
}
|
Метки: md5() + соль. Хранение паролей в базе данных |
ИНСТАЛЯЦИЯ GLASSFISH 3.0.1 НА УБУНТУ |
|
Метки: ИНСТАЛЯЦИЯ GLASSFISH 3.0.1 НА УБУНТУ |
Как развернуть сайт на весь экран |
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style type="text/css">
body
{
background: #fff;
color: #000;
}
</style>
</header>
<body>
<h2>Hello World!</h2>
<a href="#">Развернуть страницу</a>
<script type="text/javascript">
$('a').click(function () {
var element = document.body;
var req = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen;
if(req){
console.log(req);
req.call(element);
}
else
{
var wscript = new ActiveXObject("Wscript.shell");
wscript.SendKeys("{F11}");
}
return false;
});
</script>
</body>
</html>
* This source code was highlighted with Source Code Highlighter.
|
Метки: Как развернуть сайт на весь экран |
javascript date time format |
Date.parse('10:30 PM EST') // Wed Oct 31 2007 20:30:00
Date.parse('10PM') // Wed Oct 31 2007 22:00:00
* This source code was highlighted with Source Code Highlighter.|
Метки: javascript date time format |
Class IOUtils |
|
Метки: Class IOUtils |
jquery UML |
$(".UmlTableRow").eq(0).children().each(function(index,elem){console.log($(elem).first().children().attr("src"))})
* This source code was highlighted with Source Code Highlighter.<table class="UmlTable" border="0" cellspacing="0" cellpadding="0">
<tbody><tr class="UmlTableRow">
<td class="UmlTableCell"><img src="overview0W0H0.png" width="502" height="516" usemap="#umlmap155W0H0" border="0"></td>
<td class="UmlTableCell"><img src="overview0W1H0.png" width="502" height="516" usemap="#umlmap155W1H0" border="0"></td>
<td class="UmlTableCell"><img src="overview0W2H0.png" width="501" height="516" usemap="#umlmap155W2H0" border="0"></td>
<td class="UmlTableCell"><img src="overview0W3H0.png" width="501" height="516" usemap="#umlmap155W3H0" border="0"></td>
</tr>
</tbody></table>
* This source code was highlighted with Source Code Highlighter.
|
Метки: jquery UML |
utf-8 to cp866 |
char[] chars = {'Z', 'Я', 'œ'};
Charset cp866 = Charset.forName("Cp866");
CharsetEncoder cp866Encoder = cp866.newEncoder();
for (char c : chars) {
logger.info("{} {}",
c,
cp866Encoder.canEncode(c) ? "supported" : "not supported");
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: utf8 to cp866 |
Distributed MVC Application model |
|
Метки: Distributed MVC Application model |
Fixing SQLDeveloper MSVCR71.DLL Not Found Error |
|
Метки: Fixing SQLDeveloper MSVCR71.DLL Not Found Error |
Java Interceptors (в EJB 3.0) |
public class SimpleLogger{
@AroundInvoke
public Object addLog(InvocationContext context){
//какая-то логика логирования
return context.proceed();
}
public class Summ {
@Interceptors (SimpleLogger.class)
public double getResult(){
//логика
}
}
public interface InvocationContext {
public Object getTarget();
public Method getMethod();
public Object
public void setParametrs(Object
public java.util.Map<String,Object> getContextData();
public Object proceed();
}
public class SimpleLogger{
@PostConstruct
public void init(InvocationContext context){
//логирование создания объекта, например через context.getTarget()
context.proceed():
}
@PreDestroy
public void remove(InvocationContext context){
//какая-то логика
context.proceed():
}
}
<interceptor-binding>
<ejb-name>*<ejb-name>
<interceptor-class> ru.interceptortest.Validate</interceptor-class>
</interceptor-binding>
public class SimpleLogger {
@AroundInvoke
public Object logAction(InvocationContext context) throws Exception {
System.out.println("object - " + context.getTarget().getClass());
System.out.println( "method - " + context.getMethod());
return context.proceed();
}
}
@Stateless
public class Count implements Serializable{
double firstArgument=0;
double secondArgument=0;
//геттеры и сеттеры и тд
@Interceptors(SimpleLogger.class)
public double getSummResult() {
return getFirstArgument()+ getSecondArgument();
}
}
public class LifeLogger {
@AroundInvoke
public Object logAll(InvocationContext context) throws Exception {
System.out.println("LogAll object - " + context.getTarget());
System.out.println("LogAll method - " + context.getMethod());
return context.proceed();
}
@PostConstruct
public Object logCreate(InvocationContext context) throws Exception {
System.out.println("create - " + context.getTarget().getClass().getClass);
return context.proceed();
}
}
* This source code was highlighted with Source Code Highlighter.|
Метки: Java Interceptors (в EJB 3.0) |
mysql rownum |
SELECT @rownum:=@rownum+1 rank, p.id , p.message_text FROM MESSAGE p, (SELECT @rownum:=0) r ORDER BY create_date DESC LIMIT 10;
* This source code was highlighted with Source Code Highlighter.
|
Метки: mysql rownum |
java call pl sql |
Calling PL/SQL from Java
Java Database Connectivity (JDBC) and SQLJ enable you to call PL/SQL stored functions and procedures. For example, you want to call the following stored function, which returns the balance of a specified bank account:
FUNCTION balance (acct_id NUMBER) RETURN NUMBER IS
acct_bal NUMBER;
BEGIN
SELECT bal INTO acct_bal FROM accts
WHERE acct_no = acct_id;
RETURN acct_bal;
END;
In a JDBC program, a call to the balance function can be written as follows:
...
CallableStatement cstmt = conn.prepareCall("{? = CALL balance(?)}");
cstmt.registerOutParameter(1, Types.FLOAT);
cstmt.setInt(2, acctNo);
cstmt.executeUpdate();
float acctBal = cstmt.getFloat(1);
...
In a SQLJ program, the call can be written as follows:
...
#sql acctBal = {VALUES(balance(:IN acctNo))};
...
* This source code was highlighted with Source Code Highlighter.
|
Метки: java call pl sql |
Java запись в две связанные таблицы |
...
try {
con.setAutoCommit(false);
PreparedStatement stmt= null;
...
// вставка в первую таблицу
...
// получили id вставленной записи
...
// вставка во ворую таблицу
//таблица с автоинкрементом по id
...
} catch (SQLException e ) {
if (con != null) {
System.err.print("Transaction is being rolled back");
con.rollback();
}
} finally {
if (stmt!= null) {
stmt.close();
}
con.setAutoCommit(true);
}
...
если записей которые нужно вставить в таблицу B
1000 или больше - как организовать их вставку - отдельными командами insert -
после каждой делать
statement.addBatch();
после каждой 100 делать
statement.executeBatch();
// вставка в первую таблицу
connection = database.getConnection();
connection.setAutoCommit(false);
PreparedStatement stmt = null;
ResultSet rs = null;
//таблица с автоинкрементом по id
stmt = con.prepareStatement("INSERT INTO tableA (message_text) VALUES (?)");
stmt.setString(1, msg);
stmt.execute();
int autoIncKeyFromFunc = -1;
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
// получили id вставленной записи
if (rs.next()) {
autoIncKeyFromFunc = rs.getInt(1);
}
// вставка во ворую таблицу
//таблица с автоинкрементом по id
List<Integer> usersId = new ArrayList<Ineger>();
usersId.add(1);
usersId.add(2);
usersId.add(3);
PreparedStatement updateTotal = connection.prepareStatement("insert into B (id_a, id_t) values (? ,?) ");
for(List userId :usersId ){
updateTotal .setInt(1, autoIncKeyFromFunc);
updateTotal .setInt(2, usersId.get(i));
//stmt.execute();
updateTotal .addBatch();
updateTotal .executeBatch();
}
updateTotal.execute();
con.commit();
* This source code was highlighted with Source Code Highlighter.
|
Метки: Java запись в две связанные таблицы |
ubuntu netbeans look and feel + font |
|
Метки: ubuntu netbeans lookandfeel font |
боремся с тем что натворил троян |
|
Метки: троян как вернуть папки |
java compiler |
public class TestClass{
public void ptest(){
System.out.println("It works! "+this.toString());
}
}
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
class SomeLoader extends ClassLoader{
/*
* зараза нихатит создавать объекты класса ClassLoader,
* т.к. у того нет публик конструкторов
* поэтому будем создавать объекты этого класса
*/
}
public class Test{
public static void main(String[]args){
//это список файлов для компиляции
ArrayList<String> files1 = new ArrayList<String>();
files1.add("TestClass.java");
//получаем стандартный JIT компилятор и файловый менеджер
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
//получаем список чего-то, наследующего JavaFileObject
//список можно получать как из коллекции имен файлов, так и собстно файлов
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromStrings(files1);
//получили задачу для компилятора и запустили его на выполнение
//в итоге в текущем каталоге будет создан TestClass.class
compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
try {
fileManager.close();
ClassLoader l = new SomeLoader();
Class<?> clazz = l.loadClass("TestClass");
//следующие две строки задают массив параметров (в нашем случае пустых)
Class<?> cl[]=null;
Object ob[]=null;
Method ptest = clazz.getMethod("ptest", cl);
Object o = clazz.newInstance();
//ну и соссно вызываем метод, определенный в нашем классе
ptest.invoke(o, ob);
}catch(IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
* This source code was highlighted with Source Code Highlighter.
|
|
NetBeans 7.0 and 7.1 UML plugin |
|
Метки: NetBeans 7.0 and 7.1 UML plugin |
Идея |
|
Метки: бизнес идея |
Подсчет количества уникальных в массиве |
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
public class CountRepeatingElements {
public static CountRepeatingElements algorithm = new CountRepeatingElements();
public Map<Object, AtomicInteger> countRepeatingElements(Object... elements) {
ConcurrentMap<Object, AtomicInteger> result = new ConcurrentHashMap<Object, AtomicInteger>();
for (Object element : elements) {
result.putIfAbsent(element, new AtomicInteger(0)); //useful method that exists only in concurrent maps
result.get(element).incrementAndGet();
}
return result;
}
public Map<Object, AtomicInteger> testCountRepeatingElements() throws Exception {
Map<Object, AtomicInteger> result = algorithm.countRepeatingElements("aaa", "bbb", "aaa", "ccc", "bbb", "aaa");
return result;
}
public static void main(String[] args) throws Exception {
Map<Object, AtomicInteger> result = algorithm.testCountRepeatingElements();
Set<Object> keys = result.keySet();
for (Object object : keys) {
System.out.println(object + " = " + result.get(object) );
}
}
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: java уникальные значения |
Конкурс по ФП |
import java.util.*;
import java.lang.*;
import java.io.FileNotFoundException;
class Main
{
public static TreeSet<Integer> normals = new TreeSet<Integer>();
public static TreeSet<Integer> mads = new TreeSet<Integer>();
public static List<Person> allpersons = new ArrayList<Person>();
public static List<Integer> listOfMad = new ArrayList<Integer>();
private class Person {
public Integer num;
public String mChar;
public TreeSet<Integer> list = new TreeSet<Integer>();
public TreeSet<Integer> diagnoz = new TreeSet<Integer>();
public boolean ismad;
public boolean isnormal;
public Person() {
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Integer integer : list) {
sb.append(", ").append(integer);
}
String result = "[" + num + "] " + mChar + " " + sb.toString();
return result;
}
public String printNote() {
String result = "Суждения о других :";
for (Integer integer : list) {
result = result + " ," + integer;
}
return result;
}
public String printDiagnoz() {
String result = "Суждения о Мне : ";
for (Integer integer : diagnoz) {
result += " ," + integer;
}
return result;
}
}
public List<Person> readData() throws FileNotFoundException {
Scanner fw = new Scanner(System.in);
while (fw.hasNextLine()) {
Person person = new Person();
String str = fw.nextLine();
String[] arr = str.split(": '");
person.num = Integer.parseInt(arr[0].trim());
arr = arr[1].split("',");
person.mChar = arr[0];
arr = arr[1].split(",");
for (int i = 0; i < arr.length; i++) {
try {
person.list.add(Integer.parseInt(arr[i].trim()));
} catch (NumberFormatException nfe) {
System.out.println("error" + person.num);
}
}
allpersons.add(person);
}
return allpersons;
}
public static int sign(Integer x) {
return x > 0 ? 1 : -1;
}
public static void printDiagnoz(int mad) {
int size = allpersons.size();
Person ismad = allpersons.get(mad - 1);
Integer madNum = ismad.num;
for (int i = 0; i < size; i++) {
Person next = allpersons.get(i);
for (Integer integer : next.list) {
if (madNum.equals(Math.abs(integer))) {
ismad.diagnoz.add(sign(integer) * next.num);
break;
}
}
}
}
public static boolean findMad(Integer personId, Integer doctor) {
Person person = allpersons.get(personId - 1);
TreeSet<Integer> madlist = person.list;
for (Integer integer : madlist) {
if (integer > 0) {
if (!listOfMad.contains(integer) && !integer.equals(doctor)) {
listOfMad.add(integer);
mads.add(integer);
}
} else {
if (mads.contains(Math.abs(integer))) {
return true;
}
normals.add(Math.abs(integer));
}
}
return false;
}
public static void printPicture(int col) {
int i = 0;
System.out.println("");
for (Integer integer : mads) {
i++;
if (i % col == 0) {
System.out.println("");
}
System.out.print(allpersons.get(integer - 1).mChar);
}
List<Integer> list = new ArrayList<Integer>();
list.addAll(normals);
Collections.reverse(list);
for (Integer integer : list) {
i++;
if (i % col == 0) {
System.out.println("");
}
System.out.print(allpersons.get(integer - 1).mChar);
}
}
public static void fillMass(Integer doctor, Integer mad) {
int size = allpersons.size();
mads.clear();
normals.clear();
mads.add(mad);
listOfMad.clear();
listOfMad.add(mad);
for (int j = 0; j < listOfMad.size(); j++) {
int mun = listOfMad.get(j);
Person person = allpersons.get(mun - 1);
TreeSet<Integer> madlist = person.list;
for (Integer integer : madlist) {
if (integer > 0) {
if (!listOfMad.contains(integer) && !integer.equals(doctor)) {
listOfMad.add(integer);
mads.add(integer);
}
} else {
normals.add(Math.abs(integer));
}
}
}
}
public static void main (String[] args) throws java.lang.Exception
{
long time = System.currentTimeMillis();
Main Fd = new Main();
Fd.readData();
int madd = 405;
printDiagnoz(madd);
Person ismad = allpersons.get(madd - 1);
System.out.println(ismad.printDiagnoz());
System.out.println(ismad.printNote());
//
int size = allpersons.size();
boolean isDoctor = false;
int dictorId = -1;
for (int i = 1; i <size; i++) {
mads.clear();
normals.clear();
mads.add(madd);
listOfMad.clear();
listOfMad.add(madd);
boolean isMad = false;
for (int j = 0; j < listOfMad.size(); j++) {
isMad = findMad(listOfMad.get(j), i);
if (isMad || (mads.size() + normals.size()) > size) {
if(isMad) {
isDoctor = true;
dictorId = listOfMad.get(j);
}
isMad = false;
break;
}
}
int sum = mads.size() + normals.size() + 1;
if (!isMad && sum == size) {
System.out.println(" doctor x: " + i);
break;
}
if(isDoctor){
System.out.println(" Doctor X: " +dictorId);
break;
}
}
System.out.print("time : " + (System.currentTimeMillis() - time) + " ms");
fillMass(dictorId, madd);
printPicture(31);
mads.clear();
normals.clear();
listOfMad.clear();
}
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: Конкурс по ФП сентябрь java |
javascript window.opener return json |
|
Метки: javascript window.opener json |
Immunity Products |
|
Метки: Immunity Products java |
регулярные выражения regexp isURL |
String regc = "((https?|ftp|file)://([a-zA-Z0-9+&@#%?=~_|!:,.;]*)([a-zA-Z0-9+&@#%?/=~_|!:,.;]*)[^ ])";
String regx ="((https?|ftp|file)://[^ ]{3,})";
String regb = "((ftp|http|https)://(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(/|/([\\w#!:.?+=&%@!\\-\\/]))?)";
* This source code was highlighted with Source Code Highlighter.
|
Метки: regexp isURL |
... |
|
Метки: бизнес идея |
скачать файлы из контакта |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vkphoto.english;
import java.io.File;
import java.io.FileWriter;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONException;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.VkontakteApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
/**
*
* @author isalnikov
*/
public class EnglishPhoto {
/**
* @param args the command line arguments
*/
private static final String NETWORK_NAME = "Vkontakte.ru";
//private static final String PROTECTED_RESOURCE_URL_GET = "https://api.vkontakte.ru/method/photos.get";
private static final String PROTECTED_RESOURCE_URL_GET = "https://api.vkontakte.ru/method/photos.getAll";
// private static final String PROTECTED_RESOURCE_URL_GET = "https://api.vkontakte.ru/method/photos.getAlbums";
private static final Token EMPTY_TOKEN = null;
public static void main(String[] args) throws JSONException, Exception
{
final String clientId = "";
final String apiSecret = "";
OAuthService service = new ServiceBuilder()
.provider(VkontakteApi.class)
.apiKey(clientId)
.apiSecret(apiSecret)
.scope("notify,friends,wall,audio,notes,messages,offline,photos,groups") // replace with desired scope
.callback("http://api.vkontakte.ru/blank.html") //для приложения
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Authorization URL
System.out.println("Fetching the Authorization URL...");
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize Scribe here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = null;
request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL_GET);
//-36775085
request.addBodyParameter("owner_id", "-36775085");
// request.addBodyParameter("gid", "36775085");
// request.addBodyParameter("aid", "158956214");
request.addBodyParameter("count", "100");
request.addBodyParameter("offset", "900");
// request.addBodyParameter("aid", "161756102");
// request.addBodyParameter("aid", "161750509");
// request.addBodyParameter("aid", "161642875");
// request.addBodyParameter("aid", "161642730");
// request.addBodyParameter("aid", "156323580");
// request.addBodyParameter("aid", "158956214");
// request.addBodyParameter("aid", "158956214");
//
// request.addBodyParameter("filter", "owner");
// request.addBodyParameter("filter", "owner");
// HD Иpинa Шeйк
// request.addBodyParameter("count", "100");
// request.addBodyParameter("offset", "410");
//gr
//request.addBodyParameter("gid", "22786271");
// request.addBodyParameter("aid", "140908579");
service.signRequest(accessToken, request);
Response response = null;
response = request.send();
System.out.println(response.getCode());
System.out.println(response.getBody());
NewMain.setResource(response.getBody());
}
}
* This source code was highlighted with Source Code Highlighter.
|
|
qsort |
//алгоритм на языке java
public static void qSort(int[] A, int low, int high) {
int i = low;
int j = high;
int x = A[(low+high)/2];
do {
while(A[i] < x) ++i;
while(A[j] > x) --j;
if(i <= j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
i++; j--;
}
} while(i <= j);
if(low < j) qSort(A, low, j);
if(i < high) qSort(A, i, high);
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: sort |
netbeans gwt gxt |
|
Метки: netbeans gwt gxt |
How to divide a number by 3 without using *, /, +, -, %, operators? |
//java
public static void main(String[] args) {
// TODO code application logic here
int a = divBy3(15003);
System.out.println(a);
}
public static int divBy3(long a) {
a <<= 30;
for (int i = 2; i <= 32; i <<= 1) {
a = add(a, a >> i);
}
return (int) (a >> 32);
}
public static long add(long a, long b) {
long carry = (a & b) << 1;
long sum = (a ^ b);
return carry == 0 ? sum : add(carry, sum);
}
}
//C++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE * fp=fopen("temp.dat","w+b");
int number=12346;
int divisor=3;
char * buf = malloc(number);
memset(buf,0,number);
fwrite(buf,number,1,fp);
rewind(fp);
int result=fread(buf,divisor,number,fp);
printf("%d / %d = %d", number, divisor, result);
free(buf);
fclose(fp);
return 0;
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: How to divide a number by 3 without using |
Задача лифты |
|
Метки: Задача лифты |
javascript NaN |
function isNum(v) {
return typeof v === 'number' && isFinite(v);
}
|
Метки: javascript NaN |
Нахождение пары ближайших точек |
|
Метки: Нахождение пары ближайших точек математика программирование |
javascript прокрутка городов |
|
Метки: javascript карусель |
LinkedList |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>JSP Page</title>
</head>
<body>
<script>
function LinkedList() {
this._length = 0;
this._head = null;
}
LinkedList.prototype = {
add: function (data){
//create a new node, place data in
var node = {
data: data,
next: null
},
//used to traverse the structure
current;
//special case: no items in the list yet
if (this._head === null){
this._head = node;
} else {
current = this._head;
while(current.next){
current = current.next;
}
current.next = node;
}
//don't forget to update the count
this._length++;
},
item: function(index){
//check for out-of-bounds values
if (index > -1 && index < this._length){
var current = this._head,
i = 0;
while(i++ < index){
current = current.next;
}
return current.data;
} else {
return null;
}
},
remove: function(index){
//check for out-of-bounds values
if (index > -1 && index < this._length){
var current = this._head,
previous,
i = 0;
//special case: removing first item
if (index === 0){
this._head = current.next;
} else {
//find the right location
while(i++ < index){
previous = current;
current = current.next;
}
//skip over the item to remove
previous.next = current.next;
}
//decrement the length
this._length--;
//return the value
return current.data;
} else {
return null;
}
}
//more methods here
};
var list = new LinkedList();
list.add("red");
list.add("orange");
list.add("yellow");
console.log(list.item(1));//"orange"
console.log(list.remove(1));
console.log(list.item(1));
</script>
</body>
</html>
* This source code was highlighted with Source Code Highlighter.
|
Метки: LinkedList |
javascript cookie |
function setCookie(name, value, expires, path, domain, secure) {
if (!name || !value) return false;
var str = name + '=' + encodeURIComponent(value);
if (expires) str += '; expires=' + expires.toGMTString();
if (path) str += '; path=' + path;
if (domain) str += '; domain=' + domain;
if (secure) str += '; secure';
document.cookie = str;
return true;
}
function getCookie(name) {
var pattern = "(?:; )?" + name + "=([^;]*);?";
var regexp = new RegExp(pattern);
if (regexp.test(document.cookie))
return decodeURIComponent(RegExp["$1"]);
return false;
}
function deleteCookie(name, path, domain) {
setCookie(name, null, new Date(0), path, domain);
return true;
}
* This source code was highlighted with Source Code Highlighter.
|
Метки: javascript cookie |