juan_gandhi: (VP)
2013-10-10 12:19 pm
Entry tags:

if you think Java does not have problems with malloc...

java(81184,0xac87ca28) malloc: *** mmap(size=2097152) failed (error code=12)
*** error: can't allocate region
juan_gandhi: (VP)
2013-10-09 01:12 pm
Entry tags:

μWTF - джава и пустота

void get(java.lang.String s);
juan_gandhi: (VP)
2013-02-20 01:51 pm
Entry tags:

dumping stuff from stream to file fast

      val out = new FileOutputStream(myFile).getChannel
      val in: InputStream = sampleResourcePdfBSBCTX.openStream
      val ch = Channels.newChannel(in)
      try {
        while (true) {
          val nBytes = in.available
          out.transferFrom(ch, out.position, nBytes)
          out.position(out.position + nBytes)
        }
      } finally { out.close() }
      val text = PDF.extractTextFromImagesHiddenInPdf(pdf)
      text contains "Claim No.: 30l8507l5lSOX" mustBe true
    }
  }
juan_gandhi: (VP)
2013-01-10 08:55 am
Entry tags:

какой интересный баг был

В джаве, как известно, (почти) всю жизнь String.substring не копировала контент, а создавала новую строку со ссылкой на участок в старой.

Ну и теперь представьте, у вас какие-нибудь большие объекты проезжают через программу, типа веб какой-нибудь, а вы находите там какую-нибудь подстроку, типа stock symbol, и складываете куда-нибудь в кеш, а остальное думаете, что выкидываете. А оно не выкидывается, потому что ваши четыре буквы ссылаются на большое поле в очень большом объекте. Упс, OutOfMemory. details.

В седьмой джаве пофиксено, но теперь всякий код, который расчитывает, что подстроки дёшевы, грубо обламывается. Представьте, что мы выдёргиваем не символ, а html body, и, надеясь, что это дёшево, не заботимся ни о чём таком, тем более, что уже пять лет как работает же.
juan_gandhi: (Default)
2013-01-02 10:47 am

no closures in java 8 actually

https://groups.google.com/forum/?fromgroups=#!topic/scala-user/nC263xUiaQo

The same dumb stupid Java where you can only pass a final into an internal class...

"
List<Integer> ints = new ArrayList<>(); 
ints.add(1); 
ints.add(2); 
ints.add(3); 

int sum = 0; 
ints.forEach(i -> {sum += i;}); 

The compiler error is: "value used in lambda expression should be effectively final". I got some bad suspicion and tried whether this compiles:
int sumArray[] = new int[] { 0 }; 
ints.forEach(i -> {sumArray[0] += i;}); 

This did compile.
"
juan_gandhi: (VP)
2012-12-10 10:18 pm
Entry tags:

Reader and Maybe, comments

1. [livejournal.com profile] sassa_nf noted that in Haskell actually Reader composes with any monad. That's a pleasant surprise; and this happens due to the fact that any monad is strong in Haskell. Yes, with the same arguments as I used before, a composition of Reader with any monad is still a monad.

2. The proof of monadicity of Reader and Maybe (or any other strong monad).
I tried; it is long and boring, and there's nothing unusual there, just apply diagonals and eval, and use Yoneda lemma. No big deal, boring.

3. What is eval actually?
3.1. Formal definition.
eval: A × BA → B

is defined via adjointness of functors X- and -×Y, it comes from idA: A → B.

3.2. Informal definition.
Given (a,f) ∈ A × BA, eval(a,f)=f(a).

4. How does it all look in Java?
Given
interface Maybe<X> {
  X getOrElse(X alt);
  <Y> Maybe<Y> map(Function<X,Y> f);
  <Y> Maybe<Y> flatMap(Function<X,Maybe<Y> f);
}

with two implementation classes, Some and None (having appropriate factories),
and
abstract class Reader<E,X> {
  <X,Y> Reader<E,Y> map(Function<X,Y> f);
  <X,Y> Reader<E,Y> flatMap(Function<X,Reader<E,Y> f);
}

with a factory
  <E,X> Reader<E,X> reader(X x) { return new Reader<E,X){...}; } // constant x

and provided the implementations follows monadic laws,

We can define
class<E,X> PartialReader<E,X> extends Reader<E,Maybe<X>>{
  <X,Y> PartialReader<E,Y> map(Function<X,Y> f) { ... }
  <X,Y> PartialReader<E,Y> flatMap(Function<X,Reader<E,Maybe<Y> f) { ... }
}


and a factory
  <E,X> PartialReader<E,X> pr(X x) { return new PartialReader<E,X){...}; } // constant Some(x)


Now this PartialReader satisfies monadic laws.

I wonder, do I need to define the guts of the methods? I could, no request.
juan_gandhi: (VP)
2012-12-08 09:29 pm
Entry tags:

So, can we compose Reader and Maybe?

I believe we can.

Generally speaking, say, we have two monads, T and U; their composition T ∘ U is a functor which is not always a monad. Unit is okay, but multiplication, T ∘ U ∘ T ∘ U → T ∘ U does not always exist. It would exist if the two monads commuted, that if, if we had U ∘ T → T ∘ U, which is also known as traversal of U over T; in case U comes from a monoid, this is the famouse "map/reduce".

I was working on a simple example in Java programming language, say, take Reader monad and Maybe monad, the latter also known as Option in Scala and in various Java libraries. It is almost obvious that if we have a Maybe wrapped into a Reader, it cannot be naturally transformed into Reader wrapped into a Maybe.

Maybe in Java can be thought of as a function that may throw some kind of exception, and we don't care which, just catch it (and log it, that's what Java people do with exceptions).

Reader in Java can be represented as "dependency injection" - we have a function that is supposed to return something, but its behavior depends on some external circumstances unknown to client code. This is different from State, an example of which is a Random Numbers Generator; with "dependency" we are tied to the same environment during the lifetime of the program.

For the utmost simplicity, let's imagine that we have only two possible "environment values", say, DEBUG, which is either TRUE or FALSE.

So, in this case, what the client thinks of as a function: X → Y, in our Reader is actually a function: X → Y2 whereby we potentially produce two values, one for DEBUG=TRUE and another for DEBUG=FALSE.

If we deal with Maybe, what a client sees as a function: X → Y is actually function: X → 1+Y, where failures map values into this 1, which in Java is represented via null.

Okay.

Now one composition is (1 + Y)2 == 1 + 2×Y + Y2, and the other is 1 + Y2.

We can easily embed the second one into the first one, but there's no general natural way to transform the first one to the second one; what will we do with the two instances of 1×Y? Unless we have Y as an algebra over Maybe, that is, a natural transformation 1 → Y.

Nevertheless, I will show that the composition of Maybe ∘ Reader is a monad.

First, let's generalize Reader to a dependency on a certain type E of "environment: Reader<E>.

So, Reader amounts to having a functor X ↦ XE, where unit X → XE amounts to constant, and multiplication (XE)E → XE is dual to diagonal Δ E → E×E, that is, XΔ.

Now, can we naturally transform Reader(Maybe(Reader(Maybe(X)))) to Reader(Maybe(X))? Not only naturally, but with all the monadic properties of multiplication (unit and associativity, that is).

We have (1 + (1 + X)E)E, and we need to produce (1 + X)E

This is dual to (thanks to Yoneda Lemma) having a good transformation
E × (1 + (1 + X)E)E → (1 + X)

Let's throw in Δ E → E×E, and build
E × (1 + (1 + X)E)E → E × E × (1 + (1 + X)E)E → (1 + X)

Using eval: E × AE, have
E × E × (1 + (1 + X)E)E → E × (1 + (1 + X)E)

So it would be enough to have a good
E × (1 + (1 + X)E) → (1 + X)
which amounts to having

E × 1 + E × (1 + X)E) → (1 + X)

Which is obvious: the first component maps to 1, the second is eval again.

That's it.

Questions? Errors? Remarks? Suggestions.

(One question is how come Java types are not Maybe-algebras, they are, are not they?)
juan_gandhi: (Default)
2012-09-27 02:07 pm

немножко хайбернейта (aka шозанах)

		catch ( RuntimeException re ) {
			log().info( "could not bind value '" + nullSafeToString( value ) + "' to parameter: " + index + "; " + re.getMessage() );
			throw re;
		}
		catch ( SQLException se ) {
			log().info( "could not bind value '" + nullSafeToString( value ) + "' to parameter: " + index + "; " + se.getMessage() );
			throw se;
		}
......
	public String nullSafeToString(Object value) throws HibernateException {
		return value == null ? null : toString( value );
	}

.......
	public Object stringToObject(String xml) throws Exception {
		return xml;
	}

	public String toString(Object value) {
		return (String) value;
	}

	public Object fromStringValue(String xml) {
		return xml;
	}
juan_gandhi: (Default)
2012-08-14 12:01 pm
Entry tags:

new stuff

function New(name) { return java.lang.Class.forName(name).newInstance() }

function newList() { return New("java.util.LinkedList") }
juan_gandhi: (Default)
2012-08-08 07:21 pm
Entry tags:

пока сам не понимаю, что делаю

Пишу на джавасприпте кусочки, которые через http post бросаю своему серверу, там рино их исполняет, вызывая мои методы на скале, каковые разговаривают с другим сервером и переформатируют варварские данные в простые мапы; что-то тут лишнее, но я пока не понял, что.

Главное, что идея писать эту хрень на моём любименьком джаваскрипте как-то очень медленно вползает в голову.

Только что вот написал функцию на джаваскрипте, которая превращает скальный список в джаваскриптовый массив (ну вы в курсе, в джаваскрипте на самом-то деле массивов нет).

Обожаю этот постмодерновый стиль. Три языка (четыре - там ещё shell). Ещё один - и сгожусь в члены правительства ПМР.
juan_gandhi: (Default)
2012-08-07 11:57 am
Entry tags:

а вы видали такое?

Стартую сервер, гляжу - а не слушает меня на порту. Шо за. В дебагере поставил точку - не заходит.
Заменил весь thread на new Thread("wtf") { def run { println("I'm here") } - ни слуху ни духу.
Поставил в main рефренс на сервер (а в сервере на thread) - гляжу, а у этого threada (Шишков прости) состояние stillborn.

Такие дела.

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

В интернетах глухо пишут о баге в jvm.

Но это что значит, всякий thread надо проверять после запуска, жив ли, мол, ты, милок?

Между прочим, недавно исполнилось 15 лет как я с джавой трахаюсь, а такое первый раз вижу.
juan_gandhi: (Default)
2012-04-11 01:54 pm
Entry tags:

interop

    public Props(Tuple2<String, String>... tuples) {
        map = new HashMap<String, String>();
        for (Tuple2<String, String> t: tuples) {
            map.put(t._1(), t._2());
        }
    }


Это у меня есть такой джавный класс, Props, и я теперь в этом проекте кусочеки на Скале пишу, так чтоб конструктор вызывать через new Props(USER->"sonoio", PASSWORD->"пароль")
juan_gandhi: (Default)
2012-03-18 01:35 pm
Entry tags:

SKI in Java, by Tony Morris

src
interface Lam<X, Y> {
  Y apply(X x);
}
 
// http://en.wikipedia.org/wiki/SKI_combinator_calculus
class SKI {
  public static <A, B, C> Lam<Lam<A, Lam<B, C>>, Lam<Lam<A, B>, Lam<A, C>>> s() {
    return new Lam<Lam<A, Lam<B, C>>, Lam<Lam<A, B>, Lam<A, C>>>() {
      public Lam<Lam<A, B>, Lam<A, C>> apply(final Lam<A, Lam<B, C>> f) {
        return new Lam<Lam<A, B>, Lam<A, C>>() {
          public Lam<A, C> apply(final Lam<A, B> g) {
            return new Lam<A, C>() {
              public C apply(final A a) {
                return f.apply(a).apply(g.apply(a));
              }
            };
          }
        };
      }
    };
  }
 
  public static <A, B> Lam<A, Lam<B, A>> k() {
    return new Lam<A, Lam<B, A>>() {
      public Lam<B, A> apply(final A a) {
        return new Lam<B, A>() {
          public A apply(final B b) {
            return a;
          }
        };
      }
    };
  }
 
  public static <A> Lam<A, A> i() {
    return SKI.<A, Lam<A, A>, A>s().apply(SKI.<A, Lam<A, A>>k()).apply(SKI.<A, A>k());
  }
}
juan_gandhi: (Default)
2012-02-11 09:06 am
Entry tags:

две недели борьбы ушли не зря

загадка была такая, что вроде в продакшене всё у нас с базами в порядке, а когда я присобачил в фреймуорк чтобы селф-тесты бегали, то эти селф-тесты позорно рушились, причём явление происходило не сразу, а коррелировало с какими-то затратами процессора, с ресурсами памяти...

Короче, я придумал этот аспект, Health.check("vot tut pocheshite pozhaluista");, но он не особо помогал. Постепенно локализовал - после queue.wait() вдруг база переставала работать (а данные записывались только частично - но они каждый в своей транзакции). Замена на Thread.sleep() убирала эффект.

Что делал - по совету присутствующего товарища [livejournal.com profile] magictoken понатыкал логов в постгрес; ну и свои логи тоже.

Выяснились интересные вещи:
- записи перестают попадать в таблицу после queue.wait();
- лог postgres показывает, что транзакция открывается, данные приходят, транзакция закрывается.
- если не менять код, то наблюдается очень стабильное поведение.

Короче, что выяснилось. В сервере в разных потоках бегают сразу два серверных приложения. Они используют две разные базы данных. В принципе, когда мы получили задание, то в глобальный синглтон складывается рефренс на фабрику "энтити менеджеров" (каждый раз, когда я вижу в коде слово "менеджер", моя рука тянется к кнопке delete). Как только наше приложение садится подождать, пока на его мессагу ответят, просыпается другое приложение (могло бы на другом процессоре работать), и подставляет свой контекст. Мы получаем ответ, просыпаемся, продолжаем движение - складывая наши данные уже в другую базу.

Классический пример ахинеи. Я такую чушь ещё в фортране видал, и в си видал... В Борланде в одной интересной программе пара файлов передавалась в виде имён и рукояток, по иерархии вызовов; иногда, имея имя файла, мы открывали файл снова и передавали новую рукоятку; иногда имена складывалиь в глобальную переменную "имя открытого файла"; таких переменных было несколько - большая программа-то, все хотят а) кешировать, б) делиться знаниями.

Ну и теперь, по какой причине я так долго трахался с этой фигнёй? А отвык на самом деле.

Ну всё, щас я им всё поперелопачу. И логов присандалю, и ООП повпендюриваю, инкапсуляция, адхок полиморфизм, народность.

П.С. Кстати, и в реале менеджеры выполняют похожую роль, кешируют информацию и делятся ею; через пару лет у такого голова полна суеверий и сплетен, и сделать что-либо толковое можно только если ему не говорить. Ну если только он не лезет в твою компетенцию. Инкапсуляция.

Причём, в роли таких "кеширующих менеджеров" вполне может выступать и коллектив коллег (брр, это я Гугл вспоминаю, где мне не давали в джаваскрипте замыкания писать, табулировать списки параметров - аски арт запрещён, а также у них не было нигде места на серверах под 21к моего скрипта).
juan_gandhi: (Default)
2012-01-23 06:24 pm
Entry tags:

getting rid of fucking exceptions

  def tryOr[T](message: String)(action: => T) = {
    try {
      Some(action)
    } catch {
      case e: Throwable => {
        Log.error(message, e)
        None
      }
    }
  }


using like

tryOr("Oi-vei, could not find...") { database.findUserNamed("Captain Nemo") }


Could use Either as well, I don't know.
Gradually morphing from Java.
juan_gandhi: (Default)
2012-01-16 03:46 pm
Entry tags:

ever saw this?

    public  T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
	System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }


That's from Java's ArrayList class.
juan_gandhi: (Default)
2011-12-07 03:25 pm
Entry tags:

functional java

Just discovered that fj package, popular in our company, is coming from Tony Morris, Runar Bjarnason and the rest; that explains how come it is so incredibly cool, so unjava... and also it kind of obsoletes the idea of using Google Guava. Way too advanced.

Wow, it's cool, is not it?

(Yes, I happen to be using Java from time to time.)
juan_gandhi: (Default)
2011-11-30 05:22 pm
Entry tags:

stuff


    private static StackTraceElement whereami(int i) {
        return Thread.currentThread().getStackTrace()[i];
    }

    public static int __LINE__() {
        return whereami(3).getLineNumber();
    }

    public static String __FILE__() {
        return whereami(3).getFileName();
    }


e.g.
        SysLog.debug("this is %s #%d", "message", 42);
        assertEquals("DEBUG  (" + __FILE__() + ":" + (__LINE__() - 1) + ") - this is message #42", log.toString());
juan_gandhi: (Default)
2011-11-30 12:50 pm
Entry tags:

славный наброс

пусть ярость благородная вскипает как волна

"Right now at Yammer we're moving our basic infrastructure stack over to Java"

Here's what Josh Suereth writes on this topic.