wtf

Mar. 23rd, 2021 09:04 pm
juan_gandhi: (Default)
private val digest = MessageDigest.getInstance("MD5")
def md5(message: String): String = {
val bytes = message.getBytes("UTF-8")
digest.reset()
val code1 = ("" /: digest.digest(bytes))(_ + encode(_))
digest.reset()
val code2 = ("" /: digest.digest(bytes))(_ + encode(_))
digest.reset()
val code3 = ("" /: digest.digest(bytes))(_ + encode(_))
code3
}

gives me
message = "a"
bytes = {byte[1]@3305} [97]
code1 = "4k1z3161463m1w5h4f5gn635a4j1u6i"
code2 = "c5d39555c6p524o1d5f496a2x3b122p"
code3 = "n2n4mb6v1j4g2p2s4p3c182k4aq4y"

P.S. THE ANSWER: it should be synchronized.
juan_gandhi: (Default)
У нас на работе новый стайл чекер запретил пустые блоки.

Типа

public abstract class Something {
...
  void enableFeature() {} // by default we don't do anything
...
}
So now I write

public abstract class Something {
  private Boolean dummy = false;
  void enableFeature() {
    dummy = true;
  } // by default we don't do anything
...
}
Нет, я слышал про интерфейсы, но зацените задачу девелоперам - внезапно таки introduce interfaces, по всей большой кодобазе.

wtf

Sep. 22nd, 2017 02:48 pm
juan_gandhi: (Default)
scala> new java.util.Date(Long.MinValue)
res1: java.util.Date = Sun Dec 02 08:47:04 PST 292269055

scala> new java.util.Date(Long.MaxValue)
res2: java.util.Date = Sat Aug 16 23:12:55 PST 292278994

scala> new java.util.Date(Long.MinValue >> 16)
res14: java.util.Date = Thu Apr 06 13:14:04 PST 2491

μwtf

Jan. 5th, 2017 06:45 am
juan_gandhi: (Default)
double _mean, _sigma; //sum(X) and sum(X^2) for non-NA values

juan_gandhi: (Default)
So, there's a "flag" in "config" that tells whether some data should be exported or not:
dl._export_weights_and_biases

Some responsible guy decided to test both cases, with export and without.
So, in the test case he adds:


      dl._export_weights_and_biases = RandomUtils.getRNG(fnametrain.hashCode()).nextBoolean();


The commit comment was “Test both true and files for export_weights_and_biases”

Now, wtf is fnametrain? It's the name of the file with test data.

We take the file name. Calculate its hash code. Seed it into an RNG. And then take the first bit generated.

I'm afraid a lot of "data science" is like this:
- Make our code so complicated that nobody can make any sense out of it.
- Profit.
 
 
 
juan_gandhi: (VP)
/**
 * A factory for generating new instances of Date.  You can create
 * factories for each kind of thing you want to vend in your application.
 * An example is a payment gateway.  You can change the default implementation,
 * or override the default implementation on a session, request or current call
 * stack basis.
 */
object DependencyFactory extends Factory {
  implicit object time extends FactoryMaker(Helpers.now _)

  /**
   * objects in Scala are lazily created.  The init()
   * method creates a List of all the objects.  This
   * results in all the objects getting initialized and
   * registering their types with the dependency injector
   */
  private def init() {
    List(time)
  }
  init()
}

code wtf

Nov. 23rd, 2015 04:21 pm
juan_gandhi: (VP)
      } catch {
        case t: Throwable => {
          Future.successful(errorConv(t).failure[Success])
        }
      }


(no, it was not written in our company, it's stolen from some opensource)
juan_gandhi: (VP)
So, I kind of discovered that the stuff I'm doing with my Result class looks suspiciously close to linear logic, e.g., in LL we have !(A&B)≡!A⊗!B, and I have Good(a) <*> Good(b) == Good((a,b)).

Moving on.

Similarly, there's some connection between Good[Either[A,B]] and Good(a:A) orElse Good(b:B).

Actually, what I have, it seems to be a coaffine logic, but well, who cares right now. We will see.

"If Γ,Δ⊢Θ, then Γ,!A,Δ⊢Θ, for any A " maps to

Good(a) foreach (f()) is the same as f().

"If Γ,!A,!A,Δ⊢Θ, then Γ,!A,Δ⊢Θ" maps to
Good(Good(a)).flatten == Good(a)

Not everything works. But is not it weird.

wtf

Jul. 15th, 2014 09:53 pm
juan_gandhi: (VP)
IntelliJ 13 with Scala plugin
Screen Shot 2014-07-15 at 2.00.25 PM
(also, failed to upload this image to their bug reporting site)

Screen Shot 2014-07-15 at 9.52.26 PM
(atlas oreilly editor)
juan_gandhi: (VP)
Just finished watching this film. Pretty good! Kind of ready to quote the evil doctor.
I would not watch it 6 months ago; now it's so timely, wow.

Also, fyi, in summer of 1941 there were 78000 Jews in Berlin.

Kind of explains something in human nature.

scala wtf

Mar. 24th, 2014 05:18 pm
juan_gandhi: (VP)
scala> val m = Map("a"->1, "b"->2, "c"->2)
m: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 2)

scala> val m1=m map {case (x,y) => (y,x)}
m1: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> c)
juan_gandhi: (VP)
java(81184,0xac87ca28) malloc: *** mmap(size=2097152) failed (error code=12)
*** error: can't allocate region
juan_gandhi: (VP)
  implicit def f2tof1[X,Y,Z](f2: Function2[X,Y,Z]) = (xy:(X,Y)) => f2(xy._1, xy._2)


Update: f2.tupled
juan_gandhi: (VP)
Сидит Андрей Петрович Ощепков на крутом бережку Енисея и читает книжку "Гильбертовы Пространства в Задачах и Решениях"; подходит мужик, глядит на обложку, и спрашивает Андрея Петровича: "а шо це за параша, Гильбертовы Пространства?" 
/Эпиграф/

Итак, мой предыдущий пост я практически объявляю полной фигнёй.

Кроме одной фразы - type class - это класс типов. Остальное фигня.

Как я понимаю, класс типов можно определить а) параметрически: List[T] - это класс списков с элементами типа T; в хаскеле для этого есть лихой термин type family b) через уравнение:
class Eq a ...; в скале это можно задать приблизительно.

Сегодня Дэвид Анджеевски на скальном митапе вообще задвинул термин type class pattern, и на мой вопрос, не знает ли он формального определения тайпкласса сказал, что нет, не знает.

Вот ещё линки.
typeclassopedia, by John Kodumal, Atlassian - слов и примеров много, определения нет.
что сказал Дебасиш - это типа скорее паттерн тоже
Stackoverflow: какая польза от тайпклассов? ("а сёдла на них есть?")
Moors, Pissens, Oderski, "Generics of Higher Kind" - тут скорее намёки на тему тайпклассов, наряду с техничным рассуждением на тему шо в скале уже таки есть
"oop vs typeclasses" - по мне так скорее философия, с намёками, что, э, может быть таки тайпклассы - это параметризованные типы, не?

gentle haskell - здесь объясняют, что как раз не, объявляем через уравнения, а определяем или параметрически, или адхок.

Ну вы поняли, да? Я не понял. Только вижу, что тайпклассы - это что-то вроде многообразий, и не пора ли уже просто откровенно пойти пошукать шо за гомотопическая теория типов такая, и не отвечает ли она на вопросы.

Надеюсь на продуктивную дискуссию.
juan_gandhi: (Default)
		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)
сижу балуюсь с удалёнными артистами (remote actors)
чё у меня есть - а линух, ну
p
И вот потыкал lsof -i :9000, взял пид, сказал kill -9 этот самый пид

В той скале, что бежала слушала на 9000, вижу вот такой концептуальный текст:


scala> /home/vlad/scala-2.9.2/bin/scala: line 161: 5766 Killed
"${JAVACMD:=java}" $JAVA_OPTS "${java_args[@]}" ${CPSELECT}${TOOL_CLASSPATH} -Dscala.usejavacp=true -Dscala.home="$SCALA_HOME" -Denv.emacs="$EMACS" $CYGWIN_JLINE_TERMINAL scala.tools.nsc.MainGenericRunner "$@"

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

June 2025

S M T W T F S
1 2345 6 7
8 9 10 11 121314
15161718 1920 21
22232425262728
2930     

Syndicate

RSS Atom

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 26th, 2025 07:05 am
Powered by Dreamwidth Studios